Groups | Blog | Home
all groups > dotnet xml > march 2006 >

dotnet xml : How can I loop through XML like this? thanks


davidw
3/10/2006 9:39:05 AM
I have flat xml like this

<field name="a1"/>
<field name="a2" merge="true"/>
<field name="a3"/>
<field name="a4"/>
<field name="a5" merge="true"/>
<field name="a6" merge="true"/>
<field name="a7"/>

but I want to loop through them like this
<field name="a1">
<field name="a2" merge="true"/>
</field>
<field name="a3"/>
<field name="a4">
<field name="a5" merge="true"/>
<field name="a6" merge="true"/>
</field>
<field name="a7"/>

It means nodes with merge attribute is child of the previous node. I only
need handle one level for now, any suggestion?

thanks



davidw
3/10/2006 11:29:04 AM
Nice! that is exactly I need, you are the man!


[quoted text, click to view]

Martin Honnen
3/10/2006 7:08:13 PM


[quoted text, click to view]

You could apply an XSLT transformation to have the nested structure:

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

<xsl:output method="xml" indent="yes" />

<xsl:template match="fields">
<xsl:copy>
<xsl:apply-templates select="@*" />
<xsl:apply-templates select="field[not(@merge)]" />
</xsl:copy>
</xsl:template>

<xsl:template match="field">
<xsl:copy>
<xsl:apply-templates select="@*" />
<xsl:apply-templates
select="following-sibling::field[1][@merge = 'true']" mode="child" />
</xsl:copy>
</xsl:template>

<xsl:template match="field" mode="child">
<xsl:copy>
<xsl:apply-templates select="@* | node()" />
</xsl:copy>
<xsl:apply-templates
select="following-sibling::field[1][@merge = 'true']" mode="child" />
</xsl:template>

<xsl:template match="@*">
<xsl:copy />
</xsl:template>

</xsl:stylesheet>

--

Martin Honnen --- MVP XML
AddThis Social Bookmark Button