我有以下xml
<EMPLS>
<EMPL>
<NAME>110</NAME>
<REMARK>R1</REMARK>
</EMPL>
<EMPL>
<NAME>111</NAME>
<REMARK>R1</REMARK>
<REMARK>R2</REMARK>
<REMARK>R3</REMARK>
</EMPL>
</EMPLS>并需要将xml转换为以下格式:
<EMPLS>
<EMPL>
<NAME>110</NAME>
<REMARK>R1</REMARK>
</EMPL>
<EMPL>
<NAME>111</NAME>
<REMARK>R1 R2 R3</REMARK>
</EMPL>
</EMPLS>我是xsl的新手,请您告诉我如何做到这一点。
发布于 2012-09-07 11:57:16
I此XSLT1.0转换
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:key name="kChildByName" match="EMPL/*"
use="concat(generate-id(..), '+', name())"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="EMPL/*" priority="0"/>
<xsl:template match=
"EMPL/*
[generate-id()
=
generate-id(key('kChildByName',
concat(generate-id(..), '+', name())
)[1]
)
]">
<xsl:copy>
<xsl:for-each select="key('kChildByName',
concat(generate-id(..), '+', name())
)">
<xsl:if test="not(position()=1)"><xsl:text> </xsl:text></xsl:if>
<xsl:value-of select="."/>
</xsl:for-each>
</xsl:copy>
</xsl:template>
<xsl:template match="EMPL/*" priority="0"/>
</xsl:stylesheet>应用于所提供的XML文档(纠正了许多畸形):
<EMPLS>
<EMPL>
<NAME>110</NAME>
<REMARK>R1</REMARK>
</EMPL>
<EMPL>
<NAME>111</NAME>
<REMARK>R1</REMARK>
<REMARK>R2</REMARK>
<REMARK>R3</REMARK>
</EMPL>
</EMPLS>生成想要的、正确的结果
<EMPLS>
<EMPL>
<NAME>110</NAME>
<REMARK>R1</REMARK>
</EMPL>
<EMPL>
<NAME>111</NAME>
<REMARK>R1 R2 R3</REMARK>
</EMPL>
</EMPLS>解释
II. XSLT2.0解决方案:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="EMPL">
<xsl:copy>
<xsl:for-each-group select="*" group-by="name()">
<xsl:copy>
<xsl:value-of select="current-group()" separator=" "/>
</xsl:copy>
</xsl:for-each-group>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>解释
https://stackoverflow.com/questions/12316859
复制相似问题