0

I've done marshalling java object to XML elements. Now I face a difficulty to unmarshal XML file to java object using JAXB. Is it similar as marshalling java object to XML? Below is the XML file that I got from the external API.

<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>

To exchange XML element to java object, what should I do with JAXB?

Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
Alice
  • 1
  • Possible duplicate of [convert xml to java object using jaxb (unmarshal)](https://stackoverflow.com/questions/11221136/convert-xml-to-java-object-using-jaxb-unmarshal) – Tatenda Zifudzi Feb 21 '19 at 06:37

2 Answers2

0

firstly create three java classes for,

  • ShoppingMall (ProductList is a xml element in this class)
  • ProductList (product_info is a xml element in this class)
  • product_info (group_nm, group_code, product_nm and price are xml elements in this class)

then try with this,

JAXBContext jaxbContext = JAXBContext.newInstance(ShoppingMall.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
ShoppingMall shoppingMall = (ShoppingMall) jaxbUnmarshaller.unmarshal( new File("your_xml_file.xml") );
Lakshan
  • 1,404
  • 3
  • 10
  • 23
0

I suppose you want to unmarshal to ShoppingMall class. So, you might write something like this.

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();
  }
naqib83
  • 128
  • 3
  • 14