Convert XmlElement to XElement (Extension Method)

I was using some web-services that returned there values in an XmlElement. I needed to convert this XmlElement to something that I can use with LINQ. I didn't find good solutions on the internet. So I started building my own convert logic. After all kinds of solutions I ended up with creating an new XmlDocument, adding the XmlElement to the XmlDocument and then convert the innerXml of the XmlDocument to an XElement. Not really nice but it does the trick.

I've rewritten the code into a Extension Method for the XmlElement.

[code:c#]

public static XElement ToXElement(this XmlElement xml)
{
   XmlDocument doc = new XmlDocument();

   doc.AppendChild(doc.ImportNode(xml, true));

   return XElement.Parse(doc.InnerXml);

}

[/code]


You use the Extension Method like this:

[code:c#]

XmlElement xmlElement = wsClient.DoWebServiceRequest();
XElement xml = xmlElement.ToXElement();

[/code]


Please tell me if you have a better way of doing this!

Cheers,
Pieter

5 Replies to “Convert XmlElement to XElement (Extension Method)”

  1. Hi Pieter,

    you can request the OuterXml from the XmlElement so no need to create the XmlDocument etc, just use XElement.Parse(xml.OuterXml), also, extension methods are not always the best solution, this is what I use.

    [quote]
    public static XElement MakeElement(XmlNode node, params object[] descendants)
    {
    XElement element = null;
    if(null != node) {
    element = XElement.Parse(node.OuterXml);
    if(null != descendants) element.Add(descendants);
    }
    return element;
    }
    [/quote]

    Then you can do:

    var result = MakeElement(wsClient.DoWebServiceRequest());

  2. You can request the OuterXml from the XmlElement so no need to create the XmlDocument etc, just use XElement.Parse(xml.OuterXml), also, extension methods are not always the best solution, this is what I use.

  3. I haven’t tried this yet, but what about XDocument.ReadFrom(new XmlNodeReader(node))? Seems to me it would be faster than converting to/from a string. ūüôā

Leave a Reply

Your email address will not be published. Required fields are marked *