使用XSL进行XML转换并将源元素名称作为XML值

时间:2016-10-28 11:05:19

标签: xml xslt

我需要转换以下XML:

<?xml version="1.0" encoding="UTF-8"?>

 <cd>
    <title>Empire Burlesque</title>
    <artist>Bob Dylan</artist>
    <country>USA</country>
    <company>Columbia</company>
    <price>10.90</price>
    <year>1985</year>
  </cd>

我需要的目标XML是这样的:

<params>
<param>
<key>title</key>
<value>Empire Burlesque</value>
</param>
<param>
<key>artist</key>
<value>Bob Dylan<</value>
</param>
<param>
<key>country</key>
<value>USA</value>
</param>
<param>
<key>company</key>
<value>Columbia</value>
</param>
<param>
<key>price</key>
<value>10.90</value>
</param>
<param>
<key>year</key>
<value>1985</value>
</param>
</params>

XSL文件对我来说应该是什么样的?

1 个答案:

答案 0 :(得分:1)

<强>予。 XSLT 1.0

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">

    <xsl:output omit-xml-declaration="yes"/>

    <xsl:template match="/">
        <params>
            <xsl:apply-templates select="cd"/>
        </params>
    </xsl:template>

    <xsl:template match="cd/*">
        <param>
            <key><xsl:value-of select="name()"/></key>
            <value><xsl:value-of select="."/></value>
        </param>
    </xsl:template>

</xsl:stylesheet>

<强> II。输出

<params>
    <param><key>title</key><value>Empire Burlesque</value></param>
    <param><key>artist</key><value>Bob Dylan</value></param>
    <param><key>country</key><value>USA</value></param>
    <param><key>company</key><value>Columbia</value></param>
    <param><key>price</key><value>10.90</value></param>
    <param><key>year</key><value>1985</value></param>
</params>