Sometimes you want to convert an XmlNode to an XElement and back again. Some programming libraries define methods that take XmlNode objects as parameters. These libraries also may contain properties and methods that return XmlNode objects. However, it is more convenient to work with LINQ to XML instead of the classes in System.Xml (XmlDocument, XmlNode, etc.) This post presents a bit of code to do these conversions.
…
using System; using System.Collections.Generic; using System.Linq; using System.Xml; using System.Xml.Linq;
public static class MyExtensions { public static XElement GetXElement(this XmlNode node) { XDocument xDoc = new XDocument(); using (XmlWriter xmlWriter = xDoc.CreateWriter()) node.WriteTo(xmlWriter); return xDoc.Root; }
public static XmlNode GetXmlNode(this XElement element)
{
using (XmlReader xmlReader = element.CreateReader())
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlReader);
return xmlDoc;
}
}
}
[http://blogs.msdn.com/ericwhite/archive/2008/12/22/ convert-xelement-to-xmlnode-and-convert-xmlnode-to-xelement.aspx]