XDocument 或 XmlDocument

2023-11-30

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


如果您使用 .NET 版本 3.0 或更低版本,则have to use XmlDocument又名经典 DOM API。同样,您会发现还有一些其他 API 也需要这样做。

但是,如果您可以选择,我强烈建议您使用XDocument又名 LINQ to XML。它是much创建文档并处理它们更简单。例如,它是以下之间的区别:

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

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

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支持延迟输出)。XmlReader and XmlWriter是在 .NET 中流式传输 XML 的常规方法,但您可以在某种程度上混合使用所有 API。例如,您可以流式传输大型文档,但通过定位一个文档来使用 LINQ to XMLXmlReader在元素的开头,读取XElement从中进行处理,然后继续处理下一个元素等。有各种关于此技术的博客文章,这是我通过快速搜索找到的一个.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

XDocument 或 XmlDocument 的相关文章

随机推荐