System.Xml object of the Visual Basic can be used to easily import data into an application from an XML document. A container for the data is first created as a System.Xml.XmlDocument object and then the data is loaded into it using its Load() method to copy data from the XML document file.
A System.Xml.XmlNodeList can then create an Item() array of all the elements in the Xml document. Individual elements can be accessed by passing their name to the SelectSingleNode() method of the Item() array. The value contained within that element is retrieved by its innerText property.
Here is the xml file that we're going to use, books.xml:
<?xml version="1.0" encoding="ISO-8859-1" ?> <bookstore> <book category="cooking"> <title lang="en">Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2005</year> <price>30.00</price> </book> <book category="children"> <title lang="en">Harry Potter</title> <author>J K. Rowling</author> <year>2005</year> <price>29.99</price> </book> <book category="web"> <title lang="en">XQuery Kick Start</title> <author>James McGovern</author> <year>2003</year> <price>49.99</price> </book> <book category="web" cover="paperback"> <title lang="en">Learning XML</title> <author>Erik T. Ray</author> <year>2003</year> <price>39.95</price> </book> </bookstore>
Add a listBox and a Button to a new Form.
We need the following code for button event-handler to create an XmlDocument object from the XML file.
Here is the file: boox.xml
Run it:
Visual Basic provides components for data in table format. For instance, data contained in XML elements or database tables. The components are under Data of Toolbox.
To create a table in the system memory, the DataSet component can be added to an application. In general, it is convenient to display the table data in the interface using a DataGridView component. This allows the data stored in memory to be manipulated dynamically within the application and then written back to a file.
Add a DataGridView component and two Buttons (ReadButton and WriteButton) to a new Form.
If we double-click on the DataSet item in the Toolbox, the Add Dataset dialog will appear.
Choose the Untyped dataset and hit OK. Then, we'll see the DataSet icon appear on the component tray in the Form Designer.
Open code editor for the ReadButton and type into the following code into the ReadButton_Click event-handler to create a DataSet from the XML document of the previous example.
DataSet1.ReadXml(file)
Add the following code to load those elements nested under the <book> element from the DataSet into the DataGridView control.
DataGridView1.DataSource = DataSet1 DataGridView1.DataMember = "book"
This time, we want to work on WriteButton. Type the following code to the event-handler.
DataSet1.WriteXml(file)
Run it and click Read XML button to load the DataSet data into the DataGridView Control.
The DataGridView control shows the element name as the heading for each column and the element content on each row of that column. The first cell of the first row has focus by default, but we can click on any other cell to move the focus. When we double-click the cell, it changes into edit mode where we can update its contents.
Now, let's write something on the database. Add another row of data to the last row of the table then click the WriteButton control to save the modified data.
Restart it and read. We see it's been updated.
XML data can be imported from remote system into a Visual Basic application using a Really Simple Syndication (RSS) feed. It delivers the XML data as a stream that can be stored within a System.Xml.XmlDocument object.
Add a GroupBox Label from Containers, Button, and TextBox control to a new Form.
Type in "ZipCode" for the name of the TextBox and set its Text property to "94118" which is the Golden Gate Park Zip code.
We want to get RSS feed from Yahoo Weather. To create a request, we need to have a code for event-handler of the OK button:
Dim rssUrl = "http://xml.weather.yahoo.com/forecastrss?p=" _ + ZipCode.Text Dim rssRequest As System.Net.WebRequest = _ System.Net.WebRequest.Create(rssUrl)
We need to save the response data into a Stream object by adding the following lines:
Dim rssResponse As System.Net.WebResponse = _ rssRequest.GetResponse() Dim rssStream As System.IO.Stream = _ rssResponse.GetResponseStream()
To load the saved data stream into our XMLDocument object:
Dim rssDoc As New System.Xml.XmlDocument rssDoc.Load(rssStream)
Create an XmlNodeList under the <channel> element of the XmlDocument object by adding the following lines:
Dim nodes As System.Xml.XmlNodeList nodes = rssDoc.SelectNodes("/rss/channel")
To display the content contained in the <title> element of the XmlDocument object, we need:
GroupBox1.Text = _ nodes.Item(0).SelectSingleNode("title").InnerText
So, the whole code for the event-handler looks like this:
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim rssUrl = "http://xml.weather.yahoo.com/forecastrss?p=" _ + ZipCode.Text Dim rssRequest As System.Net.WebRequest = _ System.Net.WebRequest.Create(rssUrl) Dim rssResponse As System.Net.WebResponse = _ rssRequest.GetResponse() Dim rssStream As System.IO.Stream = _ rssResponse.GetResponseStream() Dim rssDoc As New System.Xml.XmlDocument rssDoc.Load(rssStream) Dim nodes As System.Xml.XmlNodeList nodes = rssDoc.SelectNodes("/rss/channel") GroupBox1.Text = _ nodes.Item(0).SelectSingleNode("title").InnerText End Sub End Class
Run it and type in 94118 (SF).
Click OK. After a short delay, we get the response and the text of the GroupBox has been changed to the title of the response document.
In the example of the previous section, we were able to retrieve the title from the XML response document. So, we can extract more information from the document about the current weather conditions.
Yahoo Weather sends us the XML response document in response to the RSS request. The document contains information about the weather conditions for the Zip code we specified.
The details are assigned to the attributes of XML elements that each have a yweather: which is namespace prefix. To access XML namespace elements in Visual Basic, it is necessary to first create an XmlNamespaceManager object. Then, we need to specify the namespace name and URL as parameters to its AddNamespace() method. Once an XmlNamespaceManager has been created, we simply add its name as a second parameter to each SelectSingleNode() call.
Let's add three TextBoxes and three Label controls to the Form we used in the previous section.
Name the TextBox controls Climate, Temperature, and Humidity. Then, set the Text property of each Label control accordingly.
Let's put more code into the event-handler for the OK button to create an XmlNamespaceManager.
Dim nsMngr = New _ System.Xml.XmlNamespaceManager(rssDoc.NameTable) nsMngr.AddNamespace("yweather", _ "http://xml.weather.yahoo.com/ns/rss/1.0")
To display the current weather condition:
Climate.Text = rssDoc.SelectSingleNode( _ "/rss/channel/item/yweather:condition/@text", nsMngr).InnerText
To display the current temperature:
Temperature.Text = rssDoc.SelectSingleNode( _ "/rss/channel/item/yweather:condition/@chill", nsMngr).InnerText + " F"
To display the current humidity:
Humidity.Text = rssDoc.SelectSingleNode( _ "/rss/channel/item/yweather:condition/@humidity", nsMngr).InnerText + " %"
Let's run it:
Here is the project file for the example. WindowRSS.zip.
The Form1.vb looks like this:
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Try ' Create a request to Yahoo Weather for the Zip code. Dim rssUrl = _ "http://xml.weather.yahoo.com/forecastrss?p=" _ + ZipCode.Text Dim rssRequest As System.Net.WebRequest = _ System.Net.WebRequest.Create(rssUrl) ' Save the response into a Stream object. Dim rssResponse As System.Net.WebResponse = rssRequest.GetResponse() Dim rssStream As System.IO.Stream = rssResponse.GetResponseStream() ' Load the Stream into an XMLDocument object. Dim rssDoc As New System.Xml.XmlDocument rssDoc.Load(rssStream) ' Create a nodes list under theelement. Dim nodes As System.Xml.XmlNodeList nodes = rssDoc.SelectNodes("/rss/channel") ' Display the content of the <title> element. GroupBox1.Text = nodes.Item(0).SelectSingleNode("title").InnerText ' Create a namespace manager to allow access to elements with a yweather: namespace prefix. Dim nsMngr = New _ System.Xml.XmlNamespaceManager(rssDoc.NameTable) nsMngr.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0") ' Now display the data. Climate.Text = _ rssDoc.SelectSingleNode( _ "/rss/channel/item/yweather:condition/@text", _ nsMngr).InnerText Temperature.Text = _ rssDoc.SelectSingleNode("/rss/channel/yweather:wind/@chill", nsMngr).InnerText + " F" Humidity.Text = _ rssDoc.SelectSingleNode("/rss/channel/yweather:atmosphere/@humidity", nsMngr).InnerText + " %" Catch ex As Exception MsgBox("Unable to retrieve RSS Feed") End Try End Sub End Class