下面是三个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。
使用XSLT1.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-它的两个大小写都匹配。谢谢。
编辑:
该解决方案还应涵盖此结构。所需的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>
发布于 2011-07-02 10:29:36
使用的
(//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。
发布于 2011-07-02 07:23:55
尝试使用:
<xsl:value-of
select="//bookmark/ancestor::*[1]/descendant-or-self::*[last()-1]/@id"/>
它为这两个XML文档返回5
。
编辑:
在这种情况下,您可以使用简单的xsl:choose
<xsl:variable name="lastSibling"
select="//bookmark/preceding-sibling::*[1]"/>
<xsl:choose>
<xsl:when test="$lastSibling">
<xsl:value-of
select="$lastSibling/descendant-or-self::*[last()]/@id"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="//bookmark/ancestor::*[@id][1]/@id"/>
</xsl:otherwise>
</xsl:choose>
另一种通用解决方案:
<xsl:for-each
select="//section[following::bookmark or descendant::bookmark][@id]">
<xsl:if test="position() = last()">
<xsl:value-of select="./@id"/>
</xsl:if>
</xsl:for-each>
https://stackoverflow.com/questions/6554067
复制相似问题