XDocument 或 XmlDocument

发布于 2024-08-07 00:18:53 字数 348 浏览 1 评论 0原文

我现在正在学习 XmlDocument 但我刚刚遇到 XDocument< /code>当我尝试搜索它们的区别或优点时,我找不到有用的东西,您能告诉我为什么您会使用其中一个而不是另一个吗?

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 ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

失退 2024-08-14 00:18:53

如果您使用的是 .NET 3.0 或更低版本,则必须使用 XmlDocument 也称为经典 DOM API。同样,您会发现还有一些其他 API 也需要这样做。

不过,如果您可以选择,我强烈建议您使用 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);

命名

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

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

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

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
    ));

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

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

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

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

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:

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:

// 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.

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.

屋檐 2024-08-14 00:18:53

令我惊讶的是,到目前为止,没有一个答案提到 XmlDocument 不提供行信息,而 XDocument 提供 (通过 IXmlLineInfo 接口)。

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

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).

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.

新雨望断虹 2024-08-14 00:18:53

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

XDocument 为 .NET 3.5 中的 LINQ to XML 功能提供支持。它大量使用了 IEnumerable,并且可以更轻松地直接在 C# 中使用。

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

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.

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#.

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

花伊自在美 2024-08-14 00:18:53

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

对于 xslxpath 顽固分子来说,值得一提的是,仍然可以在 Linq 2 Xml 上执行任意 xpath 1.0 表达式< code>XNodes 通过包含:

using System.Xml.XPath;

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

例如,给定 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>

我们可以评估:

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)");

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.

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:

using System.Xml.XPath;

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

For instance, given the Xml document:

<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)");
阳光的暖冬 2024-08-14 00:18:53

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

我刚刚开始使用 LINQ to XML,并且我喜欢使用函数式构造创建 XML 文档的方式。真的很好。相比之下,DOM 就显得笨拙了。

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.

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.

零時差 2024-08-14 00:18:53

另请注意,Xbox 360 和 Windows Phone OS 7.0 支持 XDocument
如果您的目标是它们,请针对 XDocument 进行开发或从 XmlDocument 迁移。

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.

疑心病 2024-08-14 00:18:53

我相信 XDocument 进行了更多的对象创建调用。我怀疑当您处理大量 XML 文档时,XMLDocument 会更快。

发生这种情况的一个地方是管理扫描数据。许多扫描工具以 XML 格式输出数据(出于显而易见的原因)。如果您必须处理大量此类扫描文件,我认为使用 XMLDocument 可以获得更好的性能。

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.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文