views:

116

answers:

4

I am using an XElement to hold a block of HTML serverside.

I would like to convert the children of that XElement into a string, sort of like an "InnerHtml" property does in javascript.

Can someone help me on this please? :)

A: 

The XElement class doesn't provide a method to directly get the "inner XML" of the element.
You can concatenate the child elements manually though, for example using

string result = string.Concat(element.Elements());

or

string result = string.Join(Environment.NewLine, element.Elements());
dtb
A: 

foreach(var element in Element.Elements()) { yield return element.ToString(); }

Returns an IEnumerable with strings.

Jouke van der Maas
+2  A: 

The other answers will work if the element only contains other elements. If you want to include text as well, you'll want to use Nodes() instead of Elements():

var result = string.Concat(element.Nodes());
Quartermeister
I just tested this one, it worked perfectly. This was my first question on Stack Overflow, I am certainly impressed by how quick I got it answered. :)
Michael
A: 

See a variety of options, with performance testing here: http://stackoverflow.com/questions/3793/best-way-to-get-innerxml-of-an-xelement

You may want to create an extension method for your quiver as such:

/// <summary>
///  Gets the inner XML of an <see cref="XElement"/>. Copied from
///  http://stackoverflow.com/questions/3793/best-way-to-get-innerxml-of-an-xelement
/// </summary>
/// <param name="element">The element.</param>
/// <returns>The inner XML</returns>
public static string GetInnerXml(this XElement element)
{
    var reader = element.CreateReader();
    reader.MoveToContent();
    return reader.ReadInnerXml();
}
Oskar Austegard