ノードの高さは、最も遠いリーフ ノードへのパスの長さです。ノードの深さに似ていますが、逆方向ですが、解決策はそれほど単純ではないと思います。
これには実際的な用途はありません。最初に必要だと思っていた問題が、必要ないことが判明しました。しかし、それに気付く前に解決策を書いたので、将来便利になる場合に備えてここに投稿すると思いました。
どうしたの
max(.//node()/count(ancestor::*)) - count(ancestor::*)
使用:
if(node())
then
max(.//node()[not(node())]/count(ancestor::node()))
-
count(ancestor::node())
else 0
そして、すべての要素に「高さ」属性を追加する変換:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="*">
<xsl:copy>
<xsl:apply-templates select="@*"/>
<xsl:attribute name="height" select=
"if(node())
then
max(.//node()[not(node())]/count(ancestor::node()))
-
count(ancestor::node())
else 0
"/>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
この変換が適用されると、たとえば次の XML ドキュメントに次のようになります。
<producers>
<producer>
<id>8</id>
<name>Emåmejeriet</name>
<street>Grenvägen 1-3</street>
<postal>577 39</postal>
<city>Hultsfred</city>
<weburl>http://www.emamejerie3t.se</weburl>
<certified/>
</producer>
</producers>
必要な正しい結果が生成されます。
<producers height="3">
<producer height="2">
<id height="1">8</id>
<name height="1">Emåmejeriet</name>
<street height="1">Grenvägen 1-3</street>
<postal height="1">577 39</postal>
<city height="1">Hultsfred</city>
<weburl height="1">http://www.emamejerie3t.se</weburl>
<certified height="0"/>
</producer>
</producers>
次のスタイルシートは、各ノードをheight
属性でマークします。
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:exsl="http://exslt.org/common"
xmlns:math="http://exslt.org/math"
extension-element-prefixes="math exsl"
version="1.0">
<xsl:output omit-xml-declaration="yes" indent="no"/>
<xsl:template name="height">
<xsl:param name="node"/>
<xsl:choose>
<xsl:when test="$node/node()">
<xsl:variable name="child-heights">
<xsl:for-each select="$node/node()">
<height>
<xsl:call-template name="height">
<xsl:with-param name="node" select="."/>
</xsl:call-template>
</height>
</xsl:for-each>
</xsl:variable>
<xsl:value-of select="math:max(exsl:node-set($child-heights)/height) + 1"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="0"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="*">
<xsl:copy>
<xsl:attribute name="height">
<xsl:call-template name="height">
<xsl:with-param name="node" select="."/>
</xsl:call-template>
</xsl:attribute>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>