Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Nested XML to CSV XSLT problem

Status
Not open for further replies.

stdoubt

IS-IT--Management
May 19, 2011
1
AU
Hi,

I am pretty new to xml and xsl, so I might be asking a dumb question, but I am trying to write some an xslt to convert a nested xml into a comma seperated one.

My xml looks similar to this:
Code:
<?xml version="1.0" encoding="utf-8"?>
<Field>
 <Name>name1</Name>
 <Fid>blah1</Fid>
 <Type>Enumeration</Type>
  <Enumeration>
  <Enum>
    <Number>2</Number>
    <Value>bla2h</Value>
  </Enum>
  <Enum>
    <Number>1</Number>
    <Value>blah</Value>
  </Enum>
  </Enumeration>
</Field>

and I'd like to convert it to this:
name1,blah1,Enumeration,2,bla2h,1,blah

So I wrote the following xsl:
Code:
<xsl:stylesheet version="1.0" xmlns:xsl="[URL unfurl="true"]http://www.w3.org/1999/XSL/Transform">[/URL]
<xsl:output method="text"/>

 <xsl:template match="Field">
  <xsl:for-each select="*">
   <xsl:value-of select="."/>
   <xsl:if test="position() != last()">
    <xsl:value-of select="','"/>
   </xsl:if>
   </xsl:for-each>
  <xsl:text>&#10;</xsl:text>
 </xsl:template>

</xsl:stylesheet>

Unfortunately, this gives:
name1,blah1,Enumeration, 2 bla2h 1 blah

What am I doing wrong?
 
You most likely will need to use recursion to walk the structure. There are many tutorials on the web for XSLT recursion.

What you are seeing in your results is the fact that the value of a node that has child nodes is the concatenation of all the text nodes. That is not what you want.

final hint: XSLT does not have an assignment operator in the normal procedural programming sense. That is, you cannot do a = a + 1. You probably know this. However, as you will see in the recursion tutorials, you can overcome this using template parameters. This might be handy in determining what character to emit in your CSV line before the value of a node.

Tom Morrison
Micro Focus
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top