You can use the LINQ to XML method XElement.Parse()
to parse any well-formed XML document, however your CDATA string <![CDATA[John Smith]]>
is not a well-formed XML document, it's just a document fragment, since it lacks a root element. To convert it to well-formed XML, you can surround it by a synthetic root element, parse that, and extract the value like so:
var value = XElement.Parse("<a>" + cdatastring + "</a>").Value;
If your cdatastring
is longer than 42,000 characters or so and thus the string with the added root element would go on the large object heap, you could grab ChainedTextReader
and public static TextReader Extensions.Concat(this TextReader first, TextReader second)
from the answer to How to string multiple TextReaders together? by Rex M and create the following extension method:
public static class XmlExtensions
{
public static XElement ParseFragment(string xmlFragment)
{
using (var reader = new StringReader("<a>").Concat(new StringReader(xmlFragment)).Concat(new StringReader("</a>")))
{
return XElement.Load(reader);
}
}
}
Then extract your CDATA value like so:
var value = XmlExtensions.ParseFragment(cdatastring).Value;
Sample working .Net fiddle here.