JAXB解析复杂的xml

时间:2017-05-15 10:53:49

标签: java xml xml-parsing jaxb

我想获取客户节点中的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课程(客户,价值观,类型,客户)

Customers.java

@XmlRootElement( name="customers" )
public class Customers {    
    List<Values> values;    
    private String listType;
    private String contact;
    Setters & Getters
}

Values.java

class Values {    
    List<Type> type;
    Setters & Getters
}

Type.java

class Type {    
    private int id;
    private List<Customer> customer;
    Setters & Getters
}

Customer.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的新手。请帮帮我。我想获取客户详细信息

1 个答案:

答案 0 :(得分:1)

请使用:

        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        Customers customers = (Customers) jaxbUnmarshaller.unmarshal(file);

这将使用您的类中定义的结构创建Customers对象,您可以使用适当的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对象的列表。

相关问题