22

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.

MatthewSot
  • 3,516
  • 5
  • 39
  • 58
StackOverflowVeryHelpful
  • 2,347
  • 8
  • 34
  • 46

3 Answers3

37

Other people have said it, but here's explicitly a sample to convert XDocument to XElement:

 XDocument doc = XDocument.Load(...);
 return doc.Root;
Bobson
  • 13,498
  • 5
  • 55
  • 80
  • 5
    @Pawel - Yes, but I felt the need to make it very explicit, with the trivial code sample, since the OP was still looking for an answer. – Bobson Nov 19 '12 at 20:59
  • 2
    Not to forget this acts on the same reference, i.e. if you edit the resultant XElement, the changes are reflected on XDocument doc as well. This may or may not be desired. – nawfal Aug 19 '15 at 06:15
30

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

Pawel
  • 31,342
  • 4
  • 73
  • 104
8

Simple conversion from XDocument to XElement

XElement cvtXDocumentToXElement(XDocument xDoc)
{
    XElement xmlOut = XElement.Parse(xDoc.ToString());
    return xmlOut;
}
Steve Hendren
  • 89
  • 1
  • 1
  • 1
    Not to forget this creates a completely new instance of XElement, i.e. changes made to XElement wont be reflected on XDocument. This may or may not be desired. – nawfal Aug 19 '15 at 06:17