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

亡梦爱人 提交于 2019-12-25 12:02:12

问题


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:


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.



来源:https://stackoverflow.com/questions/46767754/xslt-xml-how-to-disentangle-grouped-blocks-into-a-flat-hierarchy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!