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?
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
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);
}
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>");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With