JAXB解组未知XML内容的子集 [英] JAXB Unmarshalling an subset of Unknown XML content

查看:150
本文介绍了JAXB解组未知XML内容的子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要求 unmarshall 未知 XML 内容的子集,使用该解组对象,我需要修改一些内容并使用原始XML重新绑定相同的XML内容(子集)。

I have a requirement to unmarshall a subset of Unknown XML content, with that unmarshalled object, I need modify some contents and re-bind the same XML content(subset) with the Original XML.

示例输入XML:

<Message>
    <x>
    </x>
    <y>
    </y>
    <z>
    </z>
    <!-- Need to unmarshall this content to "Content" - java Object -->
    <Content>
        <Name>Robin</Name>
        <Role>SM</Role>
        <Status>Active</Status>
    </Content>
.....
</Message>

需要解组< Content> 通过保持其他XML部分相同来单独标记。需要修改< Content> 标记中的元素,并将修改后的XML部分与原始文件绑定,如下所示:

Need to unmarshall the <Content> tag alone, by keeping the other XML part as same. Need to modify the elements in <Content> tag and bind the modified XML part with the original as shown below:

预期输出XML:

<Message>
    <x>
    </x>
    <y>
    </y>
    <z>
    </z>
    <!-- Need to unmarshall this content to "Content" - java Object -->
    <Content>
        <Name>Robin_123</Name>
        <Role>Senior Member</Role>
        <Status>1</Status>
    </Content>
.....
</Message>

我的问题:


  1. 此要求的可能解决方案是什么? DOM 解析 - 因为XML contnet非常庞大)

  1. What is the possible solution for this Requirement ? (Except DOM parsing - as XML contnet is very huge)

JAXB2.0 中有没有选项?

请提供您对此的建议。

推荐答案

考虑使用规模缩小源文档 StAX API

Consider cutting your source document down to size using the StAX API.

对于给定的示例,此代码创建一个DOM文档,其根元素为 Content 元素:

For the given sample, this code creates a DOM document with a root element of the Content element:

class ContentFinder implements StreamFilter {
  private boolean capture = false;

  @Override public boolean accept(XMLStreamReader xml) {
    if (xml.isStartElement() && "Content".equals(xml.getLocalName())) {
      capture = true;
    } else if (xml.isEndElement() && "Content".equals(xml.getLocalName())) {
      capture = false;
      return true;
    }
    return capture;
  }
}

XMLInputFactory inFactory = XMLInputFactory.newFactory();
XMLStreamReader reader = inFactory.createXMLStreamReader(inputStream);
reader = inFactory.createFilteredReader(reader, new ContentFinder());
Source src = new StAXSource(reader);
DOMResult res = new DOMResult();
TransformerFactory.newInstance().newTransformer().transform(src, res);
Document doc = (Document) res.getNode();

这可以是传递给JAXB DOMSource

在输出上重写XML时可以使用类似的技术。

Similar techniques can be used when rewriting the XML on output.

JAXB似乎不接受直接 StreamSource ,至少在Oracle 1.7实现中。

JAXB doesn't seem to accept a StreamSource directly, at least in the Oracle 1.7 implementation.

这篇关于JAXB解组未知XML内容的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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