본문 바로가기

VB.net & WPF & C#

Nicely format an XML document in VB.NET


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

Document의 outerXml을 String으로 전환할때 Formatting적용.


'Xml Formatting
Dim settings As XmlWriterSettings = New XmlWriterSettings()
settings.Indent = True
settings.NewLineOnAttributes = True
Dim builder As New StringBuilder()
Dim writer As XmlWriter = XmlWriter.Create(builder, settings)
OrgDoc.Save(writer)
msgbox(builder.toString)

Document의 Save(xmlwriter)를 이용하여 Stringbuilder에 formatting적용.