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.
You can wrap the XmlDocument with an XmlNodeReader and feed it to XElement. Load(). The other direction is available as well using XElement. CreateReader().
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.
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.
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.
Other people have said it, but here's explicitly a sample to convert XDocument to XElement:
XDocument doc = XDocument.Load(...);
return doc.Root;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With