How to get Xml as string from XDocument?

84,207

Solution 1

You only need to use the overridden ToString() method of the object:

XDocument xmlDoc ...
string xml = xmlDoc.ToString();

This works with all XObjects, like XElement, etc.

Solution 2

I don't know when this changed, but today (July 2017) when trying the answers out, I got

"System.Xml.XmlDocument"

Instead of ToString(), you can use the originally intended way accessing the XmlDocument content: writing the xml doc to a stream.

XmlDocument xml = ...;
string result;

using (StringWriter writer = new StringWriter())
{
  xml.Save(writer);
  result = writer.ToString();
}

Solution 3

Doing XDocument.ToString() may not get you the full XML.

In order to get the XML declaration at the start of the XML document as a string, use the XDocument.Save() method:

    var ms = new MemoryStream();
    using (var xw = XmlWriter.Create(new StreamWriter(ms, Encoding.GetEncoding("ISO-8859-1"))))
        new XDocument(new XElement("Root", new XElement("Leaf", "data"))).Save(xw);
    var myXml = Encoding.GetEncoding("ISO-8859-1").GetString(ms.ToArray());

Solution 4

Several responses give a slightly incorrect answer.

  • XDocument.ToString() omits the XML declaration (and, according to @Alex Gordon, may return invalid XML if it contains encoded unusual characters like &).
  • Saving XDocument to StringWriter will cause .NET to emit encoding="utf-16", which you most likely don't want (if you save XML as a string, it's probably because you want to later save it as a file, and de facto standard for saving files is UTF-8 - .NET saves text files as UTF-8 unless specified otherwise).
  • @Wolfgang Grinfeld's answer is heading in the right direction, but it's unnecessarily complex.

Use the following:

  var memory = new MemoryStream();
  xDocument.Save(memory);
  string xmlText = Encoding.UTF8.GetString(memory.ToArray());

This will return XML text with UTF-8 declaration.

Solution 5

Use ToString() to convert XDocument into a string:

string result = string.Empty;
XElement root = new XElement("xml",
    new XElement("MsgType", "<![CDATA[" + "text" + "]]>"),
    new XElement("Content", "<![CDATA[" + "Hi, this is Wilson Wu Testing for you! You can ask any question but no answer can be replied...." + "]]>"),
    new XElement("FuncFlag", 0)
);
result = root.ToString();
Share:
84,207

Related videos on Youtube

Ashish Gupta
Author by

Ashish Gupta

Cloud Security Engineering and Operations guy at LPL Financial. Blog :- http://guptaashish.com LinkedIn Profile :- www.linkedin.com/in/ashishrgupta

Updated on July 05, 2022

Comments

  • Ashish Gupta
    Ashish Gupta almost 2 years

    I am new to LINQ to XML. After you have built XDocument, how do you get the OuterXml of it like you did with XmlDocument?

  • Andrzej Gis
    Andrzej Gis over 10 years
    What on earth is this method for? o.0
  • Admin
    Admin over 10 years
    It is only for simple demonstration to have an easy link to XmlDocument.OuterXml property.
  • The Muffin Man
    The Muffin Man over 7 years
    This now returns System.Xml.XmlDocument
  • Mathijs Segers
    Mathijs Segers over 6 years
    @TheMuffinMan Then you're doing it wrong, since this answer is about XDocument not XmlDocument (Linq)
  • Mathijs Segers
    Mathijs Segers over 6 years
    Of course it's confusing but if you're working with Linq you should be using XDocument not XmlDocument. Then it should work :-).
  • Alex Gordon
    Alex Gordon about 5 years
    if any of your XML has & or other special characters, this will not work
  • Gábor
    Gábor over 3 years
    There is hardly any need for this complexity and copying again and again. Just use a StringWriter() to Save() to directly.
  • Mike Rosoft
    Mike Rosoft almost 3 years
    By my experience, XDocument.ToString() omits the XML header. Use XDocument.Save(StringWriter) instead.
  • Mike Rosoft
    Mike Rosoft almost 3 years
    Follow-up: Writing to StringWriter causes XDocument to duly add encoding="utf-16" to the XML declaration, which you most likely don't want.
  • Zi Cold
    Zi Cold about 2 years
    This way string will still contain &amp; characters, but header (<?xml ?>) will be here.