10

Possible Duplicate:
Best way to get InnerXml of an XElement?

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? :)

Community
  • 1
  • 1
Michael
  • 210
  • 1
  • 3
  • 10

5 Answers5

28

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
  • 57,579
  • 7
  • 124
  • 111
  • 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 Jun 19 '10 at 15:58
3

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
  • 213,145
  • 36
  • 401
  • 431
2

See a variety of options, with performance testing here: 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
///  https://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();
}
Community
  • 1
  • 1
Oskar Austegard
  • 4,599
  • 4
  • 36
  • 50
0

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

Returns an IEnumerable with strings.

Jouke van der Maas
  • 4,117
  • 2
  • 28
  • 35
0

For me it works like this, thanks to Quartermeister

string result = string.Concat(instanceXElement.Nodes().ToArray());

I was having just HTML code in my instanceXElement that i wanted to fetch out exactly.

Shaheed ulHaq
  • 498
  • 5
  • 20