XML with C#

The .NET Framework provides excellent support for XML. Combined with the databinding support of WinForms and ASP.NET applications you have an easy and powerful set of tools. ASP.NET 2.0 takes databinding another step further by providing the DataSource control which lets you declaratively provide data access to data-bound UI controls.

There is excellent support for XML in Microsoft .Net framework, and there is a very good and easy article on it at Yahoo Developer Network.

I am pasting its content here for convenience. Enjoy 🙂

Using Returned XML with C#

Once you have retrieved data from a web service you will need to do something with it. This HOWTO describes the various built-in methods .NET provides to use XML returned by a web service.

Overview

The .NET Framework provides excellent support for XML. Combined with the data binding support of WinForms and ASP.NET applications you have an easy and powerful set of tools. ASP.NET 2.0 takes data binding another step further by providing the DataSource control which lets you declaratively provide data access to data-bound UI controls.

Returned Data to a String

The simplest way to view the returned data is to get the response stream and put it into a string. This is especially handy for debugging. The following code gets a web page and returns the contents as a string.

C# STRING SAMPLE

public class StringGet { public static string GetPageAsString(Uri address) { string result = “”; // Create the web request HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest; // Get response using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { // Get the response stream StreamReader reader = new StreamReader(response.GetResponseStream()); // Read the whole contents and return as a string result = reader.ReadToEnd(); } return result; } }

USING XMLREADER

XmlReader provides fast forward-only access to XML data. It also allows you to read data as simple-typed values rather than strings. XmlReader can load an XML document without having to use HttpRequest, though you won’t have the same amount of control over the request. If you use HttpRequest, you can just pass the stream returned by the GetResponseStream() method to XmlReader. Fast write-only functions are provided byXmlTextWriter.

With .NET 2.0 you should create XmlReader instances using the System.Xml.XmlReader.Create method. For the sake of compatibility and clarity the next sample uses the .NET 1.1 creation method.

C# XMLREADER SAMPLE

using System.Xml;
// Retrieve XML document
XmlTextReader reader = new XmlTextReader("http://xml.weather.yahoo.com/forecastrss?p=94704");
// Skip non-significant whitespace
reader.WhitespaceHandling = WhitespaceHandling.Significant;
// Read nodes one at a time
while (reader.Read())
{
	// Print out info on node
	Console.WriteLine("{0}: {1}", reader.NodeType.ToString(), reader.Name);
}

USING XMLDOCUMENT

XmlDocument gives more flexibility and is a good choice if you need to navigate or modify the data via the DOM. It also works as a source for the XslTransform class allowing you to perform XSL transformations.

C# XMLDOCUMENT SAMPLE

// Create a new XmlDocument
XmlDocument doc = new XmlDocument();
// Load data
doc.Load("http://xml.weather.yahoo.com/forecastrss?p=94704");
// Set up namespace manager for XPath
XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable);
ns.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0");
// Get forecast with XPath
XmlNodeList nodes = doc.SelectNodes("/rss/channel/item/yweather:forecast", ns);
// You can also get elements based on their tag name and namespace,
// though this isn't recommended
//XmlNodeList nodes = doc.GetElementsByTagName("forecast",
//                          "http://xml.weather.yahoo.com/ns/rss/1.0");
foreach(XmlNode node in nodes)
{
	Console.WriteLine("{0}: {1}, {2}F - {3}F",
	node.Attributes["day"].InnerText,
	node.Attributes["text"].InnerText,
	node.Attributes["low"].InnerText,
	node.Attributes["high"].InnerText);
}

Using XPathNavigator/XPathDocument

XPathDocument provides fast, read-only access to the contents of an XML document using XPath. Its usage is similar to using XPath with XmlDocument.

C# XPATHDOCUMENT SAMPLE

using System.Xml.XPath;
// Create a new XmlDocument
XPathDocument doc = new XPathDocument("http://xml.weather.yahoo.com/forecastrss?p=94704");
// Create navigator
XPathNavigator navigator = doc.CreateNavigator();
// Set up namespace manager for XPath
XmlNamespaceManager ns = new XmlNamespaceManager(navigator.NameTable);
ns.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0");
// Get forecast with XPath
XPathNodeIterator nodes = navigator.Select("/rss/channel/item/yweather:forecast", ns);
while(nodes.MoveNext())
{
	XPathNavigator node = nodes.Current;
	Console.WriteLine("{0}: {1}, {2}F - {3}F",
	node.GetAttribute("day", ns.DefaultNamespace),
	node.GetAttribute("text", ns.DefaultNamespace),
	node.GetAttribute("low", ns.DefaultNamespace),
	node.GetAttribute("high", ns.DefaultNamespace));
}

Using a DataSet

Using a DataSet from the System.Data namespace lets you bind the returned data to controls and also access hierarchical data easily. A dataset can infer the structure automatically from XML, create corresponding tables and relationships between them and populate the tables just by calling ReadXml().

C# DATASET SAMPLE

using System.Data;
public void RunSample()
{
	// Create the web request
	HttpWebRequest request
	= WebRequest.Create("http://xml.weather.yahoo.com/forecastrss?p=94704") as HttpWebRequest;
	// Get response
	using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
	{
		// Load data into a dataset
		DataSet dsWeather = new DataSet();
		dsWeather.ReadXml(response.GetResponseStream());
		// Print dataset information
		PrintDataSet(dsWeather);
	}
}
public static void PrintDataSet(DataSet ds)
{
	// Print out all tables and their columns
	foreach (DataTable table in ds.Tables)
	{
		Console.WriteLine("TABLE '{0}'", table.TableName);
		Console.WriteLine("Total # of rows: {0}", table.Rows.Count);
		Console.WriteLine("---------------------------------------------------------------");
		foreach (DataColumn column in table.Columns)
		{
			Console.WriteLine("- {0} ({1})", column.ColumnName, column.DataType.ToString());
		}  // foreach column
		Console.WriteLine(System.Environment.NewLine);
	}  // foreach table
	// Print out table relations
	foreach (DataRelation relation in ds.Relations)
	{
		Console.WriteLine("RELATION: {0}", relation.RelationName);
		Console.WriteLine("---------------------------------------------------------------");
		Console.WriteLine("Parent: {0}", relation.ParentTable.TableName);
		Console.WriteLine("Child: {0}", relation.ChildTable.TableName);
		Console.WriteLine(System.Environment.NewLine);
	}  // foreach relation
}

Further reading

Related information on the web is listed below.

Share your love
Muhammad Jawaid Shamshad
Muhammad Jawaid Shamshad
Articles: 128

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.