C# XDocument 到 XElement

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13460461/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:39:21  来源:igfitidea点击:

XDocument to XElement

c#xmllinq-to-xmlxelement

提问by StackOverflowVeryHelpful

How do you convert an XDocument to an XElement?

如何将 XDocument 转换为 XElement?

I found the following by searching, but it's for converting between XDocument and XmlDocument, not XDocument and XElement.

我通过搜索找到了以下内容,但它用于在 XDocument 和 XmlDocument 之间转换,而不是 XDocument 和 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.

我找不到任何将 XDocument 转换为 XElement 的东西。任何帮助,将不胜感激。

采纳答案by Pawel

XDocument to XmlDocument:

XDocument 到 XmlDocument:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xdoc.CreateReader());

XmlDocument to XDocument

XmlDocument 到 XDocument

XDocument xDoc = XDocument.Load(new XmlNodeReader(xmlDoc));

To get the root element from the XDocument you use xDoc.Root

从您使用的 XDocument 中获取根元素 xDoc.Root

回答by Bobson

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

其他人已经说过了,但这里有一个明确的将 XDocument 转换为 XElement 的示例:

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

回答by Steve Hendren

Simple conversion from XDocument to XElement

从 XDocument 到 XElement 的简单转换

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