Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 852
Alexander Abakumov Avatar asked Jul 14 '14 19:07

Alexander Abakumov


3 Answers

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
like image 89
EZI Avatar answered Nov 15 '22 04:11

EZI


You can try using InnerXml property of XmlElement to get xml content of your element then parse it to XElement using XElement.Parse:

public static XElement ToXELement(this XmlElement source)
{
    return XElement.Parse(source.InnerXml);
}
like image 40
Selman Genç Avatar answered Nov 15 '22 04:11

Selman Genç


The only way to take over all is to use OuterXml.

XElement.Parse(xNode.OuterXml);

Another way is to change the outer root element via.

XElement.Parse("<NewRoot>" + xNode.InnerXml + "</NewRoot>");
like image 27
Trivalik Avatar answered Nov 15 '22 04:11

Trivalik