Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 517
StackOverflowVeryHelpful Avatar asked Nov 19 '12 19:11

StackOverflowVeryHelpful


People also ask

How do I convert XDocument to XElement?

You can wrap the XmlDocument with an XmlNodeReader and feed it to XElement. Load(). The other direction is available as well using XElement. CreateReader().

How to convert XmlDocument to XmlElement in c#?

XmlDocument doc = new XmlDocument(); doc. LoadXml("<item><name>wrench</name></item>"); XmlElement root = doc. DocumentElement; (Or in case you're talking about XElement, use XDocument.

What is the difference between XDocument and XmlDocument?

XDocument is from the LINQ to XML API, and XmlDocument is the standard DOM-style API for XML. If you know DOM well, and don't want to learn LINQ to XML, go with XmlDocument . If you're new to both, check out this page that compares the two, and pick which one you like the looks of better.

What is an XElement?

The XElement class is one of the fundamental classes in LINQ to XML. It represents an XML element. The following list shows what you can use this class for: Create elements. Change the content of the element.


2 Answers

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

 XDocument doc = XDocument.Load(...);
 return doc.Root;
like image 89
Bobson Avatar answered Oct 02 '22 10:10

Bobson


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

like image 34
Pawel Avatar answered Oct 02 '22 09:10

Pawel