Xml Serialization with java - SimpleXml
For those of you out there who have problem implementing some complex xmls i have a good example for you:
Xml :
[cc lang="xml" lines="auto"]
Teszt1
Teszt2
Teszt2
Teszt3
[/cc]
And this is your Class Hierarchy representing it:
[cc lang="java" lines="auto" escaped="true"]
@Root
public class UIElement
{
@ElementList(name="Elements")
public List divContainers;
}
@Root
public class DivContainer
{
@ElementList(name="DivContainer", inline=true)
public List divs;
@Attribute
public String name;
}
@Root(name="Div")
public class Div
{
@Element(name="test")
public String test;
@Attribute(name="name", required=false)
public String name;
}
[/cc]
And the serialize code:
[cc lang="java" lines="auto" escaped="true"]
public void testXml()
{
Serializer serializer = new Persister();
File source = new File("c:\\tmp\\test.xml");
UIElement ui = null;
try
{
ui = serializer.read(UIElement.class, source);
} catch (Exception e)
{
e.printStackTrace();
}
for (DivContainer divc : ui.divContainers)
{
for (Div div : divc.divs)
{
System.out.println("Value of test: " + div.test);
}
}
}
[/cc]
You have to look out for two things... First note the @Root under Div tag. That is necessary there. Writing in the attribute name there is necessary too. Also the 'inline' tag. Without them it wont work.
Gergely.