Search code examples
androidxml-parsingsimple-framework

Simple XML Framework: XML Structure Issue


My external XML source has this structure

<NewDataSet>
  <Table>
    <department>HR</department>
    <depno>01</depno>
  </Table>
  <Table>
    <department>IT</department>
    <depno>02</depno>
  </Table>
</NewDataSet>

But the Simple XML Framework expects this kind of structure

<NewDataSet>
  <Tables>
    <Table>
      <department>HR</department>
      <depno>01</depno>
    </Table>
    <Table>
      <department>IT</department>
      <depno>02</depno>
    </Table>
  </Tables>
</NewDataSet>

This is my NewDataSet class

@Root
  public class NewDataSet {
    @ElementList
    public List<Table> Tables;
  }

This is my Table class

@Element
public class Table {

@Element
private String department;

@Element
private String depno;

}

How to write the correct classes to match my external XML source? These classes to be used in this program

        String url =  "http://";
        String xmlData = retrieve(url);
        Reader reader = new StringReader(xmlData);
        Serializer serializer = new Persister();
        NewDataSet nds =  serializer.read(NewDataSet.class, reader, false);
        Log.d(MainActivity.class.getSimpleName(), nds.toString());

Solution

  • Use inline

    Seems this issue already been addressed in the official docs. http://simple.sourceforge.net/download/stream/doc/tutorial/tutorial.php#inline

    When dealing with third party XML or with XML that contains a grouping of related elements a common format involves the elements to exist in a sequence with no wrapping parent element. In order to accomodate such structures the element list annotation can be configured to ignore the parent element for the list.

    @Root
    public class NewDataSet {
    
        @ElementList(inline = true, entry = "Table")
        public List<Table> Tables;
    }