Sunday, October 4, 2009

Getting an XmlElement from string in C#

I had a bunch of Xml coming at me in a POST response and needed it to be an XmlElement. I ended up doing writing a quick method that does the trick, but I am not sure if it is the best way (making it an extension method made sense in context).

public XmlElement ToXmlElement (this string xml)
{
XmlDocumentFragment frag = new XmlDocument().CreateDocumentFragment();

frag.InnerXml = xml;

return frag.FirstChild as XmlElement;
}

The problem with this is you have to assume the string you are passing in is well-f0rmed XML.