ASP.Net XmlDocuemnt class provides the methods to select nodes or a single node by passing XPath expression. Here we will learn the C# code for applying XmlDocument class functions, methods or properties to read the Value from XML file through XmlDataSource. ASP.Net XmlDataSource control reads the xml file and returns the XMLDocument through GetXmlDocument function. Further you can use SelectSingleNode and SelectNodes functions to select the child nodes or their attributes. Now we will use the XPath syntax that we discussed in the previous tutorial about ASP.Net Xml DataSource XPath.
Consider the same XML here:
<?xml version="1.0" encoding="utf-8" ?>
<movieList>
<title>Bad Boys</title>
<movie id="2">
</movie>
<title>The Love Guru</title>
</movieList>
You can drag and drop the ASP.Net XmlDataSource control on the web page and set its DataFile property as following:
<asp:XmlDataSource
ID="XmlDataSource1"
runat="server"
</asp:XmlDataSource>
First of all create an XMLDocument class object and assign its reference from the XmlDataSource1 GetXmlDocument function:
XmlDocument xmlDoc = XmlDataSource1.GetXmlDocument();
Use the following C# code to read the XML nodes using different types of XPath expressions:
// Select all child nodes of root node of XML document
// using single "/" expression
// Select child nodes of movie node under root node movieList
// Select node value of title node under movie
// Select title child node where ever it exits under movieList root node
// Select title child node where ever it exits in the XML document
// Select id attribute where ever it exits under movieList root node
// Select root node of XML Document
// Select the parent node of title child node [movie]
// Here it returns the count for title child nodes under movie node
// Returns the Count for title child nodes in the XML Document
Response.Write(xmlDoc.SelectNodes("//title").Count + "<br />");
Output for above C# code examples for XPath expressions passed to the SelectSingleNode and SelectNodes function of XmlDocument class.
Bad BoysChronicles of NarniaThe Love Guru Bad BoysChronicles of NarniaThe Love Guru Bad Boys Bad Boys Bad Boys Bad Boys 1 Bad BoysChronicles of NarniaThe Love Guru 3 3
Be the first to rate this post
Tags: asp.net, xml, c#, asp.net xmldocument, asp.net xml xpath, asp.net examples, c# code, asp.net xmldatasource control, asp.net xml namespace, asp.net xmldocument selectnodes, asp.net xmldocument selectsinglenode, asp.net xpath expressions, asp.net xpath syntax, asp.net xml elements, asp.net xml attributes, asp.net xml nodes, asp.net xmldatasource datafile, asp.net xmldatasource xpath, c# tutorials
10/11/2008 3:39:41 AM