繁体   English   中英

使用JAXB将Xml组件解组到Java Object

[英]Unmarshal Xml components to Java Object using JAXB

我已经将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类,

  • ShoppingMall(ProductList是此类中的xml元素)
  • ProductList(product_info是此类中的xml元素)
  • product_info(group_nm,group_code,product_nm和price是此类中的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(); } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM