Tutorial :How can I get an XML fragment as a string from an XElement?


I have an XElement and inside that element I have another XML fragment. How do I retrieve the XML?

If I try the following, I get only the value:

string str = "<Root><Node1>value1</Node1><Node2></Node2></Root>";    XElement elem = XElement.Parse(str);  string innerXml = elem.value;  


Eric White just posted a blog article to do exactly that - convert XElement to XmlNode and back.

Check it out here.



Try something like this:

var x = elem.Descendants();  

This will return you all the descendants of the root node - if you want a specific one you can pass its name as a string parameter to this same method.

Edit: If you really need it as a string you can aggregate the nodes. Here is an extension method that will do the trick:

public static String InnerXml(this XElement source)  {      return source.Descendants().Select(x => x.ToString()).Aggregate(String.Concat);  }  


I just going to create an extension method InnerXml to return me the innerXML

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »