2016-11-16 168 views
0

我是XSLT的新手。请为以下输入和输出XML共享XSLT。使用简单的XSLT进行XML到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

欢迎SO :-)我们不是一个代码编写的服务。请分享您尝试的问题并向您现有的代码提出具体问题。通过编辑问题来完成。 –

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

谢谢Soumik! – user2916849

+1

如果这确实回答您的问题,请将其标记为已回答 –