Converting XElement into XmlNode

Sangram Nandkhile picture Sangram Nandkhile · Mar 22, 2011 · Viewed 45.7k times · Source

I know there is no direct method of doing it but still.. Can we convert XElement element into XmlNode. Options like InnerText and InnerXml are XmlNode specific.

so,if i want to use these options, what can be done to convert XElement into XmlNode and vice versa.

Answer

BrokenGlass picture BrokenGlass · Mar 23, 2011

I use the following extension methods, they seem to be quite common:

public static class MyExtensions
{
    public static XElement ToXElement(this XmlNode node)
    {
        XDocument xDoc = new XDocument();
        using (XmlWriter xmlWriter = xDoc.CreateWriter())
            node.WriteTo(xmlWriter);
        return xDoc.Root;
    }

    public static XmlNode ToXmlNode(this XElement element)
    {
        using (XmlReader xmlReader = element.CreateReader())
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(xmlReader);
            return xmlDoc;
        }
    }
}