简体   繁体   中英

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.)

You would be to:

  1. Mark the Animal class as @XmlTransient to remove it as a mapped class.
  2. Override the getVolume() method in each of the subclasses annotating it to match the desired element for that class.

For this particular model though my preference would be for each animal to have a volume element.

JAXB is actually have several polymorphic mechanisms. You can use @XmlDescriminatorNode / @XmlDescrimintatorValue (Eclipse MOXy) or substitution groups.

Here is some details and code examples: substitution groups , descriminators

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM