How to get Xml as a string from XDocument?

I am new to LINQ to XML. Once you have created an XDocument , how do you get the OuterXml this, how did you do it with an XmlDocument ?

+61
string c # xml linq-to-xml
Dec 26 '10 at 11:07
source share
4 answers

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

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

This works with all XObjects such as XElement, etc.

+84
Dec 26 '10 at 11:11
source share
— -

I do not know when this changed, but today (July 2017), when you are trying to answer, I received

"System.Xml.XmlDocument"

Instead of ToString() you can use the originally intended way to access the contents of the XmlDocument : writing the xml document to the stream.

 XmlDocument xml = ...; string result; using (StringWriter writer = new StringWriter()) { xml.Save(writer); result = writer.ToString(); } 
+9
Jul 26 '17 at 11:01
source share

Use ToString () to convert an XDocument to 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(); 
+3
Apr 12 '13 at 9:45
source share

Running XDocument.ToString () may not give you the full XML.

To get the XML declaration at the beginning of an 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()); 
0
Jul 08 '19 at 12:45
source share



All Articles