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
XDocument or XmlDocument
提问by Tarik
I am now learning XmlDocument
but I've just ran into XDocument
and 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 XmlDocument
aka 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 XDocument
aka LINQ to XML. It's muchsimpler to create documents and process them. For example, it's the difference between:
但是,如果您可以选择,我强烈建议您使用XDocument
LINQ 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 XStreamingElement
supports lazy output). XmlReader
and XmlWriter
are 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 XmlReader
at the start of an element, reading an XElement
from 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
支持延迟输出)。XmlReader
和XmlWriter
是在 .NET 中流式传输 XML 的正常方式,但您可以在一定程度上混合所有 API。例如,您可以流式传输一个大文档,但使用 LINQ to XML,方法是将 an 定位XmlReader
在元素的开头,XElement
从中读取 an并处理它,然后移动到下一个元素等。有很多关于这种技术的博客文章,这是我通过快速搜索找到的一个。
回答by Daniel Chambers
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 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
XmlDocument
is 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 XPath
node selection.
XmlDocument
非常适合熟悉 XML DOM 对象模型的开发人员。它已经存在了一段时间,或多或少地对应于 W3C 标准。它支持手动导航以及XPath
节点选择。
XDocument
powers 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 XmlReader
for example).
两种文档模型都要求您将整个文档加载到内存中(与XmlReader
示例不同)。
回答by w0land
Also, note that XDocument
is supported in Xbox 360 and Windows Phone OS 7.0.
If you target them, develop for XDocument
or migrate from XmlDocument
.
另请注意,XDocument
Xbox 360 和 Windows Phone OS 7.0 支持此功能。如果他们的目标,制定XDocument
或迁移XmlDocument
。
回答by Brian
I believe that XDocument
makes a lot more object creation calls. I suspect that for when you're handling a lot of XML documents, XMLDocument
will 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 XmlDocument
provides no line information, while XDocument
does(through the IXmlLineInfo
interface).
我的答案都不感到惊讶到目前为止提到的事实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 xsl
and xpath
die hards to note is that it IS possible to still execute arbitrary xpath 1.0
expressions on Linq 2 Xml XNodes
by including:
值得一提xsl
并且xpath
很难注意到的一件事是,仍然可以通过包括以下内容xpath 1.0
在 Linq 2 Xml 上执行任意表达式XNodes
:
using System.Xml.XPath;
and then we can navigate and project data using xpath
via these extension methods:
然后我们可以xpath
通过这些扩展方法导航和投影数据:
- XPathSelectElement- Single Element
- XPathSelectElements- Node Set
- XPathEvaluate- Scalars and others
- XPathSelectElement- 单个元素
- XPathSelectElements- 节点集
- XPathEvaluate- 标量和其他
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)");