javareflectionxml-parsing

parsing xml using reflection api in java


This is my XML file.

<customer>
  <Field Number = '1' Value = '3'>
    <Name>customer1</Name>
    <Length>2</Length>
    <Type>regular</Type>
    <Method Number = '1'>pay through cash</Method>
    <Method Number = '2'>pay through card</Method>
  </Field>
  <Field Number = '2'>
    <Name>customer2</Name>
    <Length>2</Length>
    <Type>rare</Type>
  </Field>
  <Field Number = '3'>
    <Name>customer3</Name>
    <Length>4</Length>
    <Type>regular</Type>
  </Field>
</customer>

I should parse this file using any parser in java language.
But my java source code should not contain any component of xml file, for example node.getAttributes().getNamedItem("Name").getNodeValue(); in the above instruction i've used "Name" but I'm not supposed to use it.
Which parser is efficient for this scenario.even code snippets are welcomed.
I must be able to parse this file on the fly and use the tag contents as class members and setter and getter methods.So i,ve used reflection api.


Solution

  • I assume you have the corresponding types already. You may need to alter them slightly as without being specific (which you try to avoid) you will have hard time assigning xml elements with same name to fields(likely collections). For example you have to elements called So every element belongs to a collection should be handled as either a set (can contain any elements) or lists (can contain homogeneous elements)

    <ExampleSet>
      <ExampleList>
        <ExampleType>example1</ExampleType>
        <ExampleType>example2</ExampleType>
      </ExampleList>
      <OtherExampleType>example3</OtherExampleType>
    </ExampleSet>
    

    You can now mark each type with a corresponding interface (XmlSet, XmlList, XmlType per say). Now you can parse them knowing if they are a set they compose other types, if they are a list they are a collection of types or they simply a type. Now you can use reflection to assign the value or attribute of the XmlType to a String, int, long or whatever you need based based on the type of the field you determined via reflection.

    A very abstracted idea below, let me know if you need more details:

    void readXml(Xml xml) {
      if (xml instanceof XmlSet) readSet(xml);
      else if (xml instanceof XmlList) readList(xml);
      else if (xml instanceof XmlType) readType(xml);
    }
    
    void readSet(Xml xml) {
      /*here you loop through the elements of set and call readXml(child)*/
    }
    
    void readList(Xml xml) {
      /*here you loop through the elements of list and call readXml(child).*/
    }
    
    void readType(Xml xml) {
      /* Here you use reflection to populate the value of elements with the corresponding java types */
    }