- Extensible
- Pluggable Architecture
- Integration with ADO.NET
- Compliance with Industry Standards like DOM, XPath, XSD and XSLT
- Scalable and performance oriented
- XmlReader
- XmlTextReader
- XmlValidatingReader
- XmlNodeReader
- XmlWriter
- XmlTextWriter
XmlReader 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.
XmlTextReader 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:
XmlNodeReader represents reader that provides fast access to XML data in a XML node.
XmlReader improvements in .NET 2.0/3.5:
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.
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:
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.
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.
Happy learning!!!