StackOverflowVeryHelpful
StackOverflowVeryHelpful

Reputation: 2427

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.

Upvotes: 22

Views: 37381

Answers (3)

Steve Hendren
Steve Hendren

Reputation: 89

Simple conversion from XDocument to XElement

XElement cvtXDocumentToXElement(XDocument xDoc)
{
    XElement xmlOut = XElement.Parse(xDoc.ToString());
    return xmlOut;
}

Upvotes: 8

Bobson
Bobson

Reputation: 13696

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

 XDocument doc = XDocument.Load(...);
 return doc.Root;

Upvotes: 40

Pawel
Pawel

Reputation: 31610

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

Upvotes: 30

Related Questions