Convert XmlElement to XElement (Extension Method)

by Pieter Brinkman 8. December 2008 05:31

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.

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

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

   return XElement.Parse(doc.InnerXml);

}


You use the Extension Method like this:

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


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

Cheers,
Pieter

Tags: , , , , , , ,

Linq | XML

Comments

12/20/2008 12:51:24 PM #

Kenny Stuart

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.


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;
}


Then you can do:

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

Kenny Stuart United Kingdom

4/9/2009 9:18:54 PM #

Michael Freidgeim

Discussion  forums.asp.net/p/1278169/2437834.aspx#2437834 describes the opposite operation ConvertXNodeToXmlNode

Michael Freidgeim Australia

7/8/2009 10:25:48 PM #

club penguin cheats

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.

club penguin cheats United States

7/9/2009 8:01:42 AM #

Pieter

Hankjmatt > Thanks for the reply, I will try your solution.

Pieter Netherlands

Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen

About Me

My name is Pieter Brinkman I am Solution Architect for Sitecore in The Netherlands. My interests are mainly ASP.NET, MSSQL and Content Management Systems.

Calendar

<<  February 2012  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
2728291234
567891011

View posts in large calendar

RecentComments

Comment RSS

Most comments