XSLT, XML: How to disentangle grouped blocks into

2019-09-17 16:29发布

I have the following XML with some Nested elements. I need please help for converting this XML to a flat hierarchy.

You may would like to take a look at this question as well: XSLT, XML: Grouping by attribute value

Thanks in advance for your support. Thomas

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

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

1条回答
Rolldiameter
2楼-- · 2019-09-17 17:17

Try this:

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

The <xsl:text> tags are to preserve some of the formatting in the output XML but I don't know if you're interested in that. Feel free to remove them if not.

It works by using a for-each to look for elements in the input XML. The // at the start of the select attribute means that it can match anywhere within the document, not just at the current level.

It then simply uses copy-of to insert the entirety of the node found in the for-each.

查看更多
登录 后发表回答