Friday, January 8, 2010

XML Classes in .NET



[ Team LiB ]









XML Classes in .NET


Within the .NET architecture, XML is used to boost productivity, create compliance with open standards, and integrate with ADO.NET. To enable it to do so, namespaces and classes had to be created. Enumerating all the possible namespaces, classes, methods, properties, enumerations, interfaces, and delegates in a huge table here would be a waste of space and of time. However, in the following discussion we show how to use several classes within the .NET Framework to work programmatically with XML. You can then begin to create applications that effectively use XML in a manner emulating the reasons for its use by the .NET development team at Microsoft�and maybe have some fun along the way.


Throughout this section we present code samples to show you how to perform tasks related to application development with XML, XSL, XLST, and XPATH. (See the note regarding additional references for information about XML and the descriptions of these technologies earlier in the chapter.) Again, the main purpose of XML is to structure and describe data. The classes provided in the .NET Framework are there to help you do just that. The classes selected for discussion are from the System.xml namespace and are frequently used in work with XML data. These classes are equally important to your work in VB.NET. Any additional coding introduced is explained. Because of VB.NET's many new features, writing a program that doesn't take advantage of at least one of them is almost impossible.


Working with the Document Object Model


Introduction of the Document Object Model made programming dynamically generated sites much easier by allowing developers to add functionality to static elements from HTML/XML documents. Consider the simple JavaScript of document.location: This line navigates through the collection of elements associated with a Web page, starting at the top with the document object and finding its location property. In some sense this programmatic access to objects contained on a Web page was revolutionary. Then came XML with its strict rules and basically a dynamic object model based on what the author of the document had determined would be the root, or parent element.


We generated the file simple2.xml to provide an XML document for use in the rest of this chapter. We created it by using SQLXML, which we explain later in this chapter, and basically just saving the results with an .xml file extension. Typing line after line of HTML is no one's idea of fun, and we don't have to be concerned with formatting the data just yet. Moreover, we don't have to worry about any extraneous information being placed in the document, as can happen when we're using certain HTML editors and generators.


Listing 9.4 shows our simple2.xml file as generated. The location of the line breaks doesn't really matter because, like C++, C#, Java, and JavaScript, the lines of code are delimited. In those programming languages a semicolon (;) is used to end each line; in XML an end tag is used. Anything between the open tag (<) and the close tag (/>) is processed as one line, even if subelements fall between them.



Listing 9.4 simple2.xml


<?xml version="1.0" encoding="utf-8" ?>
<customer>
<tblCustomer ID="1" FirstName="Carole" LastName="Vermeren"
Address="6227 East Crossing Drive" City="Ocean Glen" State="NH"
PostalCode="98609" Phone="6034485994" />
<tblCustomer ID="2" FirstName="Cathy" LastName="Johnson"
Address="1629 West River Street" City="Big Center" State="NC"
PostalCode="18602" Phone="9193669205" />
<tblCustomer ID="3" FirstName="Eric" LastName="Haglund"
Address="9193 West Beach Street" City="Brown Heights" State="OK"
PostalCode="83481" Phone="4059310689" />
<tblCustomer ID="4" FirstName="Julie" LastName="Ryan"
Address="9161 Fort Beach Way" City="South Point" State="KY"
PostalCode="26973" Phone="5025245220" />
<tblCustomer ID="5" FirstName="Richard" LastName="Halpin"
Address="9790 Happy River Street" City="North Lake" State="MN"
PostalCode="62875" Phone="6124066311" />
<tblCustomer ID="6" FirstName="Kathleen" LastName="Johnson"
Address="9385 West Heights Street" City="Brown Towne" State="MI"
PostalCode="59609" Phone="3138032214" />
<tblCustomer ID="7" FirstName="Sorel" LastName="Polito"
Address="2104 Brown Brook Drive" City="Blue Valley" State="MT"
PostalCode="54401" Phone="4067260212" />
<tblCustomer ID="8" FirstName="Sorel" LastName="Terman"
Address="1920 West Point Street" City="Blue Bluffs" State="WI"
PostalCode="08965" Phone="6086246867" />
<tblCustomer ID="9" FirstName="Randy" LastName="Hobaica"
Address="4619 North Plains Drive" City="Brown Ridge" State="CT"
PostalCode="09793" Phone="2039421728" />
<tblCustomer ID="10" FirstName="Matthew" LastName="Haglund"
Address="8725 Sunset Crossing Avenue" City="New Brook"
State="AR" PostalCode="79013" Phone="5014589191" />
</customer>

The information in Listing 9.4 is from the Novelty database created earlier in Chapters 1�3. The query used to get this information is



SELECT TOP 10 * FROM tblCustomer FOR XML AUTO

We added the <customer> element manually here. Later, in the section on SQLXML, we show how to set the root element of an XML document automatically.


