我当前可以读取 xml 文件:
<?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>
使用客户类:
@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
类更改为
@XmlRootElement(name = "customers")
class Customers {
private List<Customer> customers;
public List<Customer> getCustomers() {
return customers;
}
@XmlElement(name = "customer")
public void setCustomers(List<Customer> customers) {
this.customers = customers;
}
}
您不希望 XML 元素的 get/set 方法之间出现不匹配。如果一个返回 ArrayList,另一个应该接受 ArrayList 参数。对于 List
也是如此(这只是一个很好的做法)。
关于java - 使用 JAXB 读取 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23206265/