如何使用Java/Python从XML结构中获取匹配XPATH的DOM结构



考虑以下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的形式获得DOM结构。使用XPATH和评估,您将获得DOM节点。您可以从nodeset构建所需的XML,但是随着孩子的元素的增加数量会增加(这里是another1,只有一个子节点 - 还可以(

(

,但否则请考虑使用XSLT如下:

注意:我已将XSLT用作字符串,如果您的需求与仅显示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());

它的工作方式是Transfomer在XML上应用XSLT字符串(上面代码中用anotherfoo.xml表示(,并获取与XPath //foo/foo2/another1通过xsl:copy-of的元素。

最新更新