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? :)
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? :)
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());
foreach(var element in Element.Elements()) { yield return element.ToString(); }
Returns an IEnumerable with strings.
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());
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();
}