使用按属性值的name属性重命名所有元素标记

时间:2014-11-13 08:21:31

标签: xml xslt

<IPECReactorLabel Name="Label" id= "someId">
      <IPECCodeName Name="CodeName">
        <String Name="Name" type="product">NH3</String>
        <String Name="Location">INLET</String>
        <String Name="GIPSValueType">REC</String>
      </IPECCodeName>
      <IPECReactorType Name="ReactorType">
        <String>NH3</String>
        <String Name="DesignCode">S-200</String>
      </IPECReactorType>
 </IPECReactorLabel>

上述xml中并非所有元素都具有Name属性。我通过XSLT想要实现的是保持整个xml相同,但是通过其Name属性的值更改元素标记。如果元素不包含Name属性,则元素标记应保持不变。 所以最终的xml wud就像:

<Label id= "someId">
<CodeName>
  <Name type="product">NH3</Name>
  <Location>INLET</Location>
  <GIPSValueType>REC</GIPSValueType>
</CodeName>
<ReactorType>
  <String>NH3</String>
  <DesignCode>S-200</DesignCode>
</ReactorType>
</Label>

我是XSLT的新手。在此先感谢您的帮助

1 个答案:

答案 0 :(得分:3)

XSLT identity template开始,它本身将复制所有节点

<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

这意味着,您只需要从要更改的节点中编写模板。在这种情况下,元素带有`@ Name&#39;属性。

 <xsl:template match="*[@Name]">

然后,您可以使用xsl:element构造创建新元素。

 <xsl:element name="{@Name}">

请注意Attribute Value Templates在此使用。花括号表示要计算的表达式以生成新元素名称。

试试这个XSLT

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

    <xsl:template match="*[@Name]">
      <xsl:element name="{@Name}">
        <xsl:apply-templates select="@*[name() != 'Name']|node()"/>
      </xsl:element>
    </xsl:template>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>