Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changeable XML structure in JAXB?

Tags:

java

xml

jaxb

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.

like image 249
everyonecancode Avatar asked Apr 24 '26 06:04

everyonecancode


1 Answers

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.

like image 189
Dimpre Jean-Sébastien Avatar answered Apr 26 '26 23:04

Dimpre Jean-Sébastien