gpt4 book ai didi

java - 如何使用java/python从xml结构中获取匹配xpath的DOM结构

转载 作者:行者123 更新时间:2023-12-02 12:45:58 26 4
gpt4 key购买 nike

考虑下面的 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和evaluate,你将得到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

关于java - 如何使用java/python从xml结构中获取匹配xpath的DOM结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44783159/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com