AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=293&pId=-1
XMLTextWriter & XMLTextReader
page
by Pani Baruri & Abhijit Mandrekar
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 28585/ 57

XML TextWriter

While developing ASP applications the developers used XML tag to reference XML files on the server or to refer to XML data islands within HTML file or they developed a complex code to concatenate xml data with xml tags. The inconvenience of having ASP code to generate xml output was cumbersome to maintain. Also the code was parsing for unacceptable xml characters such as “,”, “;”, “&”, “<”, “>” and converting them to &amp, &lt,, &gt characters respectively.

 

 

The .net platform has overcome the above mentioned problems by defining a class for writing xml output to a file using abstract classes XMLTextReader and XMLTextWriter. The XMLTextWriter is a sequential text file writer and its counterpart is XMLTextReader class which is sequential text file reader. The order of reading has to be essentially same as order of writing. XmlReader provides a fast, forward-only, read-only cursor for processing an XML document stream. XmlWriter provides an interface for producing XML document streams that conform to the W3C's XML 1.0 + Namespaces Recommendations. Both classes imply a streaming model that doesn't require an expensive in-memory cache. The methods of the class should be used in a specific order so that it generates a well formed and valid xml file.

 

The XmlTextWriter has different constructors to specify the location to write the XML data to. To instantiate an object of class XMLTextWriter, xml file name and encoding type parameters are passed. If encoding parameter is set to Nothing then default encoding will be <A href=’ http://www.faqs.org/rfcs/rfc2044.html”>UTF-8</A>. The other encodings supported by this class is ASCII and Unicode. The encoding values can be obtained from System.Text.Encoding class.

 

The XMLTextWriter has following essential methods.

 

WriteStartDocument:- The very first method after an instantiation of XMLTextWriter object to open new xml document with xml declaration with version 1.0.

 

WriteEndDocument:- The very last method after writing xml output to the file to close xml document.

 

WriteStartElement:- This method adds an xml tag to the contents. These tags generally denote themselves as parent tags. It accepts tag name as an input.

 

WriteEndElement:- This method closes the recently opened xml tag. If xml tags are nested then it closes the innermost tag first.

 

WriteElementString:- This method adds sibling tags as name and value pairs.

 

WriteStartAttribute:- This method appends attributes to the recently added xml tag. It accepts attribute name, xml namespace and prefix string to be used before each xml tag as an input to the method. The xml name space and prefix string can be blank strings.

 

WriteString:- This method must follow WriteStartAttribute method to associate value of an attribute with xml tag.

 

WriteEndAttribute:- This method closes the recently added attribute.

 

Flush:- This method actually writes buffered xml output obtained from methods described above to the physical file.

 

WriteComments:- Use this method to write meaningful comment any time during xml output generation. It accepts comment string as an input.

 

Formatting:- This is a property by which the xml output is automatically indented as you write xml tags and its contents. This way if the file is opened in any text reader it will not look like a long string.

 

Code

Let’s take a look at an example to create xml file with one level of nesting. The file stores contact information for personal and business purposes. The structure of the xml file expected is as below.

 

<?xml version="1.0" encoding="utf-8" ?>

<contacts>

<contact type="Personal">

                <name></name>

                <email>

                                <primary></primary>

                                <secondary></pecondary>

                </email>

                <telephone>

                                <home></home>

                                <work></work>

                                <mobile></mobile>

                </telephone>

</contact>

<contact type="Business">

                <name>PANAM</name>

                <email>

                                <primary>PANAM@ASPALLIANCE.COM</primary>

                                <secondary></secondary>

                </email>

                <telephone>

                               <home>(732)635-0507</home>

                                <work>(732)801-8075/work>

                                <mobile>(732)865-1920</mobile>

                </telephone>

</contact>

</contacts>

 

The following is a code to generate the file in above mentioned format.

 

Note:

Set TextMode Property of TextBox1 and TextBox2 to “MultiLine”

Set Caption Property of Button1 to “Save XML”

Set Caption Property of Button2 to “Show XML”

 

Code:

 

Imports System.Xml

 

