XSLT,将值连接到逗号分隔的字符串并过滤不必要的元素 [英] XSLT, concat values to comma separated string and filtering unnecessary elements
问题描述
如何将 XML1 转换为 XML2?
How to convert XML1 to XML2?
在进一步的步骤中(不是这个问题的一部分),我应该将 XML2 转换为 JSON.逗号分隔的值必须显示为数组:
{111, 222};
{456};
{777,555};
{777,555};
{678};
非常感谢您的努力,托马斯
Thanks so much in advance for your efforts, Thomas
XML1:
<transaction>
<records type="1" >
<record type="1" >
<field number="1" >
<subfield>
<item>111</item>
<item>222</item>
</subfield>
</field>
<field number="2" >
<subfield>
<item>456</item>
</subfield>
</field>
</record>
</records>
<records type="14" >
<record type="14" >
<field number="1" >
<subfield>
<item>777</item>
<item>555</item>
</subfield>
</field>
<field number="2" >
<subfield>
<item>678</item>
</subfield>
</field>
</record>
</records>
</transaction>
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>
推荐答案
首先,找一本关于 XSLT 的好书并好好阅读它.请参阅 在哪里可以找到有关 XSLT 文件的优秀教程? 的建议.
First, find a good book on XSLT and have a good read of it. See Where can I find a good tutorial on XSLT files? for suggestions.
其次,了解身份模板....
Secondly, learn about the Identity Template....
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
有了它,你就成功了一半!然后您只需要担心转换 subfield
元素.这意味着您只需要添加一个匹配 subfield
的模板来选择 item
节点.
With that in place, you are half-way there! You only need to then worry about transforming the subfield
elements. That means you just need to add a template matching subfield
which selects the item
nodes.
<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>
或者,更好的是,如果您可以使用 XSLT 2.0,请执行此操作...
Or, better still, if you can use XSLT 2.0, do this...
<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>
这确实假设每个 field
有一个 subfield
.
This does assume one subfield
per field
though.
这篇关于XSLT,将值连接到逗号分隔的字符串并过滤不必要的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!