Search code examples
c#xmllinq-to-xmlxelement

XDocument to XElement


How do you convert an XDocument to an XElement?

I found the following by searching, but it's for converting between XDocument and XmlDocument, not XDocument and XElement.

public static XElement ToXElement(this XmlElement xmlelement)
{
    return XElement.Load(xmlelement.CreateNavigator().ReadSubtree());
}

public static XmlDocument ToXmlDocument(this XDocument xdoc)
{
    var xmldoc = new XmlDocument();
    xmldoc.Load(xdoc.CreateReader());
    return xmldoc;
}

I couldn't find anything to convert an XDocument to an XElement. Any help would be appreciated.


Solution

  • XDocument to XmlDocument:

    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load(xdoc.CreateReader());
    

    XmlDocument to XDocument

    XDocument xDoc = XDocument.Load(new XmlNodeReader(xmlDoc));
    

    To get the root element from the XDocument you use xDoc.Root