Xml XSLT,将值转换为逗号分隔的字符串并过滤不必要的元素
如何将XML1转换为XML2 在下一步(不是这个问题的一部分)中,我应该将XML2转换为JSON。 然后,逗号分隔的值必须显示为数组: 提前非常感谢你的努力,托马斯 XML1:Xml XSLT,将值转换为逗号分隔的字符串并过滤不必要的元素,xml,xslt,Xml,Xslt,如何将XML1转换为XML2 在下一步(不是这个问题的一部分)中,我应该将XML2转换为JSON。 然后,逗号分隔的值必须显示为数组: 提前非常感谢你的努力,托马斯 XML1: 111 222 456 777 555 678 XML 2: <transaction> <records type="1" > <record type="1" > <field number="1" >111,222</subf
111
222
456
777
555
678
XML 2:
<transaction>
<records type="1" >
<record type="1" >
<field number="1" >111,222</subfield>
</field>
<field number="2" >456</field>
</record>
</records>
<records type="14" >
<record type="14" >
<field number="1" >777,555</field>
<field number="2" >678</field>
</record>
</records>
</transaction>
111,222
456
777,555
678
首先,找到一本关于XSLT的好书,并仔细阅读。有关建议,请参阅
其次,了解身份模板
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
或者,更好的是,如果您可以使用XSLT2.0,请执行以下操作
<xsl:template match="subfield">
<xsl:value-of select="item" separator="," />
</xsl:template>
试试这个XSLT
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="xml" indent="yes" />
<xsl:strip-space elements="*" />
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="subfield">
<xsl:value-of select="item" separator="," />
</xsl:template>
</xsl:stylesheet>
这确实假设每个
字段有一个子字段。实际上,我试图用Java解决这个问题。但1,5天后,我意识到这不是一个很好的方法。由于我是XSLT的绝对新手,我希望得到一些提示,让我找到正确的方向。提前谢谢你,托马希·蒂姆,你和这里的其他好人把我从痛苦中解救出来。非常感谢我的朋友!我真的开始理解XSLT的本质,主要是所有模板之母的含义:。
谢谢其他提示和链接。向Thomas致以最诚挚的问候——事实上,我不应该开发XSLT,而应该开发RESTfulWeb服务。现在,在两周内,我必须学习高级XSLT1.0、2.0和3.0,并实现复杂的模板!离周末还有两天。我一定要挺过这周:-)样式表上使用
的版本应该是2.0
,不是吗?Thomas似乎在其他地方使用XSLT 3.0,因此标识模板可以在该版本中更紧凑地表示为
。感谢您指出版本号的问题。我修正了我的答案。
<xsl:template match="subfield">
<xsl:for-each select="item">
<xsl:if test="position() > 1">,</xsl:if>
<xsl:value-of select="." />
</xsl:for-each>
</xsl:template>
<xsl:template match="subfield">
<xsl:value-of select="item" separator="," />
</xsl:template>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="xml" indent="yes" />
<xsl:strip-space elements="*" />
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="subfield">
<xsl:value-of select="item" separator="," />
</xsl:template>
</xsl:stylesheet>