【问题标题】:How to add ID\ParentID with XSLT如何使用 XSLT 添加 ID\ParentID
【发布时间】:2013-09-16 09:41:44
【问题描述】:

给定一个 xml 树示例:

<root>
  <child></child>
  <child>
    <child></child>
  </child>
</root>

谁能帮我设计一个样式表,添加 id 和 parentid 属性:

<root id="1" parentID="">
  <child id="2" parentID="1"></child>
  <child id="3" parentID="1">
    <child id="4" parentID="3"></child>
  </child>
</root>

【问题讨论】:

    标签: xml xslt hierarchy


    【解决方案1】:

    使用

    <xsl:stylesheet
        version="1.0"
        xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    
    <xsl:template match="*">
      <xsl:copy>
        <xsl:attribute name="id">
          <xsl:apply-templates select="." mode="number"/>
        </xsl:attribute>
        <xsl:attribute name="parentId">
          <xsl:apply-templates select="parent::*" mode="number"/>
        </xsl:attribute>
        <xsl:apply-templates select="@* | node()"/>
      </xsl:copy>
    </xsl:template>
    
    <xsl:template match="*" mode="number">
      <xsl:number level="any" count="*"/>
    </xsl:template>
    
    </xsl:stylesheet>
    

    【讨论】:

    • 这很好用,谢谢马丁。顺便说一句,我将第一个 match="*" 更改为 match="@*|node()" 以附加新属性而不是替换现有属性。
    猜你喜欢
    • 1970-01-01
    • 2016-02-08
    • 2020-08-26
    • 1970-01-01
    • 1970-01-01
    • 2016-01-06
    • 1970-01-01
    • 2011-02-12
    • 2013-02-05
    相关资源
    最近更新 更多