1

任何人都可以建议一段代码,用于使用 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
4

1 回答 1

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);
于 2012-07-27T06:44:26.333 回答