Home
    Shop
    Advertise
    Write For Us
    Affiliate
    Newsletter
    Contact

XML Programming with VB.NET

Extensible Markup Language (XML) is a meta-markup language that provides a format for describing structured data. XML is the universal language for data exchange on the Web. XML gives developers the power to deliver structured data from a wide variety of applications to the desktop for local computation and presentation.

 

Microsoft .Net framework provides integrated support for XML programming through core XML classes.


Features of core XML classes in .NET Framework

  • Extensible

  • Pluggable Architecture

  • Integration with ADO.NET

  • Compliance with Industry Standards like DOM, XPath, XSD and XSLT

  • Scalable and performance oriented

In the .Net Framework 1.1, the XmlDocument was one of the most common ways to manipulate XML. It is similar to using a static ADO recordset because it parses and loads the entire XmlDocument into memory. But there are number of problems with XmlDocument. It consumes lot of memory. The data model of XmlDocument is very different from other XML query languages like XSLT and XPath. In 2.0 Framework, XPathDocument is answer to above problems. The XPathDocument is read-only and optimized for XPath queries. It is much faster than XmlDocument for loading and querying XML. It is preferred class to use for XSLT transformations.

It is maintained that you should use the XPathDocument instead of XmlDocument except in situations where you must maintain compatibility with previous .NET framework versions.

System.Xml Namespace

The XML classes in the System.Xml namespace provide a comprehensive and integrated set of classes, allowing you to work with XML documents and data. The XML classes support parsing and writing XML, editing XML data in memory, data validation, and XSLT transformation.

There are different classes available to read and write XML document in .Net Framework. They are:

  • XmlReader

  • XmlTextReader

  • XmlValidatingReader

  • XmlNodeReader

  • XmlWriter

  • XmlTextWriter

XmlReader Class

XmlReader class offers a pull-style API over an XML document that is unique to the .NET framework. Pull style means you can skip unwanted nodes while reading. It provides fast, forward-only, read-only access to XML document.

The XmlReader class supports reading XML data from a stream or file. It defines methods and properties that allow you to move through the data and read the contents of a node.

XmlReader is an actually an abstract class that other classes derive from to provide specific concrete instances like XmlTextReader and XmlNodeReader.

XmlTextReader Class

XmlTextReader class is a forward only and read only access to stream of XML data. But XmlTextReader cannot check for validity of XML document against a DTD.

XmlNodeReader Class

XmlNodeReader class represents reader that provides fast access to XML data in a XML node.

XmlReader improvements in .NET 2.0

New changes have been added to XmlReader in .Net framework 2.0. Now you don't need to create concrete implementations of XmlReader class, you can create an instance of XmlReaderSettings class and pass it to the create method. You specify the features you want for your XmlReader object with the XmlReaderSettings class.

Below listing creates an instance of XmlReader class and iterates forward through it, counting the number of countries in the countries.xml document. The countries.xml is enclosed with attached project. The XmlReaderSettings object specifies the features that are required, rather than the actual kind of XmlReader to create. In this example, IgnoreComments are set to true. The XmlReaderSettings object is created with these property settings and then passed to create method of XmlReader. You can download sample Visual Basic .NET project, used in this tutorial.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim countrycount As Integer = 0
        Dim settings As New XmlReaderSettings()
        settings.IgnoreComments = True
        Dim Countryfile As String = Path.Combine(Request.PhysicalApplicationPath, "Countries.xml")
        Using reader As XmlReader = XmlReader.Create(Countryfile, settings)
            While (reader.Read())
                If (reader.NodeType = XmlNodeType.Element And "country" = reader.LocalName) Then
                    countrycount += 1
                End If
            End While
        End Using
        Response.Write(String.Format("Found {0} Countries!", countrycount))
    End Sub


Counting the nodes using XmlReader

Notice the use of the XmlReader.Create method in above listing. You may be used to creating concrete implementations of an XmlReader, but if you try this technique, you should find it much more flexible because you can reuse the XmlReaderSettings objects in the creation of other instances of XmlReader.

