我有一个像这样的xml,
<doc>
<chap>
<sec originator="ABC">
<app originator="body">
<sec originator="body">
<p>text</p>
</sec>
</app>
</sec>
</chap>
<chap>
<chap>
<app originator="DEF">
<sec originator="body">
<sec>
<p>text2</p>
</sec>
</sec>
</app>
</chap>
</chap>
<sec originator="GHI">
<sec originator="body">
<p>text</p>
</sec>
</sec>
<app originator="KLM">
<sec>
<sec>
<p>text2</p>
</sec>
</sec>
</app>
</doc>
我已经为<p>
节点编写了模板,因此我需要获得距离最远的祖先<sec>
或<app>
节点originator
属性值。
我的xpath是
//p/(ancestor::app[@originator][last()] | ancestor::sec[@originator][last()])/@originator
这将选择originator
属性值ABC, body, DEF, body, GHI, KLM
..但我需要的是ABC, DEF, GHI, KLM
。
如何更改xpath以获取最远距离<sec>
或<app>
节点originator
属性值
答案 0 :(得分:1)
在p
元素的上下文中,您可以选择ancestor::*[self::app[@originator] | self::sec[@originator]][last()]/@originator
,请参阅http://xsltransform.net/bFWR5EQ
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="p">
<p orig="{ancestor::*[self::app[@originator] | self::sec[@originator]][last()]/@originator}">
<xsl:apply-templates/>
</p>
</xsl:template>
</xsl:transform>
给予
<?xml version="1.0" encoding="UTF-8"?><doc>
<chap>
<sec originator="ABC">
<app originator="body">
<sec originator="body">
<p orig="ABC">text</p>
</sec>
</app>
</sec>
</chap>
<chap>
<chap>
<app originator="DEF">
<sec originator="body">
<sec>
<p orig="DEF">text2</p>
</sec>
</sec>
</app>
</chap>
</chap>
<sec originator="GHI">
<sec originator="body">
<p orig="GHI">text</p>
</sec>
</sec>
<app originator="KLM">
<sec>
<sec>
<p orig="KLM">text2</p>
</sec>
</sec>
</app>
</doc>