【问题标题】:Renaming all element tags with name attribute by attribute value按属性值重命名所有带有 name 属性的元素标签
【发布时间】:2014-11-13 08:21:31
【问题描述】:
<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 的新手。提前感谢您的帮助

【问题讨论】:

    标签: xml xslt


    【解决方案1】:

    XSLT identity template 开始,它自己将复制所有节点不变

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

    这意味着,您只需从要更改的节点编写模板。在这种情况下,具有“@Name”属性的元素。

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

    【讨论】:

      猜你喜欢
      • 2013-05-28
      • 2016-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多