简体   繁体   中英

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.

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

Simple conversion from XDocument to XElement

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM