简体   繁体   中英

JAXB parse complex xml

I want to get the id, Age, name in customer node and listType, contact from customers node.

My sample Xml format is

<?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>

I created folloing pojo classes (Customers, Values, Type, Customer)

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
}

Main class in 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();
        }        
    }

I am PHP Developer and new to java. Please help me out. I want to get the customer details

Please use:

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

This will create the Customers object with the structure defined in your class, you can use the appropriate getters to fetch the value you need.

To answer the question in your comment, try (This is just an example with hardcoded calls for first element in the list):

        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());

Call the appropriate getters and iterate the lists for the Customer object inside Type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM