使用JAXB读取XML文件

时间:2014-04-21 21:22:40

标签: java xml jaxb

我现在可以阅读xml文件:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer id="100" r="q">
<datas>
    <data>
        <age>29</age>
        <name>mky</name>
    </data>
</datas>
</customer>

使用Customer类:

@XmlRootElement
public class Customer {

String name;
String age;
String id;
String r;

@XmlAttribute
public void setR(String R) {
    this.r = R;
}   

    /etc
}

我决定扩展XML文件以支持多个客户:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customers>
<customer id="100" r="q">
        <age>29</age>
        <name>mky</name>
</customer>
<customer id="101" r="q">
        <age>29</age>
        <name>mky</name>
</customer>
</customers>

然后我试图阅读这篇文章遇到了一些麻烦。

我尝试添加一个Customers类:

@XmlRootElement
public class Customers{
private ArrayList<Customer> customers;

public List<Customer> getCustomers() {
    return customers;
}

@XmlElement
public void setCustomers(ArrayList<Customer> customers) {
    this.customers = customers;
}

}

然后尝试打印:

     try {

            File file = new File("/Users/s.xml");
            JAXBContext jaxbContext = JAXBContext.newInstance(Customers.class);

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

            System.out.println(c.getCustomers());

          } catch (JAXBException e) {
            e.printStackTrace();
          }

        }}

但是我试图打印这个值时得到一个空值。有人可以告诉我如何阅读第二个XML文件吗?

2 个答案:

答案 0 :(得分:2)

将您的Customers课程更改为

@XmlRootElement(name = "customers")
class Customers {
    private List<Customer> customers;

    public List<Customer> getCustomers() {
        return customers;
    }

    @XmlElement(name = "customer")
    public void setCustomers(List<Customer> customers) {
        this.customers = customers;
    }
}

您不想要的是XML元素的get / set方法之间的不匹配。如果有人返回ArrayList,则另一个人应该接受ArrayList参数。同样适用于List(这只是一种很好的做法)。

答案 1 :(得分:0)

如果您在使用注释时遇到问题,可以删除它们并使用JAXBElement的实例代替。 为此:

  1. 首先删除Customers班级中的任何注释

    public class Customers{
      private ArrayList<Customer> customers;
    
      public List<Customer> getCustomers() {
        return customers;
      }
    
      public void setCustomers(ArrayList<Customer> customers) {
        this.customers = customers;
      }
    
    }
    
  2. 第二次在您的解析方法中使用JAXBElement的实例

    try {
    
        File file = new File("/Users/s.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(Customers.class);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        JAXBElement<Customers> je1 = unmarshaller.unmarshal(file, Customers.class);
        Customers c = je1.getValue();
        System.out.println(c.getCustomers());
    
      } catch (JAXBException e) {
        e.printStackTrace();
      }
    }
    
  3. 但请注意,如果要覆盖默认行为,则需要注释。 您可以找到完整示例here