我正在寻找一个身份转换,它为每个节点添加一个排序属性。我希望每个节点的显式文档位置都是一个整数。
我相信所需的排序(就像在https://en.wikipedia.org/wiki/Tree_traversal#/media/File:Sorted_binary_tree_preorder.svg中一样)确实是默认排序,因为在后代轴上的选择会产生正确的排序编号:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method='xml' encoding='utf-8' indent='yes'/>
<xsl:template match="/*">
<root>
<xsl:apply-templates select="descendant::*">
</xsl:apply-templates>
</root>
</xsl:template>
<xsl:template match="*">
<xsl:copy>
<xsl:attribute name="doc_order">
<xsl:value-of select="position()"/>
</xsl:attribute>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
但我也需要保留输入文档结构,因为上面的代码生成了一个包含所有节点的平面列表。
example input:
<root>
<f>
<b>
<a/>
<d>
<c/>
<e/>
</d>
</b>
</f>
<g>
<i>
<h/>
</i>
</g>
</root>
desired output with explicit document order:
<root>
<f doc_order="1">
<b doc_order="2">
<a doc_order="3"/>
<d doc_order="4">
<c doc_order="5"/>
<e doc_order="6"/>
</d>
</b>
</f>
<g doc_order="7">
<i doc_order="8">
<h doc_order="9"/>
</i>
</g>
</root>
发布于 2015-12-11 20:29:06
了解xsl:number,它非常强大:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="/*//*">
<xsl:copy>
<xsl:attribute name="doc_order">
<xsl:number level="any" count="*" from="root"/>
</xsl:attribute>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>有关在线示例,请参阅http://xsltransform.net/94rmq6n。
https://stackoverflow.com/questions/34221471
复制相似问题