首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >xslt-1.0深度优先预排序遍历编号

xslt-1.0深度优先预排序遍历编号
EN

Stack Overflow用户
提问于 2015-12-11 18:36:40
回答 1查看 183关注 0票数 0

我正在寻找一个身份转换,它为每个节点添加一个排序属性。我希望每个节点的显式文档位置都是一个整数。

我相信所需的排序(就像在https://en.wikipedia.org/wiki/Tree_traversal#/media/File:Sorted_binary_tree_preorder.svg中一样)确实是默认排序,因为在后代轴上的选择会产生正确的排序编号:

代码语言:javascript
复制
<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>

但我也需要保留输入文档结构,因为上面的代码生成了一个包含所有节点的平面列表。

代码语言:javascript
复制
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>

EN

回答 1

Stack Overflow用户

发布于 2015-12-11 20:29:06

了解xsl:number,它非常强大:

代码语言:javascript
复制
<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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34221471

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档