Public Class xmlexample

    Inherits System.Web.UI.Page

    Protected WithEvents TextBox1 As System.Web.UI.WebControls.TextBox

    Protected WithEvents Button1 As System.Web.UI.WebControls.Button

    Protected WithEvents TextBox2 As System.Web.UI.WebControls.TextBox

    Protected WithEvents Button2 As System.Web.UI.WebControls.Button

 

    Dim filename As String = "xmlnotes.xml"

 

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        SaveXML()

    End Sub

 

    Private Sub SaveXML()

        Dim xmlwriter As XmlTextWriter

 

        Try

            xmlwriter = New XmlTextWriter(Server.MapPath(filename), Nothing)    'default encoding - UTF-8

 

            'indent xml document

            xmlwriter.Formatting = Formatting.Indented

 

            'writes the xml declaration with version 1.0

            xmlwriter.WriteStartDocument()

 

            'add coment

            xmlwriter.WriteComment("This is an xml file generated using XMLTextWriter class")

 

            'write the root node

            xmlwriter.WriteStartElement("contacts")

 

            'write parent node

            xmlwriter.WriteStartElement("contact")

 

            'define attribute type of contact

            xmlwriter.WriteStartAttribute("", "type", "")

            'define value for attribute

            xmlwriter.WriteString("business")

            'close attribute

            xmlwriter.WriteEndAttribute()

 

            'write information about children or siblings

            xmlwriter.WriteElementString("name", "PANAM")

 

            'add parent node e-mail and detailed information

            xmlwriter.WriteStartElement("email")

            xmlwriter.WriteElementString("primary", "PANAM@ASPALLIANCE.COM")

            xmlwriter.WriteElementString("secondary", "")

            xmlwriter.WriteEndElement()

 

            'add parent node telephone and detailed information

            xmlwriter.WriteStartElement("telephone")

            xmlwriter.WriteElementString("home", "(732)635-0507")

            xmlwriter.WriteElementString("work", "(732)801-8075")

            xmlwriter.WriteElementString("mobile", "(732)865-1920")

            xmlwriter.WriteEndElement()

 

            'close parent node Contact

            xmlwriter.WriteEndElement()

            'close parent node Contacts

            xmlwriter.WriteEndElement()

            'close xml declaration tag

            xmlwriter.WriteEndDocument()

 

            xmlwriter.Flush()

            xmlwriter.Close()

 

            Dim doc As New XmlDocument()

            'Preserve white space for readability.

            doc.PreserveWhitespace = True

            'Load the file.

            doc.Load(Server.MapPath(filename))

 

            'Display the XML content to the console.

            TextBox1.ForeColor = System.Drawing.Color.Blue

            TextBox1.Text = doc.InnerXml

 

        Catch ex As Exception

            TextBox1.ForeColor = System.Drawing.Color.Red

            TextBox1.Text = ex.Message

        End Try

 

    End Sub

End Class

 

 

XMLTextReader

The simplest way to instantiate an object of class XMLTextReader can be achieved by passing file name with path information to its constructor.

 

The XMLTextReader has following essential methods and properties.

 

Read:- This method reads each xml node from an input file. When it reaches the end of file then it returns false. When the file is read it skips attribute nodes for some reason. Therefore one should use HasAttributes property to determine whether a particular node has attributes associated with it and then browse attributes list.

 

Close:- This method closes the input stream and sets ReadState property value to Closed.

 

NodeType:- This property is one of the enumerated values from XMLNodeType enumerator that describes the type of node. The type of node can be xml element, text, comment, declaration, end element, etc.

 

EOF:- This property describes whether the end of file being read has reached. It returns true when end of file is reached.

 

HasAttributes:- This property returns true when the xml node has attributes associated with it.

 

MoveToNextAttribute:- This method causes reader to traverse to the next attribute node in attributes list of an xml element. It returns false when it reaches the end of the list.

 

IsEmptyElement:- This function returns true if the xml element has no text value. E.g. the function will return true if it encounters an element which is <middleinitial />.

 

IsStartElement:- This function returns true if the xml element is the starting tag. E.g. the function will return true if it encounters an element which is <middleinitial>.

 

