简体   繁体   English

一对多映射-使用XSLT从XML转换为CSV

[英]One to many mapping- conversion from XML to CSV using XSLT

I am using XSL transformation to convert a XML file to CSV file. 我正在使用XSL转换将XML文件转换为CSV文件。

I could get the identity attribute value in CSV file.But I want to get the repeated element's(Remark) attribute also. 我可以在CSV文件中获取identity属性值。但是我也想获取重复元素的(Remark)属性。

My XML is: 我的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>

I need a CSV as below: 我需要以下CSV:

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

Kindly advice on this. 请对此提出建议。

Try it this way: 尝试这种方式:

<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>

If you are using XSLT 2.0, You could use grouping. 如果您使用的是XSLT 2.0,则可以使用分组。 The below code groups by name/@identity 以下代码按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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM