使用 JAXB 解组具有不同/动态名称的元素 [英] Using JAXB to unmarshall elements with varying/dynamic names

查看:32
本文介绍了使用 JAXB 解组具有不同/动态名称的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在解析具有如下节点的 XML 文档:

I'm parsing an XML document that has nodes like the following:

<objects>
  <dog>
    <data1>...</data1>
    <data2>...</data2>
    <data3>...</data3>
  </dog>
  <cat>
    <data1>...</data1>
    <data2>...</data2>
    <data3>...</data3>
  </cat>
</objects>

元素 data1、data2、data3 始终保持一致.只有父标签有所不同.在我的对象模型中,我有一个代表所有这些情况的对象.如何在不事先知道元素名称的情况下让 JAXB 处理这种情况?

The elements data1, data2, data3 are always consistent. Only the parent tag varies. In my object model I have a single Object which represents all of these cases. How can I get JAXB to handle this case without knowing in advance the name of the element?

@XMLAnyElement 匹配所有对象但不创建适当类型的对象;我得到一个 Node 对象列表,而不是我的对象.我的对象目前看起来像:

@XMLAnyElement matches all the objects but doesn't create an object of the appropriate type; I get a list of Node objects instead of my object. My object currently looks something like:

public class MyObject {
    protected String otherData;

    @XmlAnyElement
    @XmlElementWrapper(name = "objects")
    protected List<MyChildObject> childObjects;
}

public class MyChildObject {
    protected String data1;
    protected String data2;
    protected String data3;
}

除了将传入的 XML 格式更改为使用 <object type="dog"> 元素之外,如何处理这种情况?

Any ideas how to handle this case short of changing the incoming XML format to use <object type="dog"> elements?

推荐答案

如果名称真的是动态的,那么我认为 JAXB 不会帮助你这些.如果您有定义数量的各种元素名称,那么您可以像其他帖子建议的那样使用继承.如果元素和名称的数量未知,我建议使用以下内容:

If the name is truely dynamic, then I don't think JAXB will help you these. If you have a defined number of various element names then you could use inheritance like the other post suggested. If the number of elements and names is unknown I would recommend using something like this:

@XmlMixed
@XmlAnyElement
public List<Object> getObjects() {
    return objects;
}

这将带来的元素只是一个 DOM 元素.然后,您可以再次使用 JAXB 将每个元素转换为您的自定义类型.

This would bring the element is a just a DOM element. You could then use JAXB a second time to go from each of the elements into your custom type.

如果您必须使用 JAXB,那就是这样.您可能会发现直接将 SAX 或 DOM API 用于此类数据更容易.JAXB 真正适用于可以表示为模式的定义明确的数据.

That would be if you had to use JAXB. You might find it easier to just use the SAX or DOM APIs directly for data like this. JAXB is really intended for well defined data that can be represented as a schema.

这篇关于使用 JAXB 解组具有不同/动态名称的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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