JAXB: Unmarshalling of different XML elements with same values



There is a plethora of questions on roughly the same topic, but I couldn't find exactly what I was looking for. My apologies if I missed it.


I'm trying to unmarshal XML files that have common logical elements, but defined with different tags:


Xml input file



<xml>
<animals>
<dog>
<bark>loud</bark>
</dog>
<cat>
<meow>frail</meow>
</cat>
</animals>
</xml>


Both <bark> and <meow> are in fact hiding the same concept, the "pitch" or "sound volume" of the animal, defined as a String.


I could do this:


Animal.java



public abstract class Animal {

public abstract String getVolume();

}


All it would take would be implementing getVolume() in both Cat.java and Dog.java and return this.bark or this.meow, respectively.


However, it seems cleaner to have a volume attribute in Animal.java and somehow tell JAXB to map both of these fields to it.


Am I overthinking this? How would you implement that?


(Of course, I have no control over the input XML. I would also like to avoid solutions using MOXy if possible, as pushing for another dependency to this project might be difficult.)


No comments:

Post a Comment