Recursive XML through XSLT to XML

Posted by Patrick on Stack Overflow See other posts from Stack Overflow or by Patrick
Published on 2010-06-10T21:22:04Z Indexed on 2010/06/10 22:12 UTC
Read the original article Hit count: 379

Filed under:
|

Essentially, I have XML structured like this:

<A>
 <B>
  <1>data</1>
  <2>data</2>
  <C>
   <1>data</1>
   <2>data</2>
   <B>
    <1>data</1>
    <2>data</2>
    <C>
     <B>
      <1>data</1>
      <2>data</2>
     </B>
    </C>
   </B>
   <B>
    <1>data</1>
    <2>data</2>
   </B>
  </C>
 </B>
</A>

I am trying to get the output to look like this:

<A>
<B 1="data" 2="data">
    <C 1="data" 2="data">
        <B 1="data" 2="data">
            <C>
                <B 1="data" 2="data" >
                </B>
            </C>
        </B>
        <B 1="data" 2="data" >
        </B>
    </C>
</B>
</A>

I have figured out how to put everything as attributes and start looping through the elements. The issue I am facing is that when trying to get below the first C, nothing happens. Here is my code:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
    <xsl:output method="xml" indent="yes"/>

  <xsl:template match="/">
    <MenuDataResult>
      <B>
        <xsl:apply-templates />
      </B>
    </MenuDataResult>
  </xsl:template>

  <xsl:template match="B">
        <xsl:for-each select="B">
          <B ItemID="{B/ItemID/text()}" ItemType="{ItemType/text()}" ItemSubType="{ItemSubType/text()}"
                  ItemTitle="{ItemTitle/text()}" ItemImage="{ItemImage/text()}" ItemImageOverride="{ItemImageOverride/text()}"
                ItemLink="{ItemLink/text()}" ItemTarget="{ItemTarget/text()}>">
            <xsl:for-each select="C">
              <xsl:apply-templates select="C"/>
            </xsl:for-each>
          </B>
        </xsl:for-each>
  </xsl:template>

  <xsl:template match="C">
    <C ID="{ID/text()}" Title="{Title/text()}" Template="{Template/text()}"
          Type="{Type/text()}" Link="{Link/text()}" ParentID="{ParentID/text()}"
          AncestorID="{AncestorID/text()}" FolderID="{FolderID/text()}" Description="{Description/text()}"
          Image="{Image/text()}" ImageOverride="{ImageOverride/text()}">
      <xsl:for-each select="B">
        <xsl:apply-templates select=".//B"/>
      </xsl:for-each>
    </C>
  </xsl:template>

</xsl:stylesheet>

© Stack Overflow or respective owner

Related posts about Xml

Related posts about xslt