Parsing XML file list elements using simple XML in Android… here is a solution to the problem.
Parsing XML file list elements using simple XML in Android
I
need to parse a large xml file in SImple XML (I really want to use Simple XML). I create objects using XSD and convert them from JAXB-specific objects to SimpleXML-specific annotated objects.
The XML looks like this:
<House>
<MainLevel Name="~#editRoom" IsHidden="false">
<ChildLevel Name="Television" Category="Livingroom">
<string>TestRoom</string>
</ChildLevel>
<ChildLevel Name="Chair" Category="Livingroom">
<string>TestRoom</string>
</ChildLevel>
<ChildLevel Name="Table">
<string>TestRoom</string>
</ChildLevel>
<ChildLevel Name="ChamberName" Category="Livingroom">
<string>TestRoom</string>
</ChildLevel>
<ChildLevel Name="ChamberName" Category="Bathroom">
<string>BathTub</string>
</ChildLevel>
<ChildLevel Name="Door", Category="DiningRoom">
<boolean>isOpen</boolean>
</ChildLevel>
</MainLevel>
<MainLevel Name="~#editRoom" IsHidden="false">
<ChildLevel Name="Television" Category="Livingroom">
<string>TestRoom</string>
</ChildLevel>
<ChildLevel Name="Chair" Category="Livingroom">
<string>TestRoom</string>
</ChildLevel>
<ChildLevel Name="Table" Category="Livingroom">
<string>TestRoom</string>
</ChildLevel>
<ChildLevel Name="ChamberName" Category="Livingroom">
<string>TestRoom</string>
</ChildLevel>
<ChildLevel Name="ChamberName" Category="Bathroom">
<string>BathTub</string>
</ChildLevel>
<ChildLevel Name="Door">
<boolean>isOpen</boolean>
</ChildLevel>
</MainLevel>
</House>
What do you suggest. Please help. Thank you.
Solution
You’d better write 3 classes:
The House
class, (= root) contains the (inline) list ofMainLevels
The MainLevel
class, which contains an (inline) list of allChildLevels
The ChildLevel
class, which contains values
Here is some pseudocode :
@Root(...)
public class House
{
@ElementList(inline = true, ...)
private List<MainLevel> levels;
// ...
}
public class MainLevel
{
@Attribute(name = "Name")
private String name;
@Attribute(name = "IsHidden")
private bool hidden;
@ElementList(inline = true, ...)
private List<ChildLevel> childLevels;
// ...
}
public class ChildLevel
{
@Attribute(name = "Name")
private String name;
@Attribute(name = "Category", required = false)
private String category;
// ...
}
Since ChildLevel
can be of different types, you must be aware of this. Either implement all types and mark them as unwanted, or create subclasses.