springunmarshallingcastoroxm

Spring Castor Unmarshalling with Mapping


I am trying to unmarshall an XML to Object using Castor OXM Unmarshalling in Spring.

XML:

<LevelA>
  <LevelB>
    <item name="itemA">value</item>
    <item name="itemB">value</item>
    <item name="itemC">value</item>
    <item name="itemD">value</item>
    <item name="itemE">value</item>
  </LevelB>
</LevelA>

Object:
 Class LevelA {
     LevelB objLevelB;
     //getter and setter
   }

 Class LevelB {
     List<Items> item = new ArrayList<Items>();
     //getter and setter
   }

 Class Items {
     String Name;
     String Value;
    //getter and setter
  }


 Castor Mapping: 

  <mapping>
    <class name="LevelA">
      <map-to xml="LevelA" />
      <field name="objLevelB" type="LevelB">
        <bind-xml name="LevelB" />
          <class name="LevelB">
           <field name="item" type="Items" collection="arraylist">
             <bind-xml name="item" node="element" />
                <class name="Items">
                  <field name="Name" type="string">
                    <bind-xml name="name" node="attribute" />
                  </field>
                  <field name="Value" type="string">
                    <bind-xml node="text" />
                  </field>
                 </class>
            </field>
          </class>
      </field>
    </class>
  </mapping> 

I am getting the following error:

org.xml.sax.SAXException: unable to find FieldDescriptor for 'item' in ClassDescriptor of LevelB

I have tried several ways and spent enough time that I need some help from you all now.

Any help would be useful.


Solution

  • Figured out the way myself, here is the mapping that worked for me. I am sharing the answer to help others, in the same situation.

    <?xml version="1.0" encoding="UTF-8"?>
    <mapping>
        <description> Provides Mapping to Convert Document to POJO</description>
        <class name="LevelAClass">
            <map-to xml="LevelA" />
            <field name="objLevelB" type="LevelBClass">
                <bind-xml name="LevelB" />
            </field>
        </class>
    
        <class name="LevelBClass">
            <field name="item" type="LevelCClass"
                collection="arraylist">
                <bind-xml name="item" />
            </field>
        </class>
    
        <class name="LevelCClass">
            <field name="Name">
                <bind-xml name="name" node="attribute" />
            </field>
            <field name="Value">
                <bind-xml name="item" node="text" />
            </field>
        </class>
    </mapping>