我想获取ID,年龄,客户节点中的名称和listType,以及客户节点中的联系人。
我的样本Xml格式是
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customers>
<values>
<type>
<customer id="100">
<age>29</age>
<name>mkyong</name>
</customer>
<customer id="140">
<age>29</age>
<name>chandoo</name>
</customer>
</type>
</values>
<listType>Population</listType>
<contact>phani</contact>
</customers>
我创建了以下pojo类(客户,值,类型,客户)
客户.java
@XmlRootElement( name="customers" )
public class Customers {
List<Values> values;
private String listType;
private String contact;
Setters & Getters
}
值.java
class Values {
List<Type> type;
Setters & Getters
}
Type.java
class Type {
private int id;
private List<Customer> customer;
Setters & Getters
}
客户.java
class Customer {
private String name;
private int age;
Setters & Getters
}
主班
App.java
public static void main(String[] args) {
try {
File file = new File("D:/userxml/complex.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customers.class,Values.class,Type.class,Customer.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Type type = (Type) jaxbUnmarshaller.unmarshal(file);
System.out.println(type);
} catch (JAXBException e) {
e.printStackTrace();
}
}
我是PHP开发人员,并且是Java的新手。请帮帮我。我想获取客户详细信息
最佳答案
请用:
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Customers customers = (Customers) jaxbUnmarshaller.unmarshal(file);
这将创建具有您的类中定义的结构的Customer对象,您可以使用适当的getter获取所需的值。
要回答您评论中的问题,请尝试(这只是对列表中第一个元素进行硬编码调用的示例):
System.out.println(customers.getValues().get(0).getType().get(0));
System.out.println(customers.getValues().get(0).getType().get(0).getCustomer().get(0).getAge());
System.out.println(customers.getValues().get(0).getType().get(0).getCustomer().get(0).getName());
调用适当的getter并在Type内迭代Customer对象的列表。