XSLT 如何应用递归从平面文件转换为嵌套树 [英] XSLT How to apply recursion to transform from a flat file to a nested tree
本文介绍了XSLT 如何应用递归从平面文件转换为嵌套树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道还有其他几个与此类似的问题/答案,但我还没有读过一个解决我对这种转换的困惑的问题/答案.我需要从这种格式移动 XML 文档:
I know that there are several other question/answers similar to this, but I haven't read one that addresses my confusion over this transform. I need to move an XML document from this format:
<root>
<row>
<t0>1</t0>
<title>Main Title</title>
</row>
<row>
<t0>2</t0>
<title>Secondary Title</title>
<note>Note</note>
</row>
<row>
<t0>3</t0>
<title>Tertiary Title</title>
</row>
<row>
<t0>3</t0>
<title>Another Title</title>
</row>
<row>
<t0>2</t0>
<title>A Second Secondary Title</title>
<note>Note</note>
</row>
<row>
<t0>3</t0>
<title>Third Level Title</title>
</row>
<row>
<t0>3</t0>
<title>Title at Level Three</title>
</row>
</root>
到这种格式:
<root>
<header>List</header>
<t01>
<title>Main Title</title>
<t02>
<title>Secondary Title</title>
<note>Note</note>
<t03>
<title>Tertiary Title</title>
</t03>
<t03>
<title>Another Title</title>
</t03>
</t02>
<t02>
<title>A Second Secondary Title</title>
<note>Note</note>
<t03>
<title>Third Level Title</title>
</t03>
<t03>
<title>Title at Level Three</title>
</t03>
</t02>
</t01>
</root>
我正在使用 XSLT 2.0 并且我对递归地应用 for-each-group 感到厌烦.感谢您的时间 &麻烦.
I'm using XSLT 2.0 and I'm getting hung up on applying for-each-group recursively. Thanks for your time & trouble.
推荐答案
对于 XSLT 2.0,我强烈建议将 for-each-grouping
与递归函数或模板一起使用;下面是一个使用函数的示例:
With XSLT 2.0 I would strongly suggest to use the for-each-grouping
together with a recursive function or template; below is a sample using a function:
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="2.0"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:mf="http://example.com/mf"
exclude-result-prefixes="xs mf">
<xsl:output indent="yes"/>
<xsl:function name="mf:group" as="element()*">
<xsl:param name="elements" as="element(row)*"/>
<xsl:param name="level" as="xs:integer"/>
<xsl:for-each-group select="$elements" group-starting-with="row[t0 = $level]">
<xsl:element name="t{format-number($level, '00')}">
<xsl:copy-of select="* except t0"/>
<xsl:sequence select="mf:group(current-group() except ., $level + 1)"/>
</xsl:element>
</xsl:for-each-group>
</xsl:function>
<xsl:template match="root">
<xsl:copy>
<header>List</header>
<xsl:sequence select="mf:group(row, 1)"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
这篇关于XSLT 如何应用递归从平面文件转换为嵌套树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文