XML

Dealing with XML files as a place to store data is very common in ASP.NET, and it’s straightforward to implement, just use the XmlDataSource, and set the DataFile property to your XML file then set the DataSourceID of the data control (GrideView, DataList…) to the XmlDataSource. This post demonstrates a simple example of transforming XML using XSLT.

If data records in the XML file are described as attributes, then there is no problem while displaying the data records directly in the GrideView as the following example:

<People>
    <Person name="Bashar Kokash" age="22" />
    <Person name="Bassl Kokash" age="21" />
    <Person name="Morhaf Musa" age="25"/>
</People>

But what if the XML file was written differently and the previous attributes are represented as child nodes instead so that the previous XML will look something like this:

<People>
    <Person>
      <name>
        Bashar Kokash
      </name>
      <age>
        22
      </age>
    </Person>
    <Person>
      <name>
        Bassl Kokash
      </name>
      <age>
        21
      </age>
    </Person>
    <Person>
      <name>
        Morhaf Musa
      </name>
      <age>
        25
      </age>
    </Person>
</People>

Simply we can rewrite the XML file to be just like what we want, i.e., as records, each record is represented by a node and a set of attributes. Actually, it’s not that simple when dealing with a large amount of data stored as XML. Instead, we can Transform the XML file into the desired XML using the XSL Transformation.

To write code in XSLT, add an XSLT File to your project. Remove the Template section  then format the template of the XML file that you want to get using XSLT tags, for the previous XML the following XSLT code will transform the XML hierarchical nodes into XML records as in the first example:

<xsl:template match="/">
    <xsl:for-each select="People">
      <xsl:element name="People">
        <xsl:for-each select ="Person">
          <xsl:element name ="Person">
          <xsl:attribute name="name">
            <xsl:value-of select ="name"/>
          </xsl:attribute>
          <xsl:attribute name ="age">
            <xsl:value-of select ="age"/>
          </xsl:attribute>
          </xsl:element>
        </xsl:for-each>
      </xsl:element>
    </xsl:for-each>
  </xsl:template>

Then as a final step when setting the XML file to the XmlDataSource, we have also to set the XSLT transformation file. Now we can bind our XML file to the GrideView having no problems.

Have you used XSLT to transform XML before?