具有类似结构的XML的JAXB [英] JAXB for XMLs with similar structure

查看:64
本文介绍了具有类似结构的XML的JAXB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在使用JAXb来解析不具有模式的XML ...

We are using JAXb for parsing XMLs without schema...

我们处理的一种XML如下:

One of the XMLs we deal with looks like this:

<Trade>
    <Something1>
         <!-- stuff here -->
    </Something1>
</Trade>

另一个像这样:

<Trade>
    <Something2>
         <!-- stuff here -->
    </Something2>
</Trade>

我们使用相同的Jaxb上下文,并解组将它们解析为对象,例如 Something1 Something2 ( Something1 Something2实现了一个名为 Something 的接口;解组的结果被强制转换为 Something .这两个对象在上下文中都是已知的).但是,根据解组程序首先找到哪个类,这两个XML最终都将解组到 Something1 Something2 对象.

We use the same Jaxb context and unmarshaller to parse these into objects, say Something1 and Something2 (Both Something1 and Something2 implement an interface called Something; the result of the unmarshalling is cast to Something. Both objects are -of course- known to the context). However, depending on which class is found first by the unmarshaller, both of these XMLs end up being unmarshalled to Something1 or Something2 objects.

我还尝试添加一些XML-> XSD生成的模式,但这是一个死胡同,因为在< Trade> 和其他几个标记之间存在这种冲突.我遇到的错误是:

I also tried adding some XML->XSD generated schema, but that was a dead end, as theres's this clash at <Trade> and several other tags. The error I was getting was like:

A schema cannot contain two global components with the same name; this schema contains two occurrences of ',Trade'.

有没有办法用JAXB统一处理两个结构相似的XML?

Is there no way to handle two similarly structured XMLs uniformly with JAXB?

谢谢.

推荐答案

您可以这样编写Trade元素的类:

You can write the class for element Trade like this:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "TradeType", propOrder = {
    "something1",
    "something2"
})
public class TradeType {
    @XmlElement(name = "Something1")
    protected Something1Type something1;
    @XmlElement(name = "Something2")
    protected Something2Type something2;
    // getters, setters
}

顺便说一句,这是编译(xjc)此XML模式时得到的:

BTW, this is what you get when you compile (xjc) this XML schema:

<xs:complexType name="TradeType">
  <xs:choice>
    <xs:element name="Something1" type="Something1Type"/>
    <xs:element name="Something2" type="Something2Type"/>
  </xs:choice>
</xs:complexType>

您只有一个顶级元素Trade,可以通过将 trade.getSomethingX()与null进行比较来区分(解组后).

You'll just have a single top-level element Trade, and the distinction (after unmarshalling) can be made by comparing trade.getSomethingX() with null.

如果Something1Type和Something2Type类型相同(不是相似"),则可以使用相同的 class (而不是接口).

If types Something1Type and Something2Type are identical (not "similar"), you could use the same class (not the interface).

这篇关于具有类似结构的XML的JAXB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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