简体   繁体   中英

Convert XML to CSV using XSLT

Convert the XML into CSV using XSLT transformation

<start>
<article>
<key>key1</key>

<definition type="m">
<![CDATA[abcdefghijk]]>
</definition>
</article>

<article>
<key>key2</key>

<definition type="m">
<![CDATA[bcdefghijkl]]>
</definition>
</article>
</start>

csv will look like

key1,abcdefghijk
key2,bcdefghijkl

I'v learn w3c school xslt tutorial,but can't get practice. Can someone write XSLT code for transformation?

You can achieve the wanted result with a single template:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="start/article">
        <xsl:if test="position()>1">
            <xsl:text>&#xA;</xsl:text>
        </xsl:if>
        <xsl:value-of select="normalize-space(
            concat(key,'; ',definition))"/>
    </xsl:template>

</xsl:stylesheet>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text" indent="yes"/>

  <xsl:template match="/">
    <xsl:apply-templates select="//article/*"/>
  </xsl:template>

  <xsl:template match="key">
    <xsl:copy-of select="normalize-space(concat(., ';'))"/>
  </xsl:template>

  <xsl:template match="definition">
    <xsl:copy-of select="normalize-space(.)"/>
    <xsl:text>&#xD;&#xA;</xsl:text>
  </xsl:template>

</xsl:stylesheet>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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