ReadState:- This property is one of the enumerated values from ReadState enumerator that describes the state of the reader. While the reader is reading the file the state value is Interactive and when it reaches the end of file the state value is EndOfFile. The other values can be xml element, text, comment, declaration, end element, etc.

 

Encoding:- This property is a read-only property that describes the type of encoding present in the file.

 

WhiteSpaceHandling:- This property is one of the enumerated values from WhiteSpaceHandling enumerator that describes how to handle white spaces within the file. This property must be set to None so that white space and significant white space nodes are not generated as part of input stream. The other values can be All(generates whitespace and significant whitespace nodes) or Significant(significant whitespace nodes only).

 

The following code browses through all xml nodes in the file and lists the order in which it visits the nodes, its type, and text contents or attribute name and value or name of the node.

 

Code:

 

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

        ShowXML()

    End Sub

 

    Private Sub ShowXML()

        Dim xmlreader As XmlTextReader

        Dim counter As Int16 = 0

        Dim xmlString As String

        Dim vbcrlf As String = Chr(13) & Chr(10)

 

        Try

            xmlreader = New XmlTextReader(Server.MapPath(filename))    'default encoding - UTF-8

            xmlreader.WhitespaceHandling = WhitespaceHandling.None

            'While xmlreader.Read()

            xmlreader.Read()

            'While Not xmlreader.ReadState.Equals(ReadState.EndOfFile)

            While Not xmlreader.EOF

                Select Case xmlreader.NodeType

                    Case XmlNodeType.Element

                        If xmlreader.IsStartElement() Then

                            xmlString &= CStr(counter) & "-Start Element-" & xmlreader.Name & vbcrlf

                        Else

                            xmlString &= CStr(counter) & "-End Element-" & xmlreader.Name & vbcrlf

                        End If

                        If xmlreader.IsEmptyElement() Then

                            xmlString &= CStr(counter) & "-Empty Element-" & xmlreader.Name & vbcrlf

                        End If

 

                        If xmlreader.HasAttributes Then

                            counter += 1

                            While xmlreader.MoveToNextAttribute()

                                xmlString &= CStr(counter) & "-Attribute-" & xmlreader.Name & "-" & xmlreader.Value & vbcrlf

                            End While

                        End If

                    Case XmlNodeType.Text

                            xmlString &= CStr(counter) & "-Text-" & xmlreader.Value & vbcrlf

                    Case XmlNodeType.CDATA

                            xmlString &= CStr(counter) & "-CDATA-" & xmlreader.Value & vbcrlf

                    Case XmlNodeType.ProcessingInstruction

                            xmlString &= CStr(counter) & "-ProcessingInstruction-" & xmlreader.Name & "-" & xmlreader.Value & vbcrlf

                    Case XmlNodeType.Comment

                            xmlString &= CStr(counter) & "-Comment-" & xmlreader.Value & vbcrlf

                    Case XmlNodeType.XmlDeclaration

                            xmlString &= CStr(counter) & "-XmlDeclaration-" & "<?xml version='1.0'?>" & vbcrlf

                    Case XmlNodeType.Document

                    Case XmlNodeType.DocumentType

                            xmlString &= CStr(counter) & "-Document-DocumentType-" & xmlreader.Name & "-" & xmlreader.Value & vbcrlf

                    Case XmlNodeType.EntityReference

                            xmlString &= CStr(counter) & "-EntityReference-" & xmlreader.Name & vbcrlf

                     Case XmlNodeType.EndElement

                            xmlString &= CStr(counter) & "-EndElement-" & xmlreader.Name & vbcrlf

                End Select

                counter += 1

                xmlreader.Read()

                'End While

            End While

 

            ''Display the XML content to the console.

            TextBox2.ForeColor = System.Drawing.Color.Brown

            TextBox2.Text = xmlString

 

        Catch ex As Exception

            TextBox2.ForeColor = System.Drawing.Color.Red

            TextBox2.Text = ex.Message

        End Try

    End Sub


Product Spotlight
Product Spotlight 

©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-26 7:15:24 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search