具有相同名称的Jaxb对象 [英] Jaxb objects with same name

查看:73
本文介绍了具有相同名称的Jaxb对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎可以使用相同的名称解组两个不同的 jaxb 对象。

It would appear to be possible to unmarshal two different jaxb objects with the same name.

有一个 Bar 类......

There is a Bar class ...

public abstract Bar {
   private @XmlElement String val;
}

..有两个实现(构造函数等省略):

.. with Two implementations (constructors etc. left out):

@XmlRootElement(name="bar")
public class BarA extends Bar { }

@XmlRootElement(name="bar")
public class BarB extends Bar {
     private @XmlElement(required=true) String type;
}

最后我要解组一个 Bar <的列表/ code>来自XML的文档类似于以下内容

Lastly I want to unmarshall a list of Bar documents from XML similar to the following

<bars>
  <bar>
    <val>1</val>
  </bar>
  <bar>
    <val>1</val>
    <type>2</type>
  </bar>
</bars>

列表包含在使用 @XmlAnyElement

The list is wrapped in an class utilizing the @XmlAnyElement

@XmlRootElement
public class Bars {

  @XmlMixed
  @XmlAnyElement(lax = true) 
  @XmlElementRefs({@XmlElementRef(BarA.class), @XmlElementRef(BarB.class)})
  private List<Bar> bars;
}

但我似乎获取<的实例em> BarA BarB ,以 last 元素为准 @XmlElementRefs 链。

However I seem to only get instances of either BarA or BarB, whichever is the last element in the @XmlElementRefs chain.

测试代码:

String xml = ...
JAXBContext jc = JAXBContext.newInstance(Bars.class);
ByteArrayInputStream in = new ByteArrayInputStream(xml.getBytes());
Bars bars = (Bars) jc.createUnmarshaller().unmarshal(in);
for (Bar bar : bars.getBars()) {
    System.out.println(bar.getClass());
}

我不认为 XmlAdapter 建议在 JAXB @XmlElements,不同类型但同名?必然是唯一的方法。

I don't think the XmlAdapter suggested in JAXB @XmlElements, different types but same name? would neccesarily be the only approach either.

推荐答案

真的,我要做的第一件事是消除问题的来源 - 有两个不同的JAXB类同名。对于你和那些必须维护代码的人来说,这样的情况肯定会引起头痛。

Really, the first thing I would try to do is eliminate the source of the problem - having two different JAXB classes with the same name. A situation like that is bound to cause headaches, for you and for the people who have to maintain your code.

如果这是不可能的......也许你可以编写另一个子类叫EveryBar,总是解开它。 EveryBar将包含每个其他Bar子类的所有字段。然后,您将在对象树上执行一个后处理步骤,该步骤将检查EveryBar,并将其交换为适合的任何类型的实例。是的,这是一个丑陋的解决方案,但它只比链接中的那个稍差。

If that's impossible... Maybe you could write another subclass called EveryBar, and always unmarshall to that. EveryBar would contain all the fields of every other Bar subclass. Then you'd have a post-processing step on your object tree that would examine the EveryBar, and swap it for an instance of whatever type is appropriate. Yeah, it's an ugly solution, but it's only slightly worse than the one from your link.

这篇关于具有相同名称的Jaxb对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