The countries.xml is in the same directory as this ASPX page, so a call to Path.combine gets the complete path to the XML file. The file name with full path is then passed into XmlReader.Create, along with the XmlReaderSettings instance.

The read method continues to return true if the node was read successfully. It will return false when no more nodes are left to read. XmlReader treats everything as a node including comments, attributes, elements and end elements. That's where we are checking node type to be element. If not, XmlReader will return number of countries to be 12 including end elements because end element's local name is also Country.

The reader.LocalName property returns non-namespace qualified name of that node.

XmlWriter Class

XmlWriter works exactly like XmlReader except in reverse. XmlWriter is a abstract class that helps generate XML streams or files. Though, .Net Framework includes XmlTextWriter class which is an implementation of XmlWriter abstract class. It is recommended in ASP.NET 2.0 that you use create method to create new XmlWriter objects. The create method allows you to specify the features to support on the created XmlWriter using XmlWriterSettings. This settings class has options for indentation, new lines, encoding and XML conformance level.

Below given listing uses XmlWriter to create a Countries XML document in an XML file created on hard disk as shown below.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim Capital As String = "Washington"
        Dim Cities As String = "NewYork"
        Dim rank As Integer = 1
        Dim settings As New XmlWriterSettings()
        settings.Indent = True
        settings.NewLineOnAttributes = True
        Using writer As XmlWriter = XmlWriter.Create("C:\xmlfile.xml", settings)
            writer.WriteStartDocument()
            writer.WriteStartElement("countries")
            writer.WriteStartElement("UnitedStates")
            writer.WriteStartAttribute("capital")
            writer.WriteValue(Capital)
            writer.WriteEndAttribute()
            writer.WriteStartAttribute("Cities")
            writer.WriteValue(Cities)
            writer.WriteEndAttribute()
            writer.WriteStartAttribute("rank")
            writer.WriteValue(rank)
            writer.WriteEndAttribute()
            writer.WriteEndElement()
            writer.WriteEndDocument()
            writer.Flush()
        End Using
    End Sub


Xml file using XmlWriter

Above output listing shows newly created XML file at C:\xmlfile. The XmlwriterSettings.Indent property includes indentation that makes the resulting XML document more readable.

New methods for XmlReader and XmlWriter in 2.0

ReadSubTree: This method reads the current node of an XmlReader and returns a new XmlReader that traverses the current node and all of its descendants.

ReadToDescendant /ReadToNextSibling: These two methods provide convenient ways to advance the XmlReader to specific elements that appear later in the document.

XPathDocument Class

XPathDocument is most efficient way to use XPath expressions over an in-memory data structure. The XPathDocument implements the IXPathNavigable interface, allowing you to iterate over the underlying XML by providing an XPathNavigator.

The XPathNavigator class differs from the XmlReader in that it provides random access over your XML rather than forward-only with XmlReader. XPathDocument allows you to move freely, forward and backward within the document.

DataSets

Datasets are best example to show that core XML classes in .Net Framework are tightly integrated with ADO.NET. Classes within System.Data use XmlWriter and XmlReader in a number of places. Most of the methods with System.Data are pluggable with the classes from System.Xml. Below listing shows how to retrieve the XML from relational data by loading a Dataset from SQL command and writing it directly to browser with response object's TextWriter property using Dataset.Writexml method.

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim ds As New dataset
        Dim connStr As String = "database=NorthWind;Data Source=localhost;User id=sa;password=sa"
        Using conn As New SqlConnection(connStr)
            Dim command As New SqlCommand("select * from customers", conn)
            conn.Open()
            ds.DataSetName = "Customers"
            ds.Load(command.ExecuteReader(), LoadOption.OverwriteChanges, "customers")
            Response.ContentType = "text/xml"
            ds.WriteXml(Response.OutputStream)
        End Using
    End Sub


Dataset written as xml

Hence, this article gives an idea of improvements and changes to XML classes in .NET Framework 2.0.


Tutorial toolbar:  Tell A Friend  |  Add to favorites  |  Feedback  |   


comments powered by Disqus