我目前可以讀取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