我目前可以读取XML文件:,读取XML文件,JAXB
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer id="100" r="q">
<datas>
<data>
<age>29</age>
<name>mky</name>
</data>
</datas>
</customer>
使用Customer类:
@XmlRootElement
public class Customer {
String name;
String age;
String id;
String r;
@XmlAttribute
public void setR(String R) {
this.r = R;
}
/etc
}
我决定延长XML文件,以支持多个客户:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customers>
<customer id="100" r="q">
<age>29</age>
<name>mky</name>
</customer>
<customer id="101" r="q">
<age>29</age>
<name>mky</name>
</customer>
</customers>
然后我遇到了一些麻烦,试图阅读此。
我尝试添加一个客户等级:
@XmlRootElement
public class Customers{
private ArrayList<Customer> customers;
public List<Customer> getCustomers() {
return customers;
}
@XmlElement
public void setCustomers(ArrayList<Customer> customers) {
this.customers = customers;
}
}
然后尝试与打印:
try {
File file = new File("/Users/s.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customers.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Customers c = (Customers) jaxbUnmarshaller.unmarshal(file);
System.out.println(c.getCustomers());
} catch (JAXBException e) {
e.printStackTrace();
}
}}
但我发现了一个空值,试图打印此。有人能告诉我如何阅读第二个XML文件吗?
尝试将'customers'属性的类型从'ArrayList'更改为'List '。 (还没有尝试过,但至少我读过的每个例子都使用'List',如果我从xsd文件生成代码,它也使用'List') –
fabian
[如何使用JAXB读取XML文件?] http://stackoverflow.com/questions/12053379/how-to-read-an-xml-file-with-jaxb) – malat