Tuesday, March 1, 2011

C# XElement: Node Formatting with HTML

I'm extracting XML node from an XElement. When I use XElement.Value it strips any HTML that may be in the node.

I know that if I do XElement.ToString() I can keep the HTML, but it also gives me the node tags. Is there any way to extract the content of a Node as is without the HTML being stripped out?

Cheers.

From stackoverflow
  • You need to concatenate the nodes inside the XElement, like this:

    node.Nodes().Aggregate(new StringBuilder(), (sb, n) => sb.Append(n.ToString())).ToString()
    

    Or, in .Net 4.0:

    String.Concat(node.Nodes())
    
    Arnej65 : This worked perfectly. Makes total sense, when you see it. Cheers
  • Alternatively:

    using System.Xml.XPath;
    
    string xml = node.CreateNavigator().InnerXml;
    

0 comments:

Post a Comment