Coder Perfect

XmlDocument to String conversion

Problem

Here’s how I’m converting an XMLDocument to a String right now.

StringWriter stringWriter = new StringWriter();
XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);

xmlDoc.WriteTo(xmlTextWriter);

return stringWriter.ToString();

It escapes them if I have ” ((quotes) which I have in attributes).

For Instance:

<Campaign name="ABC">
</Campaign>

The expected XML is seen above. However, it reappears.

<Campaign name=\"ABC\">
</Campaign>

String is something I’m good at. Is it acceptable to use “” instead of “”? Are there any unfavorable effects? Will it still work if the XML has a “”?

Asked by akif

Solution #1

Assuming xmlDoc is an XmlDocument object whats wrong with xmlDoc.OuterXml?

return xmlDoc.OuterXml;

The OuterXml attribute returns the xml as a string.

Answered by Chris Moutray

Solution #2

There are no quotations. It’s just the Visual Studio debugger. You’ll notice if you print to the terminal or save to a file. As an aside, always dispose of disposable items:

using (var stringWriter = new StringWriter())
using (var xmlTextWriter = XmlWriter.Create(stringWriter))
{
    xmlDoc.WriteTo(xmlTextWriter);
    xmlTextWriter.Flush();
    return stringWriter.GetStringBuilder().ToString();
}

Answered by Darin Dimitrov

Solution #3

If you’re a Windows user. You can use yourXmlDocument instead of the Data.Xml.Dom.XmlDocument version of XmlDocument (which is used in UWP apps). To get the XML as a string, use GetXml().

Answered by Whyser

Solution #4

As a means of extension:

public static class Extensions
{
    public static string AsString(this XmlDocument xmlDoc)
    {
        using (StringWriter sw = new StringWriter())
        {
            using (XmlTextWriter tx = new XmlTextWriter(sw))
            {
                xmlDoc.WriteTo(tx);
                string strXmlText = sw.ToString();
                return strXmlText;
            }
        }
    }
}

To put it plainly:

yourXmlDoc.AsString()

Answered by SixOThree

Solution #5

The debugger displays ” as “, but the data in the string is correct, and you don’t need to replace anything. If you try to save your string to a file, you’ll notice that it’s right.

Answered by Arsen Mkrtchyan

Post is based on https://stackoverflow.com/questions/2407302/convert-xmldocument-to-string