java - JAXB解析复杂的xml

标签 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 类(客户、值、类型、客户)

客户.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
}

类型.java

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

客户.java

class Customer {    
    private String name;
    private int age;
    Setters & Getters
}

主要类(class)在 应用程序.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);

这将使用类中定义的结构创建 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 对象的列表。

关于java - JAXB解析复杂的xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43977667/

相关文章:

c - 如何使用 libxml c 库获取 XML 中的属性?

java - 使用 java 反编译器 jd-gui 并获取//INTERNAL ERROR//

java - 查找同级或更高级别的 XML 节点数

javascript - 如果 xml 包含重复(多个)标签,如何在 json 中表示 xml

c# - 为什么我的 XDocument 在我不想要的时候保存了声明?

java - 启动时解析camelContext.xml文件时出现空指针

java - JNI 将 String 转换为 char *,由实例方法返回

java - 对称矩阵Java构造错误

java - 为什么捕获 RuntimeException 不被认为是一种好的编程习惯?

java - SimpleXML - Android - CDATA 解析