Convert XmlDocument to String

C#StringEscapingQuotesXmldocument

C# Problem Overview


Here is how I'm currently converting XMLDocument to String

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

xmlDoc.WriteTo(xmlTextWriter);

return stringWriter.ToString();

The problem with this method is that if I have " ((quotes) which I have in attributes) it escapes them.

For Instance:

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

Above is the expected XML. But it returns

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

I can do String.Replace "" but is that method okay? Are there any side-effects? Will it work fine if the XML itself contains a ""

C# Solutions


Solution 1 - C#

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

return xmlDoc.OuterXml;

The OuterXml property returns a string version of the xml.

Solution 2 - C#

There aren't any quotes. It's just VS debugger. Try printing to the console or saving to a file and you'll see. As a side note: always dispose disposable objects:

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

Solution 3 - C#

If you are using Windows.Data.Xml.Dom.XmlDocument version of XmlDocument (used in UWP apps for example), you can use yourXmlDocument.GetXml() to get the XML as a string.

Solution 4 - C#

As an extension method:

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;
            }
        }
    }
}

Now to use simply:

yourXmlDoc.AsString()

Solution 5 - C#

" is shown as \" in the debugger, but the data is correct in the string, and you don't need to replace anything. Try to dump your string to a file and you will note that the string is correct.

Solution 6 - C#

you can use xmlDoc.InnerXml property to get xml in string

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionakifView Question on Stackoverflow
Solution 1 - C#Chris MoutrayView Answer on Stackoverflow
Solution 2 - C#Darin DimitrovView Answer on Stackoverflow
Solution 3 - C#WhyserView Answer on Stackoverflow
Solution 4 - C#SixOThreeView Answer on Stackoverflow
Solution 5 - C#Arsen MkrtchyanView Answer on Stackoverflow
Solution 6 - C#احمد بندارىView Answer on Stackoverflow