【发布时间】:2016-11-30 19:39:16
【问题描述】:
要为 xml 文件中的每个节点生成 xpath 并将此路径作为属性添加到每个节点,我找到了一些帮助 here。 xslt 文件应如下所示:
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes" encoding="UTF-8"/>
<xsl:strip-space elements="*"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="*">
<xsl:copy>
<xsl:attribute name="xpath">
<xsl:for-each select="ancestor-or-self::*">
<xsl:value-of select="concat('/',local-name())"/>
<!--Predicate is only output when needed.-->
<xsl:if
test="(preceding-sibling::*|following-sibling::*)[local-name()=local-name(current())]">
<xsl:value-of
select="concat('[',count(preceding-sibling::*[local-name()=local-name(current())])+1,']')"
/>
</xsl:if>
</xsl:for-each>
</xsl:attribute>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="text()"/>
</xsl:stylesheet>
现在我对使用 xslt 2.0 的更紧凑的方式感兴趣。例如,在下面的 xslt 文件中,我有两个函数 createXPath 和 getXpath。第一个返回带有节点名称的路径,第二个返回相应的编号。是否有可能以聪明的方式将它们结合起来?
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:func="http://www.functx.com">
<xsl:output method="xml" encoding="utf-8"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:attribute name="xpath">
<xsl:value-of select="func:getXpath(.)"/>
</xsl:attribute>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:function name="func:createXPath" >
<xsl:param name="pNode" as="node()"/>
<xsl:value-of select="$pNode/ancestor-or-self::*/local-name()" separator="/"/>
</xsl:function>
<xsl:function name="func:getXpath">
<xsl:param name="pNode" as="node()"/>
<xsl:value-of select="$pNode/ancestor-or-self::*/(count(preceding-sibling::*) + 1)" separator="/" />
</xsl:function>
</xsl:stylesheet>
【问题讨论】: