Using the ASP.NET XML Control for displaying XML File Contents in a Web Page
By Vishal Khanna
Say you have an XML file, and you quickly need to display it in your webpage. Whats the best way to implement this requirement? There might be numerous approaches to incorporate this, but using an XML Control provided in ASP.NET 2 (and above) shall help you quickly. With the power of the asp:XML control, the XML data may be presented in the way you like. The DocumentSource property may be set to the relative path of the source XML file. The TransformSource property may be used to specify the path of the XSL file, that may be styled in such a way so as to achieve the presentation in the page.
Say you have an XML file named books.xml like the one below:
<?xml version='1.0'?>
<Books>
<BookDetails>
<name>The Criminal Court of USA</name>
<price>$800</price>
</BookDetails>
<BookDetails>
<name>Best Criminal Lawyers</name>
<price>$2500</price>
</BookDetails>
</Books>
You may use the following books.xsl file to display the book contents:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<HTML>
<BODY>
<xsl:for-each select="Books/BookDetails">
<DIV STYLE="background-color:yellow; color:black;">
<SPAN><xsl:value-of select="name"/></SPAN> - <xsl:value-of select="price"/>
</DIV>
</xsl:for-each>
</BODY>
</HTML>
</xsl:template>
</xsl:stylesheet>
Wow. Isn't that too simple. Ofcourse, it may get more and more complex as your design requirements increase.
This is what you need to put in your ASP.NET page code:
<asp:Xml id="Xml1" runat="server" DocumentSource="books.xml" TransformSource="books.xsl"></asp:Xml>
Thats it! Your XML is ready for your web page.
Happy Programming.
Cheers!