XDocument to XElement
32,999
Solution 1
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
Solution 2
Other people have said it, but here's explicitly a sample to convert XDocument to XElement:
XDocument doc = XDocument.Load(...);
return doc.Root;
Solution 3
Simple conversion from XDocument to XElement
XElement cvtXDocumentToXElement(XDocument xDoc)
{
XElement xmlOut = XElement.Parse(xDoc.ToString());
return xmlOut;
}
Author by
StackOverflowVeryHelpful
Updated on July 09, 2022Comments
-
StackOverflowVeryHelpful almost 2 years
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.
-
Bobson over 11 years@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.
-
nawfal over 8 yearsNot 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 over 8 yearsNot 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.