I was thinking about creating Java generator of XML files, that are then loaded by another Java program (I cannot change code there). The obvious answer was JAXB, however I stumbled upon a problem.
I want the XML to be a little more customizable:
<HeadTag>
<firsElement>
<att1/>
<att2/>
<att3/>
</firsElement>
<secondElement>
<att3/>
<att4/>
<att5/>
<att6/>
</secondElement>
</HeadTag>
<HeadTag>
<firsElement>
<att1/>
<att2/>
<att3/>
</firsElement>
</HeadTag>
<HeadTag>
<secondElement>
<att3/>
<att4/>
<att5/>
<att6/>
</secondElement>
</HeadTag>
All three XMLs would be a valid output of the generator. I have created Java Class for fistElement, secondElement and so on (there is many of them), but I can't figure out how to add them all under one HeadTag element.
I have many elements, over 500, so putting them as a fields in class is kind of ugly.
If you can afford your elements classes to extends an abstract class, you can try this :
@XmlAccessorType(XmlAccessType.FIELD)
public abstract class Element{};
@XmlAccessorType(XmlAccessType.FIELD)
public class FirstElement extends Element{ ... };
@XmlAccessorType(XmlAccessType.FIELD)
public class SecondElement extends Element{ ... };
//Other elements classes
@XmlRootEntity
@XmlAccessorType(XmlAccessType.FIELD)
public class HeadTag{
@XmlElements({
@XmlElement(name="firstElement",type=FirstElement.class),
@XmlElement(name="secondElement",type=SecondElement.class),
//One for each of your classes
})
private List<Element> elements;
}
You'll still have a lot of @XmlElement annotations, but you won't have 500+ fields in your class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With