Search code examples
c#.netlinqlinq-to-xml

How to convert XmlNode into XElement?


I have an old XmlNode-based code. but the simplest way to solve my current task is to use XElement and LINQ-to-XML. The only problem is that there is no direct or obvious method for converting a XmlNode to a XElement in .NET Framework.

So for starters, I want to implement a method that receives a XmlNode instance and converts it to a XElement instance.

How can I implement this conversion?


Solution

  • var xElem = XElement.Load( xmlElement.CreateNavigator().ReadSubtree() );
    

    There are two problems with xmlElement.InnerXml used in other answer,

    1- You will loose the root element (Of course, it can be handled easily)

    XmlDocument doc = new XmlDocument();
    doc.LoadXml("<root> <sub>aaa</sub> </root>");
    var xElem1 = XElement.Load(doc.DocumentElement.CreateNavigator().ReadSubtree());
    var xElem2 = XElement.Parse(doc.DocumentElement.InnerXml);
    

    xElem2 will be <sub>aaa</sub>, without(root)

    2- You will get exception if your xml contains text nodes

    XmlDocument doc = new XmlDocument();
    doc.LoadXml("<root> text <sub>aaa</sub> </root>");
    var xElem1 = XElement.Load(doc.DocumentElement.CreateNavigator().ReadSubtree());
    var xElem2 = XElement.Parse(doc.DocumentElement.InnerXml); //<-- XmlException