使用XSLT进行一对多映射 - 从XML到CSV的转换

时间:2015-03-26 17:50:51

标签: xml csv xslt xslt-2.0

我正在使用XSL转换将XML文件转换为CSV文件。

我可以在CSV文件中获取身份属性值。但我也想获得重复元素的(备注)属性。

我的XML是:

<library>
  <book>
    <name identity="book1"/>
    <Remark id="1"/>
    <Remark id="2" />
  </book>
  <book>
    <name identity="book2"/>
    <Remark id="3"/>
    <Remark id="4" />
  </book>
</library>

我需要一个CSV,如下所示:

name_identity,remark_id
book1,1
book1,2
book2,3
book2,4

请就此提出建议。

2 个答案:

答案 0 :(得分:1)

以这种方式尝试:

<xsl:template match="/library">
    <xsl:text>name_identity,remark_id&#10;</xsl:text>
    <xsl:for-each select="book/Remark">
        <xsl:value-of select="../name/@identity"/>
        <xsl:text>,</xsl:text>
        <xsl:value-of select="@id"/>
        <xsl:if test="position()!=last()">
            <xsl:text>&#10;</xsl:text>
        </xsl:if>
    </xsl:for-each>
</xsl:template>

答案 1 :(得分:1)

如果您使用的是XSLT 2.0,则可以使用分组。以下代码分组由name/@identity

组成
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"  xmlns:xs="http://www.w3.org/2001/XMLSchema" >
<xsl:output method="text"/>
<xsl:template match="/">
<xsl:text>name_identity,remark_id&#10;</xsl:text>
    <xsl:for-each-group select="/library/book" group-by="name/@identity">
        <xsl:for-each select="current-group()/Remark">
            <xsl:value-of select="current-grouping-key()"/>
            <xsl:text>,</xsl:text>
            <xsl:value-of select="@id"/>
            <xsl:if test="position() != last()">
                <xsl:text>&#10;</xsl:text>
            </xsl:if>
        </xsl:for-each>
        <xsl:if test="position() != last()">
            <xsl:text>&#10;</xsl:text>
        </xsl:if>
    </xsl:for-each-group>
</xsl:template>
</xsl:stylesheet>