Search code examples
.netxmlvb.netxmldocument

XmlDocument.InnerText Replacement for New .NET


I am attempting to convert an object of type XmlDocument to a String.

In Visual Studio 2010 all that was required was to call XmlDocument.InnerText as per the documentation here.

In the new .NET framework XmlDocument.InnerText has been discontinued, and now throws an exception as per the documentation here.

I would simply use XmlDocument.InnerXml as this returns a String, although the issue is that the string returned does not contain any of the xml document formatting (newlines, indentation, etc). The legacy XmlDocument.InnerText did return all of this.

It looks like XmlDocument.InnerText is still available for Nodes and XmlElements, although I'm wondering what the simplest way would be to get the entire XmlDocument as text.


Solution

  • You can accomplish this with a StringWriter...

        ' build an XML document to test
        Dim x As New System.Text.StringBuilder
        With x
            .AppendLine("<root>")
            .AppendLine("<foo>bar</foo>")
            .AppendLine("</root>")
        End With
        Dim d As New XmlDocument
        d.LoadXml(x.ToString)
    
        ' create a stringwriter
        Dim sw As New System.IO.StringWriter
    
        ' write the xml to the stringwriter
        d.Save(sw)
    
        ' get the contents of the stringwriter with whitespace and line breaks preserved
        Debug.WriteLine(sw.ToString)