C# XDocument 或 XmlDocument

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1542073/
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-06 18:39:33  来源:igfitidea点击:

XDocument or XmlDocument

c#xmlxmldocumentlinq-to-xml

提问by Tarik

I am now learning XmlDocumentbut I've just ran into XDocumentand when I try to search the difference or benefits of them I can't find something useful, could you please tell me why you would use one over another ?

我现在正在学习,XmlDocument但我刚刚遇到了XDocument,当我尝试搜索它们的区别或好处时,我找不到有用的东西,你能告诉我为什么你会使用它们吗?

采纳答案by Jon Skeet

If you're using .NET version 3.0 or lower, you haveto use XmlDocumentaka the classic DOM API. Likewise you'll find there are some other APIs which will expect this.

如果您使用 .NET 3.0 或更低版本,必须使用XmlDocument又名经典 DOM API。同样,您会发现还有一些其他 API 会期待这一点。

If you get the choice, however, I would thoroughly recommend using XDocumentaka LINQ to XML. It's muchsimpler to create documents and process them. For example, it's the difference between:

但是,如果您可以选择,我强烈建议您使用XDocumentLINQ to XML。这是很多简单的创建文档并对其进行处理。例如,这是以下之间的区别:

XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("root");
root.SetAttribute("name", "value");
XmlElement child = doc.CreateElement("child");
child.InnerText = "text node";
root.AppendChild(child);
doc.AppendChild(root);

and

XDocument doc = new XDocument(
    new XElement("root",
                 new XAttribute("name", "value"),
                 new XElement("child", "text node")));

Namespaces are pretty easy to work with in LINQ to XML, unlike any other XML API I've ever seen:

命名空间在 LINQ to XML 中非常容易使用,这与我见过的任何其他 XML API 不同:

XNamespace ns = "http://somewhere.com";
XElement element = new XElement(ns + "elementName");
// etc

LINQ to XML also works really well with LINQ - its construction model allows you to build elements with sequences of sub-elements really easily:

LINQ to XML 也与 LINQ 配合得非常好 - 它的构造模型允许您非常轻松地构建具有子元素序列的元素:

