> I have an xml doc in a string it all just runs to gether no crlf or
indents, I want to lay it out in a textbox so each element is on its
ownline and indented correctly.
The following routine creates a string from an XML document with all
the formatting characters (crlf, tab et al.) in place.
Good News: It gives a nicely formatted output for my textbox
Bad news: There a few strangenesses with it that I haven't tracked down
yet and might cause problems (or they might not)
The basic idea is to use an XMLTextWriter to write to a MemoryStream
and then read the contents of the memStream into a string.
Private Function PrettyPrintXML( ByVal xmlDoc As XmlDocument) As
String
Dim ret As String = String.Empty
Dim memStream As New MemoryStream
Dim writer As XmlTextWriter
Dim reader As StreamReader
Try
writer = New XmlTextWriter(m emStream,
System.Text.Enc oding.UTF8)
writer.Formatti ng = Formatting.Inde nted
writer.Indentat ion = 3
xmlDoc.WriteTo( writer)
writer.Flush()
' NOTE1 : We can't close the writer here as this will close
the memstream
'ret =
System.Text.Enc oding.UTF8.GetS tring(memStream .GetBuffer())
'NOTE2: This looks like it should work but gives me extra
characters at the start of the
' string. (1st 3 chars of the memstream are not
obviously part of the XML output.
memStream.Seek( 0, SeekOrigin.Begi n)
reader = New StreamReader(me mStream)
ret = reader.ReadToEn d
Finally
'NOTE3: As both the reader and writer are pointing to the
memstream and both
' try to close the memstream when they are
closed we cannot close both
' No idea if this will cause an error or not.
reader.Close()
End Try
Return ret
End Function
If anyone can come up with a better way (or tweaks on this code) I
would be interested.
Thanks
Alan.