views:

89

answers:

3

I'm looking for the simplest way to convert a string into an XmlElement in C#.

Thanks

+2  A: 

Use XmlDocument.LoadXml:

XmlDocument doc = new XmlDocument();
doc.LoadXml("<item><name>wrench</name></item>");
XmlElement root = doc.DocumentElement;

(Or in case you're talking about XElement, use XDocument.Parse:)

XDocument doc = XDocument.Parse("<item><name>wrench</name></item>");
XElement root = doc.Root;
dtb
He wanted the element, and for XElement he can just do XElement.Parse(xmlString), but you're giving him a document not element.
Jimmy Hoffa
@Jimmy Hoffa: If you have a document, it's straightforward to get the root element, no?
dtb
@dtb: Sure, was just saying your answer could be tailored to the posters question a little more in case it's not as easy for him as it is for us..
Jimmy Hoffa
@Jimmy Hoffa: Your wish is my command. :-)
dtb
+1  A: 

Use this:

private static XmlElement GetElement(string xml)
    {
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(xml);
        return doc.DocumentElement;
    }

Beware!! If you need to add this element to another document first you need to Import it using ImportNode.

Aliostad
Wont this fail if there's no <?xml version bla bla> tag at the beginning? If he just has an xml fragment I don't think this will work..
Jimmy Hoffa
@Jimmy Hoffa: IIRC LoadXml takes any well-formed XML fragment that contains exactly one XML element at the top level. `<?xml` at the beginning is not required.
dtb
Yes, it will work, try it yourself.
Aliostad
Thanks for your response.
CletusLoomis
Anytime... mate.
Aliostad
+1  A: 

You can use XmlDocument.LoadXml() to do this.

Here is a simple examle:

XmlDocument xmlDoc = new XmlDocument(); 
xmlDoc.LoadXml("YOUR XML STRING"); 
Florian
Thanks for your response.
CletusLoomis