我有一个管道分隔的文本文件,如下所示,我需要使用 xsl 将其转换为格式良好的 xml 结构(如下所示的示例)。下面的 xsl 是我解决此问题的(最新)尝试 - 但是当逐行遍历文件时,我似乎无法找到将 002 级元素封装在 001 级中的方法,即保持父子关系。有人可以帮忙吗?
管道分隔文件 - 输入
001|XXX|YYY
002|AAA|BBB
002|CCC|DD
001|EEF|XXX
002|HHH|GGG
XML 文件 - 所需的输出
<root>
<level001>
<elem name="field1">001</elem>
<elem name="field2">XXX</elem>
<elem name="field3">YYY</elem>
<level002>
<elem name="field1">002</elem>
<elem name="field2">AAA</elem>
<elem name="field3">BBB</elem>
</level002>
<level002>
<elem name="field1">002</elem>
<elem name="field2">CCC</elem>
<elem name="field3">DD</elem>
</level002>
</level001>
<level001>
<elem name="field1">001</elem>
<elem name="field2">XXX</elem>
<elem name="field3">YYY</elem>
<level002>
<elem name="field1">002</elem>
<elem name="field2">HHH</elem>
<elem name="field3">GG</elem>
</level002>
</level001>
</root>
当前 XSL
<xsl:variable name="Cols">
<col>field1,1</col>
<col>field2,2</col>
<col>field3,3</col>
</xsl:variable>
<xsl:template match="/" name="main">
<xsl:choose>
<xsl:when test="unparsed-text-available($pathToCSV, $encoding)">
<xsl:variable name="csv" select="unparsed-text($pathToCSV, $encoding)" />
<xsl:variable name="lines" select="tokenize($csv, '\n')" as="xs:string+" />
<root>
<xsl:for-each select="$lines[position() > 0]">
<xsl:if test="translate(., '  	 ', '') != ''">
<level001>
<xsl:variable name="line" select="." />
<xsl:variable name="columns" select="tokenize(.,'\|')" as="xs:string+"/>
<xsl:choose>
<xsl:when test="$columns[1]='001'">
<xsl:for-each select="$Cols/col">
<xsl:variable name="column" select="number(substring-after(.,','))"/>
<elem name="{substring-before(.,',')}">
<!-- trims the whitespace from the beginning and the ending of the value -->
<xsl:value-of select="replace(replace($columns[$column],'\s+$',''),'^\s+','')"/>
</elem>
</xsl:for-each>
</xsl:when>
<xsl:when test="$columns[1]='002'">
<level002>
<xsl:for-each select="$Cols/col">
<xsl:variable name="column" select="number(substring-after(.,','))"/>
<elem name="{substring-before(.,',')}">
<!-- trims the whitespace from the beginning and the ending of the value -->
<xsl:value-of select="replace(replace($columns[$column],'\s+$',''),'^\s+','')"/>
</elem>
</xsl:for-each>
</level002>
</xsl:when>
</xsl:choose>
</level001>
</xsl:if>
</xsl:for-each>
</root>
</xsl:when>
</xsl:choose>