【问题标题】:How to get DOM structure of matching xpath from xml structure using java/python如何使用 java/python 从 xml 结构中获取匹配 xpath 的 DOM 结构
【发布时间】:2017-06-27 23:32:09
【问题描述】:

考虑到下面的 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>

【问题讨论】:

  • 您看过一些用于 Java 的 XPath API 吗?教程很多

标签: java html xml python-3.x xpath


【解决方案1】:

您不能仅使用 xpath 以 xml 的形式获取 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());

它的工作方式是转换器将 XSLT 字符串应用于您的 xml(在上面的代码中由 anotherfoo.xml 表示)并获取与 xpath //foo/foo2/another1xsl:copy-of 匹配的元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-29
    • 1970-01-01
    • 1970-01-01
    • 2014-09-23
    • 2021-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多