使用简单的XSLT进行XML到XML的转换

时间:2016-11-16 15:02:30

标签: xslt

我是XSLT的新手。请分享XSLT以获取以下输入和输出XML。

输入XML:

<Cars>
  <Car>
    <Company>Maruthi</Company>
    <Model>Alto</Model>
    <FeatureName>CC|Mileage</FeatureName>
    <FeatureValue>800|20</FeatureValue>
  </Car>
  <Car>
    <Company>Hyundai</Company>
    <Model>i10</Model>
    <FeatureName>CC|Mileage|Airbag</FeatureName>
    <FeatureValue>1000|18|Y</FeatureValue>
  </Car>
</Cars>

输出XML:

<Cars>
  <Car>
    <Company>Maruthi   </Company>
    <Model>Alto      </Model>
    <FeatureName><CC>800</CC><Mileage>20</Mileage></FeatureName>
  </Car>
  <Car>
    <Company>Hyundai   </Company>
    <Model>i10       </Model>
    <FeatureName><CC>1000</CC><Mileage>18</Mileage><Airbag>Y</Airbag></FeatureName>
  </Car>
</Cars>

请提供XSLT将输入转换为输出XML。

先谢谢。

1 个答案:

答案 0 :(得分:0)

这有效:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:template match="@*|node()">
      <xsl:copy>
        <xsl:apply-templates select="@*|node()" />
      </xsl:copy>
    </xsl:template>

        <xsl:template match="Cars/Car/FeatureValue"/>

    <xsl:template match="Cars/Car/FeatureName">
      <xsl:param name="featureNames" select="concat(./text(),'|')"/> 
      <xsl:param name="featureValues" select="concat(following-sibling::FeatureValue/text(),'|')"/>
      <FeatureName>
                <xsl:call-template name="features">
                     <xsl:with-param name="featureNames" select="$featureNames" />
                     <xsl:with-param name="featureValues" select="$featureValues" />
                </xsl:call-template>
      </FeatureName>
    </xsl:template>

    <xsl:template name="features">
       <xsl:param name="featureNames"/>
       <xsl:param name="featureValues"/>
       <xsl:param name="featureName" select="substring-before($featureNames,'|')"/>
             <xsl:param name="featureValue" select="substring-before($featureValues,'|')"/>
       <xsl:choose>
          <xsl:when test="$featureName">
             <xsl:element name="{$featureName}"><xsl:value-of select="$featureValue" /></xsl:element>
             <xsl:call-template name="features">
                <xsl:with-param name="featureNames" select="substring-after($featureNames,'|')" />
                        <xsl:with-param name="featureValues" select="substring-after($featureValues,'|')" />
             </xsl:call-template>
          </xsl:when>
       </xsl:choose>
    </xsl:template>
</xsl:stylesheet>