我已经完成了将java对象编组到XML元素。现在我面临使用JAXB将XML文件解组为java对象的困难。它是否与将java对象编组为XML类似?下面是我从外部API获得的XML文件。
<ShoppingMall>
<ProductList>
<product_info>
<group_nm>electronic device</group_nm>
<group_code>e001</group_code>
<product_nm>computer</product_nm>
<price>30000</price>
</product_info>
<product_info>
<group_nm>living</group_nm>
<group_code>lv002</group_code>
<product_nm>bed</product_nm>
<price>140000</price>
</product_info>
<product_info>
<group_nm>Food</group_nm>
<group_code>f001</group_code>
<product_nm>pasta</product_nm>
<price>10</price>
</product_info>
</ProductList>
</ShoppingMall>
要将XML元素交换为java对象,我应该如何处理JAXB?
首先创建三个java类,
然后尝试这个,
JAXBContext jaxbContext = JAXBContext.newInstance(ShoppingMall.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
ShoppingMall shoppingMall = (ShoppingMall) jaxbUnmarshaller.unmarshal( new File("your_xml_file.xml") );
我想你想解开ShoppingMall类。所以,你可能会写这样的东西。
ShoppingMall shoppingMall = getShoppignMallByUnmarshal(your_xml);
public static getShoppignMallByUnmarshal(
String xml) throws JAXBException
{
JAXBContext jaxbContext = JAXBContext.newInstance(package.path.of.ShoppingClass.ObjectFactory.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
return ((JAXBElement<ShoppingMall>) jaxbUnmarshaller.unmarshal(new StringReader(xml)))
.getValue();
}