gpt4 book ai didi

xml - XPath 1.0 在 XML 树中具有属性的最接近的前导和/或祖先节点

转载 作者:数据小太阳 更新时间:2023-10-29 01:38:52 25 4
gpt4 key购买 nike

这是三个 XML 树

(1)

<?xml version="1.0" encoding="UTF-8"?>
<content>
<section id="1">
<section id="2"/>
<section id="3"/>
<section id="9"/>
</section>
<section id="4">
<section id="5">
<section>
<bookmark/> <!-- here's the bookmark-->
<section id="6">
<section id="7">
<section id="8"/>
</section>
</section>
</section>
</section>
</section>
</content>

(2)

<?xml version="1.0" encoding="UTF-8"?>
<content>
<section id="1"/>
<section id="2">
<section id="9">
<section id="10">
<section id="11"/>
</section>
</section>
<section>
<section id="4">
<section id="5"/>
</section>
</section>
<section/>
<bookmark/> <!-- here's the bookmark-->
<section id="6">
<section id="7">
<section id="8"/>
</section>
</section>
</section>
</content>

在这两种情况下,所需的结果都是 ID 5

使用 XSLT 1.0 和 XPath 1.0,我可以从 (1) 获取祖先

<xsl:value-of select="//bookmark/ancestor::*[@id][1]/@id"/>

或 (2) 中的前一个节点

<xsl:value-of select="//bookmark/preceding::*[@id][1]/@id"/>

如何从我的书签中获取具有 id 的最近祖先前一个节点?
我需要一个匹配这两种情况的 xsl:value-of。谢谢。

编辑:

解决方案也应该涵盖这个结构。所需的 id 仍然是 5

(3)

<?xml version="1.0" encoding="UTF-8"?>
<content>
<section id="1">
<section id="2"/>
<section id="3"/>
<section id="9"/>
</section>
<section id="4">
<section>
<section id="10"/>
<section id="5"/>
<section>
<bookmark/> <!-- here's the bookmark-->
<section id="6">
<section id="7">
<section id="8"/>
</section>
</section>
</section>
</section>
</section>
</content>

最佳答案

使用:

    (//bookmark/ancestor::*[@id][1]/@id 
|
//bookmark/preceding::*[@id][1]/@id
)
[last()]

验证:使用XSLT作为XPath的宿主,进行如下转换:

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>

<xsl:template match="/">
<xsl:value-of select=
"(//bookmark/ancestor::*[@id][1]/@id
|
//bookmark/preceding::*[@id][1]/@id
)
[last()]"/>
</xsl:template>
</xsl:stylesheet>

应用于所提供的三个 XML 文档中的任何一个时,会产生所需的正确结果:

5

我强烈推荐使用 XPath Visualizer用于玩/学习 XPath

关于xml - XPath 1.0 在 XML 树中具有属性的最接近的前导和/或祖先节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6554067/

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