Using same id attribute for different element types
Brought to you by:
niallg
I am using SimpleXML for parsing XML to Java objects, but I am not able to parse this file :
<pets>
<cats>
<cat id="0" talk="miaou" />
<cat id="1" talk="MIWAOUHAUOHou" />
</cats>
<dogs>
<dog id="0"/>
</dogs>
<mine>
<cat ref="1"/>
</mine>
</pets>
Using this Java class :
@Default
@Root(name = "pets")
public class SimpleIds
{
@ElementList(required = false)
public ArrayList<Cat> cats;
@ElementList(required = false)
public ArrayList<Dog> dogs;
@Root(name = "cat")
public static class Cat
{
@Attribute
public String talk;
public void talk()
{
System.out.println(talk);
}
}
@Root(name = "dog")
public static class Dog
{
}
@Element
public Mine mine;
@Root(name = "mine")
public static class Mine
{
@Element
public Cat cat;
}
}
And this Serializer :
Strategy strategy = new CycleStrategy("id", "ref");
Serializer serializer = new Persister(strategy);
SimpleIds xml = serializer.read(SimpleIds.class, new File("simpleIds.xml"));
xml.mine.cat.talk();
It throws me :
org.simpleframework.xml.strategy.CycleException: Element '0' already exists
Is it impossible to use this kind of xml files with SimpleXML ? Or is it just a bad xml format ?
PS : If I change cat id="0" to cat id="2" it works like a charm...