jaxb想直接解析出list对象, 不用在list对象上再去包装一层对象
首先定义一个通用的包装对象
import java.util.*;
import javax.xml.bind.annotation.XmlAnyElement;
public class Wrapper
{
private List
items;
public Wrapper() {
items = new ArrayList
(); }
public Wrapper(List
items) { this.items = items;
}
@XmlAnyElement(lax=true)
public List
getItems() { return items;
}
}
然后是我们的xml
java类
@XmlRootElement(name="Item")
public class Item {
private String item;
private boolean needData;
private List
books;
@XmlAttribute(name = "item")
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
@XmlAttribute(name = "needData")
public boolean isNeedData() {
return needData;
}
public void setNeedData(boolean needData) {
this.needData = needData;
}
@XmlElements(value = { @XmlElement(name = "Book", type = Book.class) })
public List
getBooks() { return books;
}
public void setBooks(List
books) { this.books = books;
}
}
@XmlRootElement(name="Book")
public class Book {
private String name;
@XmlAttribute(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
jaxb代码
private static
List unmarshal(javax.xml.bind.Unmarshaller unmarshaller, Class
clazz, String xmlLocation) throws JAXBException { StreamSource xml = new StreamSource(xmlLocation);
Wrapper
wrapper = (Wrapper ) unmarshaller.unmarshal(xml, Wrapper.class).getValue();
return wrapper.getItems();
}
public static
List parseXmlToList(Class topLevelClass, String xmlLocation) throws Exception { JAXBContext jc = JAXBContext.newInstance(Wrapper.class,topLevelClass);
// Unmarshal
Unmarshaller unmarshaller = jc.createUnmarshaller();
List
list = unmarshal(unmarshaller, topLevelClass, xmlLocation); return list;
}
最后是客户端代码
List
- addresses = parseXmlToList(Item.class, "WardCheck.xml");
System.out.println(addresses);
System.out.println(addresses.get(0).getItem());
List
list = addresses.get(0).getBooks(); System.out.println(list.size());
System.out.println(addresses.get(0).getBooks().get(0).getName());
来自link http://blog.bdoughan.com/2012/11/creating-generic-list-wrapper-in-jaxb.html