256

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 "\"

akif
  • 12,034
  • 24
  • 73
  • 85

6 Answers6

734

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

return xmlDoc.OuterXml;

The OuterXml property returns a string version of the xml.

Chris Moutray
  • 18,029
  • 7
  • 45
  • 66
  • 4
    Well you are right. I tried that first but when I saw the quotes in the debugger. I thought its because of OuterXml and try that StringWriter method. But I was wrong the quotes were only in the debugger. So I'll just use OuterXml. Thanks – akif Mar 09 '10 at 07:43
  • Worked for me! Just do a null check on xmlDoc! return xmlDoc == null ? "xmlDoc is null" : xmlDoc.OuterXml; – SarjanWebDev Oct 27 '14 at 01:04
  • 1
    @SarjanWebDev if you think your object could be null, then the null-check goes without saying and for every answer here; and really for every interaction with an object in C# - personally I try to ensure objects are always constructed so that I don't have to bloat the code with null-checks everywhere... i guess it just depends on your code base... – Chris Moutray Oct 27 '14 at 06:09
  • 12
    (y) but OuterXml doesn't include declarative tag – hazjack Sep 28 '15 at 04:50
  • @hazjack I wouldn't expect it to, that doesn't make sense; in any event w3 says it optional for v1 spec http://www.w3.org/TR/xml/#sec-prolog-dtd – Chris Moutray Sep 28 '15 at 06:35
  • @hazjack also I would say that the encoding format doesn't really apply to the c# string more so the final output if you were to write to file or stream. – Chris Moutray Sep 28 '15 at 06:43
  • Yes, thanks for the link. The version 1.1 says it must have an xml declaration http://www.w3.org/TR/xml11/#sec-prolog-dtd – hazjack Sep 28 '15 at 08:24
  • @hazjack ok I see... your example was for v1.0 – Chris Moutray Sep 28 '15 at 08:43
  • 3
    @hazjack if you want declarative tag then make use of the XmlDeclaration Class https://msdn.microsoft.com/en-us/library/system.xml.xmldeclaration.aspx - if you then want to write it to file then then use the save method found on you XmlDocument instance https://msdn.microsoft.com/en-us/library/dw229a22.aspx - to me the declarative tag only makes sense if you're writing to say file and not a C# string – Chris Moutray Sep 28 '15 at 08:52
  • Should be the accepted answer since you can't use XmlWriter in some platforms like UWP – fillobotto Jan 09 '16 at 13:33
  • Large files throw OUtOfMemoryException – Ruslan_K Nov 06 '20 at 02:27
209

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();
}
Brian
  • 25,523
  • 18
  • 82
  • 173
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 2
    +1 for fixing the code to use `using` blocks and not `XmlTextWriter`. – John Saunders Mar 09 '10 at 08:02
  • 1
    Worthing noting (as mentioned in the remarks here: http://msdn.microsoft.com/en-us/library/system.xml.xmlwriter.aspx) that the elements and attributes will not be written until you call the Close method of the XmlWriter. – TonE Aug 23 '11 at 14:47
  • Some of them may be written immediately. It depends on buffering. Regardless, I added a call to `Flush`, though a call to `Close` or just closing the `xmlTextWriter` `using` block would accomplish the same. – Brian Mar 27 '12 at 16:46
  • 18
    To make the xml pretty, pass in this settings object to XmlWriter.Create: XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.IndentChars = " "; settings.Encoding = Encoding.UTF8; – Adam Bruss Sep 18 '12 at 16:44
13

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.

Whyser
  • 2,187
  • 2
  • 20
  • 40
6

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()
SixOThree
  • 745
  • 1
  • 9
  • 21
3

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

2

" 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.

saluce
  • 13,035
  • 3
  • 50
  • 67
Arsen Mkrtchyan
  • 49,896
  • 32
  • 148
  • 184