如果您使用 .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 支持延迟输出)。 XmlReader 和 XmlWriter 是 .NET 中流式传输 XML 的常规方式,但您可以在一定程度上混合使用所有 API。例如,您可以通过将XmlReader 定位在元素的开头,从中读取XElement 并对其进行处理,然后移动到下一个元素等来流式传输大型文档,但使用 LINQ to XML。关于这项技术的博文,here's one I found with a quick search。