我已经将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类- shoppmall(产品列表是此类的XML元素)
- productList(product_info是此类的XML元素)
- product_info(group_nm,group_code,product_nm和价格是此类XML元素)
然后尝试一下,
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();
}