The first class related to the DOM that we consider is the XMLDocument. Without it, you won't get very far using XML data or documents. In its simplest case, XML data, either in a document or in an in-memory string, is loaded by calling the XMLDocument.Load() method.



Working with XPATH


Now that we have the document loaded, what do we do with it? Within the System.xml namespace are the xmlNode and xmlNodeList classes. Using these classes and a little XPATH is all we need to read through an XML document that we've loaded and fetch the data that we're interested in. Listing 9.5 shows a simple VB.NET application that simply loads our simple2.xml document and prints all the FirstName attributes to a textbox control.



Listing 9.5 XMLDocument and XMLNode sample


Imports System.Xml
Imports System.Xml.XPath
Imports System.IO
Public Class Form1
Inherits System.Windows.Forms.Form
. . . (Generated code removed from listing)
Private Sub Form1_Load (ByVal sender As System.Object,_
ByVal e As System.EventArgs) Handles MyBase.Load
Dim xDoc As New XmlDocument()
xDoc.Load("simple2.xml")
'Note the XPATH query syntax for getting to an attribute.
Dim xNodeList As XmlNodeList = _
xDoc.SelectNodes("descendant::tblCustomer/@FirstName")
Dim xNode As XmlNode
For Each xNode In xNodeList
lstResults.AppendText(vbCrLf & xNode.InnerText)
Next
End Sub
End Class

To execute this code, create a new VB.NET executable project and on the form create a listbox, lstResults. Place the code from Listing 9.5 in the form's Load event. When you execute the code, provided the simple2.xml file is in the same directory as your application, you should get results similar to those shown in Figure 9.2.


Figure 9.2. Results of Listing 9.5



As we've just demonstrated, loading the XML and navigating through it isn't a problem�it really is that easy. Next we ask, How do we change the data that's in the document? The answer comes from the same combination of classes we used earlier.


Note



To keep things clean and bring us a little closer to the real world, in the VB.NET project created for Listing 9.5, we move the code inside the Form_Load routine to a private subelement, ShowTop10. We show it in Listing 9.6 shortly.




Listing 9.6 shows the modified Visual Basic application, reflecting changing the node's value and saving it to the XML file. This example is fairly simple, but the techniques used are extremely efficient and reliable when it comes to modifying an XML document. The modifications from the original code also include the addition of two command buttons, btnShowTop10 and btnChangeAndSave. We added these buttons as a simple way to control which routine gets executed. After adding this code to your Visual Basic executable project and being sure that you have the simple2.xml file in the application's bin directory, start the application and click on the ShowTop10 button. The results should be similar to those shown in Figure 9.2. To change one of the values, double-click on the item in the listbox that you want to change. An input box will prompt you to enter a new value for the item you selected. Clicking on OK in the input box changes the XML document and reloads the values are in the listbox to show the changes you made.



Listing 9.6 Completed XMLDomSample application code


Imports System.Xml
Imports System.Xml.XPath
Imports System.IO
Public Class Form1
Inherits System.Windows.Forms.Form
. . . (Generated code removed from listing)
Private Sub Form1_Load(ByVal sender As System.Object
ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub ShowTop10()
'This is the code used in Listing 9.5.
Dim xDoc As New XmlDocument()
xDoc.Load("simple2.xml")
'Note the XPATH syntax used to get the attibute of an element.
Dim xNodeList As XmlNodeList = xDoc.SelectNodes
("descendant::tblCustomer/@FirstName")
Dim xNode As XmlNode
Dim i As Integer = 0
For Each xNode In xNodeList
lstResults.Items.Insert(i, xNode.InnerText)
i = i + 1
Next
End Sub
Public Sub ChangeNameandSave(ByVal NameToChange As String,
ByVal ChangeTo As String)
Dim xDoc As New XmlDocument()
xDoc.Load("simple2.xml")
Dim xNodeList As XmlNodeList = xDoc.SelectNodes
("descendant::tblCustomer/@FirstName")
Dim xNode As XmlNode
For Each xNode In xNodeList
If xNode.InnerText = NameToChange Then
xNode.Value = ChangeTo
End If
Next
xDoc.Save("simple2.xml")
MsgBox("Name change saved !", 0)
lstResults.Items.Clear()
ShowTop10()
End Sub
Private Sub btnShowTop10_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles btnShowTop10.Click
ShowTop10()
End Sub
Private Sub lstResults_DoubleClick(ByVal sender As Object,
ByVal e As System.EventArgs) Handles lstResults.DoubleClick
Dim oldName As String = lstResults.GetItemText
(lstResults.Items.Item(lstResults.SelectedIndex))
Dim newName As String = InputBox_
("Please enter a new name", "ChangeAndSave")
ChangeNameandSave(oldName, newName)
End Sub
End Class

Note



The complete code listings for this chapter are available from the publisher's Web site�http://www.awprofessional.com.










    [ Team LiB ]



    No comments: