【问题标题】:Use XSL to transform an XML list into an XHTML tree使用 XSL 将 XML 列表转换为 XHTML 树
【发布时间】:2011-02-27 13:35:23
【问题描述】:

我需要把这个 xml...

<root>
   <item id=’1’ parent_id=’0’>ONE</item>
   <item id=’2’ parent_id=’1’>TWO</item>
   <item id=’3’ parent_id=’1’>THREE</item>
   <item id=’4’ parent_id=’2’>FOUR</item>
   <item id=’5’ parent_id=’0’>FIVE</item>
</root>

并生成这个 xhtml……

<div class=’parent’>ONE</div>
<div class=’child’>
   <div class=’parent’>TWO</div>
   <div class=’child’>
      <div class=’parent’>FOUR</div>
   </div>
   <div class=’parent’>THREE</div>
</div>
<div class=’parent’>FIVE</div>

我知道如何收集子节点并将它们放在它们的父节点下,但是如果我已经将它们用作子节点,我无法掌握如何跳过将它们视为父节点。

【问题讨论】:

    标签: xml xhtml xslt tree


    【解决方案1】:

    测试了以下,似乎可以工作

    在根节点应用 parent_id = 0 的所有项,然后递归迭代任何子项..

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    
    <xsl:template match="/">
      <xsl:apply-templates select="root/item[@parent_id='0']"/>
    </xsl:template>
    
    
    <xsl:template match="item">
      <div class="parent"><xsl:value-of select="."/></div>
      <xsl:if test="count(../item[@parent_id=current()/@id]) != 0">
        <div class="child">
          <xsl:apply-templates select="../item[@parent_id=current()/@id]"/>
        </div>
      </xsl:if>
    </xsl:template>
    

    【讨论】:

      【解决方案2】:

      这个样式表:

      <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
          <xsl:key name="kItemById" match="item" use="@id"/>
          <xsl:key name="kItemByParentId" match="item" use="@parent_id"/>
          <xsl:template match="root">
              <xsl:apply-templates select="item[not(key('kItemById',@parent_id))]"/>
          </xsl:template>
          <xsl:template match="item">
              <xsl:variable name="vChild" select="key('kItemByParentId',@id)"/>
              <div class="parent">
                  <xsl:value-of select="."/>
              </div>
              <xsl:if test="$vChild">
                  <div class="child">
                      <xsl:apply-templates select="$vChild"/>
                  </div>
              </xsl:if>
          </xsl:template>
      </xsl:stylesheet>
      

      输出:

      <div class="parent">ONE</div>
      <div class="child">
          <div class="parent">TWO</div>
          <div class="child">
              <div class="parent">FOUR</div>
          </div>
          <div class="parent">THREE</div>
      </div>
      <div class="parent">FIVE</div>
      

      注意:交叉引用的键。

      【讨论】:

        猜你喜欢
        • 2019-03-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-07
        相关资源
        最近更新 更多