簡體   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