【问题标题】:JAXB parse complex xmlJAXB 解析复杂的 xml
【发布时间】:2017-05-15 10:53:49
【问题描述】:

我想获取客户节点中的 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
}

值.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
}

主类在 应用程序.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 新手。请帮帮我。我想获取客户详细信息

【问题讨论】:

  • 你的问题是什么?
  • @BetaRide 我编辑了我的问题。您能提供此查询的帮助网址或答案吗? TQ

标签: java xml xml-parsing jaxb


【解决方案1】:

请使用:

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

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

【讨论】:

  • 最初我尝试使用该模式并从客户节点获取 listType、Contact 值。我还想在类型节点中获取客户节点中的名称、年龄值。这是我的问题。
  • JAXB 将根据 xml 和您拥有的结构解组。请在我的回答中检查我的编辑。您可以通过调用适当的 getter 来获取值(我已经提供了一个示例)。
  • 是的,但我没有在内部客户节点中获得姓名、年龄。
  • 请粘贴我在答案中输入的 sysout 命令的输出。我能够运行此代码并查看姓名、年龄等
  • 问题是我在 Type.java 类中为 getCustomer 添加了注释(@XmlElementWrapper(name="customer") )。如果我想循环姓名和年龄,我该怎么做。 Tq 很多。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多