XPath 1.0 在 XML 树中具有属性的最接近的前一个和/或祖先节点 [英] XPath 1.0 closest preceding and/or ancestor node with an attribute in a XML Tree
问题描述
这里是三个 XML 树
Here are three XML-trees
(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.
The desired result is in both cases the id 5.
使用 XSLT 1.0 和 XPath 1.0 我可以从 (1) 获取祖先
With XSLT 1.0 and XPath 1.0 I can either get the ancestor from (1)
<xsl:value-of select="//bookmark/ancestor::*[@id][1]/@id"/>
或 (2) 中的前一个节点
or the preceding node from (2)
<xsl:value-of select="//bookmark/preceding::*[@id][1]/@id"/>
如何使用书签中的 ID 获取最近祖先或前一个节点?
我需要一个 xsl:value-of 匹配这两种情况.谢谢.
How do I get the nearest ancestor or preceding node with an id from my bookmark?
I need a single xsl:value-of which matches both cases. Thanks.
解决方案还应涵盖此结构.所需的 ID 仍然是 5.
The solution should also cover this structure. Desired id is still 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 的宿主,进行以下转换:
Verification: Using XSLT as host of XPath, the following transformation:
<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.
I strongly recomment using the XPath Visualizer for playing with / learning XPath.
这篇关于XPath 1.0 在 XML 树中具有属性的最接近的前一个和/或祖先节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!