xmlファイル内の各ノードのxpathを生成し、このパスを各ノードの属性として追加するには、ヘルプhereが見つかりました。 xsltファイルは次のようになります。xsltを使用してノードからxpathを生成する2
<?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という2つの関数を持っています。最初のノードはノード名のあるパスを返し、2番目のノードは対応する番号を返します。それらをスマートな方法で組み合わせることは可能ですか?
<?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>
私はあなたがこれらをテストしたとは思わない。 –
私はごくまれにテストコードサンプルをテストします。読者はコードをそのまま使うのではなく、そのコードを理解して、間違ったエラーを残すことがそのコードを確実にするのに役立つことが重要だと思います。 –