tags:

views:

33

answers:

1

I am have trouble converting my xml using XSLT back to xml in the convert format, this is my XML below:

<?xml version="1.0" encoding="UTF-8" ?>
<DOCUMENTS>
<DOCUMENTS_INFO DOCUMENT_COUNT="8" />
  <DOCUMENT_GROUP NAME="Invoices" DISPLAY_NAME="INVOICES">
    <DOCUMENT>
      <FIELD>
<name>USER</name>
        <display_name>Deposited by</display_name>
        <value>machine</value>
      </FIELD>
      <FIELD>
        <name>DATE</name>
        <display_name>Archive date</display_name>
        <value>21/05/2009</value>
      </FIELD>
    </DOCUMENT>
    <DOCUMENT>
      <FIELD>
        <name>USER</name>
        <display_name>Deposited by</display_name>
        <value>machine</value>
      </FIELD>
      <FIELD>
        <name>DATE</name>
        <display_name>Archive date</display_name>
        <value>21/06/2009</value>
      </FIELD>
    </DOCUMENT>
  </DOCUMENT_GROUP>
</DOCUMENTS>

I need to convert so I can read it into my datagrid in ASP.NET so the output would be something like this below:

Deposited by | Archive date
     machine | 21/05/2009
     machine | 21/06/2009

Many Thanks

+1  A: 

You don't really need to do any conversion at all. If you want to pull the data into a dataset or something so that you can display it, all you need is a little bit of XPath.

The XPath to get all DOCUMENT elements:

//DOCUMENT

And the XPath to get a pair of value elements based on the name value, based in a DOCUMENT element:

FIELD[name = 'USER']/value
FIELD[name = 'DATE']/value

So depending on the technology you use to parse the XML, you'll basically need a loop over the first expression, and then run the following two expressions on the results of the first loop. In XSL it'll look something like this:

<xsl:template match="/">
  <xsl:for-each select="//DOCUMENT">
    <xsl:value-of select="FIELD[name = 'USER']/value"/>
    <xsl:text>|</xsl:text>
    <xsl:value-of select="FIELD[name = 'DATE']/value"/>
  </xsl:for-each>
</xsl:template>

Like anything, there's more than one way to do this. You can use a template as well:

<xsl:template match="/">
  <xsl:apply-templates select="//DOCUMENT" />
</xsl:template>
<xsl:template match="DOCUMENT">
  <xsl:value-of select="FIELD[name = 'USER']/value"/>
  <xsl:text>|</xsl:text>
  <xsl:value-of select="FIELD[name = 'DATE']/value"/>
</xsl:template>

Both of these will give the output you gave as an example, but you're probably better off reading the XPath values directly into a dataset or writing your own adapter to pull these values out and load them directly into a datagrid.

Welbog