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
Returned Data to a String
Using XmlReader
Using XmlDocument
Using XPathNavigator/XPathDocument
Using a DataSet
Further Reading
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.
VB.NET STRING SAMPLE
Public Shared Function GetPageAsString(ByVal address As Uri) As String
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader
Dim result As String
Try
' Create the web request
request = DirectCast(WebRequest.Create(address), HttpWebRequest)
' Get response
response = DirectCast(request.GetResponse(), HttpWebResponse)
' Get the response stream into a reader
reader = New StreamReader(response.GetResponseStream())
' Read the whole contents and return as a string
result = reader.ReadToEnd()
Finally
If Not response Is Nothing Then response.Close()
End Try
Return result
End Function
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.
VB.NET XMLREADER SAMPLE
Imports System.Xml
' Retrieve XML document
Dim reader As XmlTextReader = 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)
End While
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.
VB.NET XMLDOCUMENT SAMPLE
Dim doc As XmlDocument
Dim ns As XmlNamespaceManager
Dim nodes As XmlNodeList
' Create a new XmlDocument
doc = New XmlDocument()
' Load data
doc.Load("http://xml.weather.yahoo.com/forecastrss?p=94704")
' Set up namespace manager for XPath
ns = New XmlNamespaceManager(doc.NameTable)
ns.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0")
' Get forecast with XPath
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
'nodes = doc.GetElementsByTagName("forecast", _
' "http://xml.weather.yahoo.com/ns/rss/1.0")
For Each node As XmlNode 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)
Next
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.
VB.NET XPATHDOCUMENT SAMPLE
Imports System.Xml.XPath
Dim doc As XPathDocument
Dim ns As XmlNamespaceManager
Dim navigator As XPathNavigator
Dim nodes As XPathNodeIterator
Dim node As XPathNavigator
' Create a new XmlDocument
doc = New XPathDocument("http://xml.weather.yahoo.com/forecastrss?p=94704")
' Create navigator
navigator = doc.CreateNavigator()
' Set up namespace manager for XPath
ns = New XmlNamespaceManager(navigator.NameTable)
ns.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0")
' Get forecast with XPath
nodes = navigator.Select("/rss/channel/item/yweather:forecast", ns)
While nodes.MoveNext()
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))
End While
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().
VB.NET DATASET SAMPLE
Imports System.Data
Public Shared Sub DataSetSample1()
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim dsWeather As DataSet
Try
' Create the web request
request = DirectCast(WebRequest.Create( _
"http://xml.weather.yahoo.com/forecastrss?p=94704"), HttpWebRequest)
' Get response
response = DirectCast(request.GetResponse(), HttpWebResponse)
' Load data into a dataset
dsWeather = New DataSet()
dsWeather.ReadXml(response.GetResponseStream())
' Print dataset information
PrintDataSet(dsWeather)
Finally
If Not response Is Nothing Then response.Close()
End Try
End Sub
Public Shared Sub PrintDataSet(ByVal ds As DataSet)
' Print out all tables and their columns
For Each table As DataTable In ds.Tables
Console.WriteLine("TABLE '{0}'", table.TableName)
Console.WriteLine("Total # of rows: {0}", table.Rows.Count)
Console.WriteLine("---------------------------------------------------------------")
For Each column As DataColumn In table.Columns
Console.WriteLine("- {0} ({1})", column.ColumnName, column.DataType.ToString())
Next ' For Each column
Console.WriteLine(System.Environment.NewLine)
Next ' For Each table
' Print out table relations
For Each relation As DataRelation 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)
Next ' For Each relation
End Sub
No comments:
Post a Comment