简体   繁体   English

JAXB:解组具有相同值的不同XML元素

[英]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文件:

Xml input file XML输入文件

<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 . 实际上, <bark><meow>都隐藏了相同的概念,即动物的“音调”或“音量”,定义为String

I could do this: 我可以这样做:

Animal.java 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. getVolume()Cat.javaDog.java实现getVolume()Dog.java返回this.barkthis.meow

However, it seems cleaner to have a volume attribute in Animal.java and somehow tell JAXB to map both of these fields to it. 但是,在Animal.java具有volume属性似乎更干净,并且以某种方式告诉JAXB将这两个字段都映射到它。

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.) (当然,我无法控制输入的XML。如果可能的话,我也想避免使用MOXy的解决方案,因为向该项目寻求另一个依赖可能很困难。)

You would be to: 您将要:

  1. Mark the Animal class as @XmlTransient to remove it as a mapped class. Animal类标记为@XmlTransient以将其删除为映射类。
  2. Override the getVolume() method in each of the subclasses annotating it to match the desired element for that class. 重写每个子类中的getVolume()方法,对它进行注释,以匹配该类的所需元素。

For this particular model though my preference would be for each animal to have a volume element. 对于这个特定的模型,尽管我更喜欢每只动物都有一个volume元素。

JAXB is actually have several polymorphic mechanisms. JAXB实际上具有几种多态机制。 You can use @XmlDescriminatorNode / @XmlDescrimintatorValue (Eclipse MOXy) or substitution groups. 您可以使用@XmlDescriminatorNode / @XmlDescrimintatorValue (Eclipse MOXy)或替换组。

Here is some details and code examples: substitution groups , descriminators 以下是一些详细信息和代码示例: 替换组 ,说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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