// Customers is a List<Customer>
XElement customersElement = new XElement("customers",
    customers.Select(c => new XElement("customer",
        new XAttribute("name", c.Name),
        new XAttribute("lastSeen", c.LastOrder)
        new XElement("address",
            new XAttribute("town", c.Town),
            new XAttribute("firstline", c.Address1),
            // etc
    ));

It's all a lot more declarative, which fits in with the general LINQ style.

它更具声明性,符合一般的 LINQ 风格。

Now as Brannon mentioned, these are in-memory APIs rather than streaming ones (although XStreamingElementsupports lazy output). XmlReaderand XmlWriterare the normal ways of streaming XML in .NET, but you can mix all the APIs to some extent. For example, you can stream a large document but use LINQ to XML by positioning an XmlReaderat the start of an element, reading an XElementfrom it and processing it, then moving on to the next element etc. There are various blog posts about this technique, here's one I found with a quick search.

现在正如布兰农所提到的,这些是内存中的 API,而不是流式 API(虽然XStreamingElement支持延迟输出)。XmlReaderXmlWriter是在 .NET 中流式传输 XML 的正常方式,但您可以在一定程度上混合所有 API。例如,您可以流式传输一个大文档,但使用 LINQ to XML,方法是将 an 定位XmlReader在元素的开头,XElement从中读取 an并处理它,然后移动到下一个元素等。有很多关于这种技术的博客文章,这是我通过快速搜索找到的一个

回答by Daniel Chambers

XDocumentis from the LINQ to XML API, and XmlDocumentis 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 pagethat compares the two, and pick which one you like the looks of better.

XDocument来自 LINQ to XML API,XmlDocument是用于 XML 的标准 DOM 样式 API。如果您非常了解 DOM,并且不想学习 LINQ to XML,请使用XmlDocument. 如果您对两者都不熟悉,请查看比较两者的页面,然后选择您更喜欢哪个外观。

I've just started using LINQ to XML, and I love the way you create an XML document using functional construction. It's really nice. DOM is clunky in comparison.

我刚刚开始使用 LINQ to XML,我喜欢您使用函数式构造创建 XML 文档的方式。这太好了。DOM 比较笨重。

回答by Brannon

XmlDocumentis great for developers who are familiar with the XML DOM object model. It's been around for a while, and more or less corresponds to a W3C standard. It supports manual navigation as well as XPathnode selection.

XmlDocument非常适合熟悉 XML DOM 对象模型的开发人员。它已经存在了一段时间,或多或少地对应于 W3C 标准。它支持手动导航以及XPath节点选择。

XDocumentpowers the LINQ to XML feature in .NET 3.5. It makes heavy use of IEnumerable<>and can be easier to work with in straight C#.

XDocument支持 .NET 3.5 中的 LINQ to XML 功能。它IEnumerable<>在直接 C# 中大量使用并且可以更容易地使用。

Both document models require you to load the entire document into memory (unlike XmlReaderfor example).

两种文档模型都要求您将整个文档加载到内存中(与XmlReader示例不同)。

回答by w0land

Also, note that XDocumentis supported in Xbox 360 and Windows Phone OS 7.0. If you target them, develop for XDocumentor migrate from XmlDocument.

另请注意,XDocumentXbox 360 和 Windows Phone OS 7.0 支持此功能。如果他们的目标,制定XDocument或迁移XmlDocument

回答by Brian

I believe that XDocumentmakes a lot more object creation calls. I suspect that for when you're handling a lot of XML documents, XMLDocumentwill be faster.

我相信这XDocument会产生更多的对象创建调用。我怀疑当您处理大量 XML 文档时,XMLDocument速度会更快。

One place this happens is in managing scan data. Many scan tools output their data in XML (for obvious reasons). If you have to process a lot of these scan files, I think you'll have better performance with XMLDocument.

发生这种情况的一个地方是管理扫描数据。许多扫描工具以 XML 格式输出数据(原因很明显)。如果您必须处理大量这些扫描文件,我认为使用XMLDocument.

回答by Julien Guertault

I am surprised none of the answers so far mentions the fact that XmlDocumentprovides no line information, while XDocumentdoes(through the IXmlLineInfointerface).

我的答案都不感到惊讶到目前为止提到的事实XmlDocument没有提供行信息,而XDocument不会(通过IXmlLineInfo接口)。

This can be a critical feature in some cases (for example if you want to report errors in an XML, or keep track of where elements are defined in general) and you better be aware of this before you happily start to implement using XmlDocument, to later discover you have to change it all.

在某些情况下,这可能是一个关键功能(例如,如果您想报告 XML 中的错误,或者通常跟踪元素的定义位置),并且在您愉快地开始使用 using 之前,您最好意识到这一点XmlDocument,以后发现你必须改变这一切。

回答by StuartLC

As mentioned elsewhere, undoubtedly, Linq to Xml makes creation and alteration of xml documents a breeze in comparison to XmlDocument, and the XNamespace ns + "elementName"syntax makes for pleasurable reading when dealing with namespaces.

正如在别处提到的,毫无疑问,与 相比,Linq to Xml 使 xml 文档的创建和更改变得轻而易举XmlDocument,并且XNamespace ns + "elementName"在处理名称空间时,语法使阅读更加愉快。

One thing worth mentioning for xsland xpathdie hards to note is that it IS possible to still execute arbitrary xpath 1.0expressions on Linq 2 Xml XNodesby including:

值得一提xsl并且xpath很难注意到的一件事是,仍然可以通过包括以下内容xpath 1.0在 Linq 2 Xml 上执行任意表达式XNodes

using System.Xml.XPath;

and then we can navigate and project data using xpathvia these extension methods:

然后我们可以xpath通过这些扩展方法导航和投影数据:

For instance, given the Xml document:

例如,给定 Xml 文档:

<xml>
    <foo>
        <baz id="1">10</baz>
        <bar id="2" special="1">baa baa</bar>
        <baz id="3">20</baz>
        <bar id="4" />
        <bar id="5" />
    </foo>
    <foo id="123">Text 1<moo />Text 2
    </foo>
</xml>

We can evaluate:

我们可以评估:

var node = xele.XPathSelectElement("/xml/foo[@id='123']");
var nodes = xele.XPathSelectElements(
"//moo/ancestor::xml/descendant::baz[@id='1']/following-sibling::bar[not(@special='1')]");
var sum = xele.XPathEvaluate("sum(//foo[not(moo)]/baz)");