Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleNicely format an XML document in Visual Basic .NET
DescriptionThis example shows how to nicely format an XML document in Visual Basic .NET.
KeywordsXML, XmlDocument, format, format XML, indent XML, Visual Basic .NET, VB.NET
CategoriesInternet, VB.NET
 
When the form loads, the program creates an XML document (that code is omitted below).

Next the program displays the the document's OuterXml. This is not formatted.

The code then creates a StringWriter to hold the formatted XML document. It creates an XmlTextWriter attached to the StringWriter, sets its Formatting property to indicate we want an indented format, and then writes the XML document into it. It finishes by displaying the resulting string.

 
Private Sub Form1_Load(ByVal sender As System.Object, ByVal _
    e As System.EventArgs) Handles MyBase.Load
    Dim doc As New XmlDocument()
    doc.LoadXml("...")

    txtOuterXml.Text = doc.OuterXml
    txtOuterXml.Select(0, 0)

    ' Use an XmlTextWriter to format.
    ' Make a StringWriter to hold the result.
    Using sw As New System.IO.StringWriter()
        ' Make the XmlTextWriter to format the XML.
        Using xml_writer As New XmlTextWriter(sw)
            xml_writer.Formatting = Formatting.Indented
            doc.WriteTo(xml_writer)
            xml_writer.Flush()

            ' Display the result.
            txtFormatted.Text = sw.ToString()
        End Using
    End Using
    txtFormatted.Select(0, 0)
End Sub
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated