Using Returned XML with C#

Original Post: https://developer.yahoo.com/dotnet/howto-xml_cs.html

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 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.

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

  1. public class StringGet
  2. {
  3.     public static string GetPageAsString(Uri address)
  4.     {
  5.         string result = “”;
  6.         // Create the web request
  7.         HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
  8.         // Get response
  9.         using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
  10.         {
  11.             // Get the response stream
  12.             StreamReader reader = new StreamReader(response.GetResponseStream());
  13.             // Read the whole contents and return as a string
  14.             result = reader.ReadToEnd();
  15.         }
  16.         return result;
  17.     }
  18. }

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 by XmlTextWriter.

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

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

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

  1. // Create a new XmlDocument
  2. XmlDocument doc = new XmlDocument();
  3. // Load data
  4. doc.Load(http://xml.weather.yahoo.com/forecastrss?p=94704”);
  5. // Set up namespace manager for XPath
  6. XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable);
  7. ns.AddNamespace(“yweather”http://xml.weather.yahoo.com/ns/rss/1.0”);
  8. // Get forecast with XPath
  9. XmlNodeList nodes = doc.SelectNodes(“/rss/channel/item/yweather:forecast”, ns);
  10. // You can also get elements based on their tag name and namespace,
  11. // though this isn’t recommended
  12. //XmlNodeList nodes = doc.GetElementsByTagName(“forecast”, 
  13. //                          “http://xml.weather.yahoo.com/ns/rss/1.0”);
  14. foreach(XmlNode node in nodes)
  15. {
  16.     Console.WriteLine(“{0}: {1}, {2}F – {3}F”,
  17.                         node.Attributes[“day”].InnerText,
  18.                         node.Attributes[“text”].InnerText,
  19.                         node.Attributes[“low”].InnerText,
  20.                         node.Attributes[“high”].InnerText);
  21. }

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

  1. using System.Xml.XPath;
  2. // Create a new XmlDocument
  3. XPathDocument doc = new XPathDocument(http://xml.weather.yahoo.com/forecastrss?p=94704”);
  4. // Create navigator
  5. XPathNavigator navigator = doc.CreateNavigator();
  6. // Set up namespace manager for XPath
  7. XmlNamespaceManager ns = new XmlNamespaceManager(navigator.NameTable);
  8. ns.AddNamespace(“yweather”http://xml.weather.yahoo.com/ns/rss/1.0”);
  9. // Get forecast with XPath
  10. XPathNodeIterator nodes = navigator.Select(“/rss/channel/item/yweather:forecast”, ns);
  11. while(nodes.MoveNext())
  12. {
  13.     XPathNavigator node = nodes.Current;
  14.     Console.WriteLine(“{0}: {1}, {2}F – {3}F”,
  15.                         node.GetAttribute(“day”, ns.DefaultNamespace),
  16.                         node.GetAttribute(“text”, ns.DefaultNamespace),
  17.                         node.GetAttribute(“low”, ns.DefaultNamespace),
  18.                         node.GetAttribute(“high”, ns.DefaultNamespace));
  19. }

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

  1. using System.Data;
  2. public void RunSample()
  3. {
  4.     // Create the web request
  5.     HttpWebRequest request
  6.         = WebRequest.Create(http://xml.weather.yahoo.com/forecastrss?p=94704”as HttpWebRequest;
  7.     // Get response
  8.     using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
  9.     {
  10.         // Load data into a dataset
  11.         DataSet dsWeather = new DataSet();
  12.         dsWeather.ReadXml(response.GetResponseStream());
  13.         // Print dataset information
  14.         PrintDataSet(dsWeather);
  15.     }
  16. }
  17. public static void PrintDataSet(DataSet ds)
  18. {
  19.     // Print out all tables and their columns
  20.     foreach (DataTable table in ds.Tables)
  21.     {
  22.         Console.WriteLine(“TABLE ‘{0}'”, table.TableName);
  23.         Console.WriteLine(“Total # of rows: {0}”, table.Rows.Count);
  24.         Console.WriteLine(“—————————————————————“);
  25.         foreach (DataColumn column in table.Columns)
  26.         {
  27.             Console.WriteLine(“- {0} ({1})”, column.ColumnName, column.DataType.ToString());
  28.         }  // foreach column
  29.         Console.WriteLine(System.Environment.NewLine);
  30.     }  // foreach table
  31.     // Print out table relations
  32.     foreach (DataRelation relation in ds.Relations)
  33.     {
  34.         Console.WriteLine(“RELATION: {0}”, relation.RelationName);
  35.         Console.WriteLine(“—————————————————————“);
  36.         Console.WriteLine(“Parent: {0}”, relation.ParentTable.TableName);
  37.         Console.WriteLine(“Child: {0}”, relation.ChildTable.TableName);
  38.         Console.WriteLine(System.Environment.NewLine);
  39.     }  // foreach relation
  40. }

Further reading

Related information on the web is listed below.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s