考虑到以下 XML 结构,我如何获取/打印与给定 xpath 匹配的相应 DOM 结构。
<foo>
<foo1>Foo Test 1</foo1>
<foo2>
<another1>
<test1>Foo Test 2</test1>
</another1>
</foo2>
<foo3>Foo Test 3</foo3>
<foo4>Foo Test 4</foo4>
</foo>
说 xpath/foo/foo2
的输出应该是这样的
<another1>
<test1>Foo Test 2</test1>
</another1>
您无法仅使用 xpath 以 xml 的形式获取 DOM 结构。使用 xpath 和评估,您将获得 DOM 节点。您可以从 NODESET 构建您想要的 xml,但是随着感兴趣元素下子节点数量的增加,这会很麻烦(这里another1
只有一个子节点 - 没关系)
但否则考虑使用 XSLT,如下所示:
注意:我已经将 xslt 用作字符串,如果您的要求像 show 一样简单another1
,则可以,否则您需要创建一个新.xsl
文件并使用它来创建StreamSource
:new StreamSource( new File("mystylesheet.xsl") )
String xslt = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">" +
"<xsl:output method=\"xml\" omit-xml-declaration=\"yes\"/>" +
"<xsl:template match=\"/\">" +
"<xsl:copy-of select=\"//foo/foo2/another1\"/>" +
"</xsl:template>" +
"</xsl:stylesheet>";
Transformer transformer = TransformerFactory.newInstance().newTransformer( new StreamSource(new StringReader(xslt)) );
StreamSource xmlSource = new StreamSource( new File( "anotherfoo.xml" ) );
StringWriter sw = new StringWriter();
transformer.transform(xmlSource, new StreamResult(sw) );
System.out.println(sw.toString());
它的工作方式是主变差动应用XSLT串在你的XML(记anotherfoo.xml
在上面的代码)并获取与XPath相匹配的元素//foo/foo2/another1
通过xsl:copy-of
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句