我正在尝试获取XML文件并使用XSLT进行转换 我试图转换的XML看起来像这样:
<root>
<TAG>10, 1, 3, 123, 4001, 34, 200, 105, 54, 0, 0, 0</TAG>
</root>
当我运行转换时,我希望结果显示如下:
<Field1>10</Field1>
<Field2>1</Field2>
...
<Field12>0</Field12>
但是,我的XSLT文件不像设计的那样工作 每当我运行转换器时,我都会回复这个作为回应:
<Field_1>
<TAG>10, 1, 3, 123, 4001, 34, 200, 105, 54, 0, 0, 0</TAG>
</Field_1>
这是我的XSLT文件:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:kml="http://www.opengis.net/kml/2.2" version="1.0">
<xsl:strip-space elements = "*"/>
<xsl:output method = "xml" indent = "yes"/>
<xsl:template match = "@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="root">
<xsl:call-template name="listItem">
<xsl:with-param name="tag" select="TAG"/>
</xsl:call-template>
</xsl:template>
<xsl:template name="listItem">
<xsl:param name="features"/>
<xsl:choose>
<xsl:when test="contains($features, ',')">
<xsl:element name="Field_{position()}">
<xsl:apply-templates select="@*|node()"/>
<xsl:value-of select="normalize-space(substring-before($features, ','))"/>
<xsl:variable name="nextValue" select="substring-after($features, ',')"/>
</xsl:element>
<xsl:if test="normalize-space($nextValue)">
<xsl:call-template name="listItem">
<xsl:with-param name="features" select="$nextValue"/>
</xsl:call-template>
</xsl:if>
</xsl:when>
<xsl:otherwise>
<xsl:element name="Field_{position()}">
<xsl:apply-templates select="@*|node()"/>
<xsl:value-of select="$features"/>
</xsl:element>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
有没有人对如何让我的XSLT文件将我的XML转换为所需的结果有任何建议? 拜托,谢谢你的帮助。
答案 0 :(得分:0)
使用此XSLT
它是XSLT版本1.0,并通过名为<xsl:template>
的名为field
的递归来分隔逗号分隔值并封装<Field>
元素中的每个值。元素的名称由静态字符串Field
和递归传递的名为cnt
的变量生成。
<?xml version="1.0" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" />
<xsl:template match="/root">
<root>
<xsl:call-template name="field">
<xsl:with-param name="cnt" select="1" />
<xsl:with-param name="txt" select="concat(TAG/text(),',')" />
</xsl:call-template>
</root>
</xsl:template>
<xsl:template name="field">
<xsl:param name="cnt" />
<xsl:param name="txt" />
<xsl:element name="{concat('Field',$cnt)}">
<xsl:value-of select="normalize-space(substring-before($txt,','))"/>
</xsl:element>
<xsl:if test="normalize-space(substring-after($txt,',')) != ''">
<xsl:call-template name="field">
<xsl:with-param name="cnt" select="$cnt + 1" />
<xsl:with-param name="txt" select="substring-after($txt,',')" />
</xsl:call-template>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
结果 - 根据需要 - 是:
<?xml version="1.0"?>
<root>
<Field1>10</Field1>
<Field2>1</Field2>
<Field3>3</Field3>
<Field4>123</Field4>
<Field5>4001</Field5>
<Field6>34</Field6>
<Field7>200</Field7>
<Field8>105</Field8>
<Field9>54</Field9>
<Field10>0</Field10>
<Field11>0</Field11>
<Field12>0</Field12>
</root>