使用jaxb将复杂的xml解析为java

时间:2012-07-26 04:51:48

标签: jaxb

任何人都可以建议一段代码,用于使用jaxb将xml转换为java。 我的xml文件看起来像

     <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

1 个答案:

答案 0 :(得分: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);