tags:

views:

477

answers:

3

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;
+1  A: 

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);
}
Andrew Hare
that gives the XML including Root, but i want the innerXml
jyotishka bora
i dont think that will work, because that will return me a enumeration of all the descendants, i will have the add the each element to get the innerXml
jyotishka bora
A: 

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

jyotishka bora
A: 

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

Check it out here.

Marc

marc_s