//
You're reading...
Tips/Tricks, VB.Net, XML

Format XML using VB.Net

While working with xml it is more meaningful to the user if xml could appear in a hierarchical manner which can increase understandability.

For example the below sample is preferable from perspective of readability and understandability:

<?xml version="1.0"?>
<note>
           <to>Tove</to>
           <from>Jani</from>
           <heading>Reminder</heading>
           <body>
                      <name>abc</name>
                      <message>Don't forget me this weekend!</message>
           </body>
</note>

while this detracts the user concentration:

<?xml version="1.0"?><note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body><name>abc</name>
<code>0</code><message>Don't forget me this weekend!</message></body></note>

When we work with .net we have a built-in functionality in “XML EDITOR” toolbar to format whole document.

I have two options to format xml document excluding the one which .Net offers(as discussed above).

This is how we can format XML in the following two ways:

Using XmlWriterSettings

 
        Dim wrPath As XmlWriter = XmlWriter.Create("D:\abc.txt", New XmlWriterSettings() With {.Indent = True, .CloseOutput = True})
        xDoc.WriteTo(wrPath)
        Dim sb As New Text.StringBuilder()
        Dim wrString As XmlWriter = XmlWriter.Create(sb, New XmlWriterSettings() With {.Indent = True, .CloseOutput = True})
        xDoc.WriteTo(wrString)
        wrString.Close()

        ' At this point check out "sb" variable

Using Recursion

    Private Function DoFormating(ByVal nodes As XmlNodeList, ByVal paddingLen As Integer) As String
        For Each node As XmlNode In nodes
            If (node.HasChildNodes) Then
                formattedString &= IIf(String.IsNullOrEmpty(formattedString), "", IIf(formattedString.EndsWith(">"), Environment.NewLine & _
                                                "".PadLeft(paddingLen), "")) & "<" & node.Name & _
                                                String.Join("", node.Attributes.OfType(Of XmlAttribute).Select(Function(c) " " & c.Name & "=""" & c.Value & """").ToArray()) & ">"
                DoFormating(node.ChildNodes, paddingLen + 2)
                formattedString &= (IIf(formattedString.EndsWith(">"), Environment.NewLine & "".PadLeft(paddingLen), "")) & _
                                                ("</" & node.Name & ">")
            Else
                If (node.NodeType = XmlNodeType.XmlDeclaration) Then : formattedString &= node.OuterXml
                ElseIf (node.NodeType = XmlNodeType.Text) Then : formattedString &= node.Value
                Else : formattedString &= Environment.NewLine & "".PadLeft(paddingLen) & node.OuterXml
                End If
            End If
        Next
        Return formattedString.TrimEnd(Environment.NewLine.ToCharArray())
    End Function

where “formattedString” is a global variable that will hold the formatted string.

How to use Recursive implementation:

 Dim xmlStr As String = System.IO.File.ReadAllText("../../XMLFile1.xml")
Dim xDoc As New XmlDocument()
xDoc.LoadXml(xmlStr)
Dim formattedXml As String = DoFormating(xDoc.ChildNodes, 0)
' Check out "formattedXml" as this point

I hope this can help you if you have made this executable and you don’t have Visual Studio IDE available.

Await your feedback and suggestions.

Regards,
Shahan

Advertisements

About Shahan Ayyub

Shahan is a Microsoft Certified Professional of .Net. Mostly self taught programmer and a quick learner, who just love to code and always eager to find unique solutions to the common problems. Currently working as an iOS developer.

Discussion

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: