我已经将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?
答案 0 :(得分:0)
首先为它创建三个Java类,
然后尝试一下,
JAXBContext jaxbContext = JAXBContext.newInstance(ShoppingMall.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
ShoppingMall shoppingMall = (ShoppingMall) jaxbUnmarshaller.unmarshal( new File("your_xml_file.xml") );
答案 1 :(得分:0)
我想您想解组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();
}