XSLT,XML:如何将分组块分解为平面层次结构?

XSLT, XML: How to disentangle grouped blocks into a flat hierarchy?

我有以下 XML 和一些嵌套元素。 我需要帮助将此 XML 转换为平面层次结构。

你可能也想看看这个问题:

在此先感谢您的支持。 托马斯

原文XML:

<transaction>
  <records type="1" >
      <record type="1" >
        <field number="1" >
            <item >223</item>
        </field>
      </record>
  </records>

  <records type="14" >
      <record type="14" >
        <field number="1" >
            <item >777</item>
        </field>
      </record>

      <record type="14" >
        <field number="1" >
            <item >555</item>
        </field>
      </record>
  </records>

  <record type="200" >
    <field number="1" >
        <item>546</item>
    </field>
  </record>

  <record type="201" >
    <field number="1" >
        <item>123</item>
    </field>
  </record>
</transaction>

目标XML:

<transaction>    
  <record type="1" >
    <field number="1" >
        <item >223</item>
    </field>
  </record>

  <record type="14" >
    <field number="1" >
        <item >777</item>
    </field>
  </record>

  <record type="14" >
    <field number="1" >
        <item >555</item>
    </field>
  </record> 

  <record type="200" >
    <field number="1" >
        <item>546</item>
    </field>
  </record>

  <record type="201" >
    <field number="1" >
        <item>123</item>
    </field>
  </record>
</transaction>

试试这个:

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

    <xsl:template match="/">
        <xsl:text>&#x0A;</xsl:text>
        <transaction>
            <xsl:text>&#x0A;</xsl:text>
            <xsl:for-each select="//record">
                <xsl:copy-of select="." />
                <xsl:text>&#x0A;</xsl:text>
            </xsl:for-each>
            <xsl:text>&#x0A;</xsl:text>
        </transaction>
    </xsl:template>

</xsl:stylesheet>

<xsl:text> 标记用于在输出中保留一些格式 XML,但我不知道您是否对此感兴趣。如果没有,请随意删除它们。

它的工作原理是使用 for-each 在输入 XML 中查找元素。 select 属性开头的 // 意味着它可以匹配文档中的任何位置,而不仅仅是当前级别。

然后它简单地使用 copy-of 插入在 for-each 中找到的整个节点。