2012-07-26 76 views
1

任何人都可以推薦一段代碼,用於使用jaxb將xml轉換爲java。 我的XML文件的樣子使用jaxb將複雜的xml解析爲java

 <Customer> 
    <Operation>Sample</Operation> 
    <head> 
     <sub> 
      <value> 
       <att> 
        <req> 
         <name>sample</name> 
         <value> 
          <string> sample values </string> 
         </value> 
        </req> 
       </att> 
      </value> 
     </sub> 
     <sub> 
      <value> 
       <att> 
        <req> 
         <name>var</name> 
         <value> 
          <string>var value</string> 
         </value> 
        </req> 
       </att> 
      </value> 
     </sub> 
    </head> 
</Customer> 

我用下面的一段代碼,但是我得到空值

File file = new File("C:\\xml.xml"); 
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class); 
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); 
Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file); 
System.out.println(customer.name); 
System.out.println(customer.string); 

我預期的輸出應該像

Sample 
sample values 
var 
var value 
+0

您可能感興趣的以下內容:http://blog.bdoughan.com/2010 /09/xpath-based-mapping-geocode-example.html – 2012-07-26 09:28:15

回答

0

哪有我通過相同的標籤名稱獲得多個值。例如,如果XML是像

xml文檔

<customer> 
     <sample> 
     <name>name</name> 
     <value> 
     <string> value </string> 
     </value> 
     </sample> 
     <sample> 
     <name>name</name> 
     <value> 
     <string> value </string> 
     </value> 
     </sample> 
</customer> 

我使用下面的代碼

File file = new File("C:\\sample.xml"); 
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class); 
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); 
Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file); 
System.out.println(customer.value.string); 
System.out.println(customer.sample.name);