我有一个 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 解析器来执行此操作吗?
感谢您的帮助!