Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting XElement into XmlNode

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.

like image 397
Sangram Nandkhile Avatar asked Mar 22 '11 10:03

Sangram Nandkhile


4 Answers

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;
        }
    }
}
like image 94
BrokenGlass Avatar answered Oct 27 '22 11:10

BrokenGlass


Here is converting from string to XElement to XmlNode and back to XElement. ToString() on XElement is similar to OuterXml on XmlNode.

    XElement xE = XElement.Parse("<Outer><Inner><Data /></Inner></Outer>");

    XmlDocument xD = new XmlDocument();
    xD.LoadXml(xE.ToString());
    XmlNode xN = xD.FirstChild;

    XElement xE2 = XElement.Parse(xN.OuterXml); 
like image 30
Wes Grant Avatar answered Oct 27 '22 11:10

Wes Grant


Based on BrokenGlass's answer, if you wish to embed the XmlNode to an XmlDocument, than use:

public static class MyExtensions
{
    public static XmlNode ToXmlNode(this XElement element, XmlDocument xmlDoc = null)
    {
        using (XmlReader xmlReader = element.CreateReader())
        {
            if(xmlDoc==null) xmlDoc = new XmlDocument();
            return xmlDoc.ReadNode(xmlReader);
        }
    }
}

Note: if you try to insert into a document a node, that is created by a different document, than it will throw an exception: "The node to be inserted is from a different document context."

like image 37
jaraics Avatar answered Oct 27 '22 10:10

jaraics


XElement xelement = GetXElement();
XmlNode node = new XmlDocument().ReadNode(xelement.CreateReader()) as XmlNode;
like image 20
Mohini Mhetre Avatar answered Oct 27 '22 10:10

Mohini Mhetre