繁体   English   中英

用JAXB读取XML文件

[英]Reading an XML file with 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>

使用客户类:

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

然后,我在尝试阅读此书时遇到了一些麻烦。

我尝试添加一个Customer类:

@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文件吗?

将您的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同样(这只是一个好习惯)。

如果您在使用批注时遇到问题,则可以将其删除并改用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(); } } 

但是请注意,要覆盖默认行为时,需要使用批注。 您可以在此处找到完整的示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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