簡體   English   中英

JAXB解析復雜的xml

[英]JAXB parse complex xml

我想獲取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
}

Values.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對象的列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM