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.

1 comment:

  1. I love extension methods - best thing since code-behind.

    I've worked with XML a lot but generally every piece of XML was converted to an XmlDocument.

    Depends what the bigger picture is I guess.

    ReplyDelete