【发布时间】:2016-08-06 00:26:53
【问题描述】:
我有一个包含以下内容的 XML 文件:
<contexts>
<context name="a">
<xi:include xmlns:xi="http://www.w3.org/2003/XInclude" href="reuse.xml"/>
<other_stuff/>
</context>
<context name="b">
<xi:include xmlns:xi="http://www.w3.org/2003/XInclude" href="reuse.xml"/>
<other_stuff/>
</context>
</contexts>
...以及上面 XInclude 引用的reuse.xml,其中包含如下内容:
<good_stuff/><!-- and a bunch of complex stuff ->
我正在尝试编写一些 Java 代码,它可以为每个上下文元素生成一些字符串输出(简单),但不是 xi:include 行,而是用包含文件的内容替换它,即给我一个“爆炸”每个上下文的字符串如下:
<context name="a">
<good_stuff/><!-- and a bunch of complex stuff ->
<other_stuff/>
</context>
而不是我现在得到的:
<context name="a">
<xi:include xmlns:xi="http://www.w3.org/2003/XInclude" href="reuse.xml"/>
<other_stuff/>
</context>
希望我已经清楚地解释了自己,我不希望在我的输出中包含 xi:include 文本,而是应该替换它的另一个文件的内容。
我将解析器设置为 XInclude 和命名空间感知:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
factory.setXIncludeAware(true);
...
然后获取我想要的类型的子节点(在这种情况下,类型给了我上下文)。
NodeList result = doc.getElementsByTagName(type).item(0).getChildNodes();
但是当我对此进行迭代,并使用以下内容将每个元素传递给 StringWriter 时,它并没有替换 xi:include;
StringWriter sw = new StringWriter();
Transformer serializer = TransformerFactory.newInstance().newTransformer();
serializer.setOutputProperty(OutputKeys.INDENT, "no");
serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
serializer.setOutputProperty(OutputKeys.STANDALONE, "yes");
serializer.transform(new DOMSource(element), new StreamResult(sw));
String result = sw.toString();
除了使用字符串操作来替换 xi:include 我自己之外,还有其他方法可以使用 JDK 7/8 内置 XML 解析器吗?
感谢您的帮助!
【问题讨论】:
-
我会自己替换 xi:include,但我认为不需要进行字符串操作。但是可能提供了一个 xi:include 设施,我不知道。
-
我怀疑这是一个命名空间问题,W3C XInclude 命名空间是
http://www.w3.org/2001/XInclude而不是http://www.w3.org/2003/XInclude。