I am not able to parse following xml file using jaxB
<?xml version="1.0" encoding="utf-8"?>
<Root>
<Status>1</Status>
<StatusMessage/>
<ResultSet>
<Columns count="2">
<col type="Decimal">COL1</col>
<col type="String">COL2</col>
</Columns>
<Rows count="3">
<row index="0">
<col index="0">1</col>
<col index="1">ABC</col>
</row>
<row index="1">
<col index="0">2</col>
<col index="1">DEF</col>
</row>
<row index="2">
<col index="0">3</col>
<col index="1">XYZ</col>
</row>
</Rows>
</ResultSet>
</Root>
Here is how I have written the java objects
@XmlRootElement(name = "Root")
@XmlAccessorType(XmlAccessType.FIELD)
public class Root{
@XmlElement(name="Status")
private String status;
@XmlElement(name="StatusMessage")
private String statusMessage;
@XmlElement(name="ResultSet")
private ResultSet resultSet;
}
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="ResultSet")
public class ResultSet {
@XmlElement(name = "Columns")
MyColumns cols;
@XmlElementWrapper(name="Rows")
@XmlElement(name = "row")
List<MyRow> all;
}
@XmlRootElement(name = "Columns")
public class MyColumns {
@XmlElement(name = "col")
private String columns1;
@XmlElement(name = "col")
private String columns2;
}
@XmlRootElement(name = "row")
@XmlAccessorType(XmlAccessType.FIELD)
public class MyRows {
@XmlElement(name = "col")
private String row1;
@XmlElement(name = "col")
private String row2;
}
I am not getting any exception while parsing but the data in MyRows and MyColumns is coming as null. what I am suspecting is the XMLElement name in MyRows. For both the variables the name is "col". due to which it might not be able to map data correctly.
What could be the right way to parse this xml file?
Your POJOs should match better your rows and columns. We create a Column class (I opted for one to be used both in MyRow and MyColumns - has attributes of both).
@XmlAccessorType(XmlAccessType.FIELD)
public class Column {
@XmlAttribute
private String type;
@XmlAttribute
private String index;
@XmlValue
private String value;
}
Alter MyColumns to use it:
@XmlRootElement(name = "Columns")
public class MyColumns {
@XmlElement(name = "col")
private List<Column> columns;
}
And same for MyRow:
@XmlRootElement(name = "row")
@XmlAccessorType(XmlAccessType.FIELD)
public class MyRow {
@XmlAttribute
private String index;
@XmlElement(name = "col")
private List<Column> columns;
}