XDocument或XmlDocument

19 浏览
0 Comments

XDocument或XmlDocument

我现在正在学习XmlDocument,但我刚刚遇到了XDocument,当我尝试搜索它们的区别或优点时,我找不到有用的东西,请问您为什么会优先使用一个而不是另一个呢?

admin 更改状态以发布 2023年5月20日
0
0 Comments

我很惊讶到目前为止,没有一个答案提到 XmlDocument 不提供行信息,而 XDocument 做到了 (通过 IXmlLineInfo 接口)。在某些情况下,这可能是一个关键特性(例如,如果您想在 XML 中报告错误或者一般追踪元素定义的位置),在您开心地开始使用 XmlDocument 实现之前,最好您要知道这一点,以免后来发现你不得不全部更改。

0
0 Comments

如果您正在使用.NET 3.0或更低版本,则必须使用XmlDocument(也称为经典DOM API)。同样,您会发现有一些其他的API会希望使用它。

然而,如果您有选择的话,我强烈推荐使用XDocument(即LINQ到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到XML中,命名空间处理非常简单,不像其他我见过的XML API:

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

LINQ到XML还可以很好地运用LINQ——构建模型允许您轻松地为子元素序列构建元素:

// Customers is a List
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支持惰性输出)。XmlReader和XmlWriter是.NET中流式传输XML的常规方法,但您可以在一定程度上混合使用所有API。例如,您可以在流式传输大型文档的同时,通过将XmlReader定位到元素的开头,从它读取XElement并处理它,然后继续移动到下一个元素等等,使用LINQ到XML。关于这种技术有各种博客文章,这里是我通过快速搜索找到的一个

0