如果您使用 .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
从中进行处理,然后继续处理下一个元素等。有各种关于此技术的博客文章,这是我通过快速搜索找到的一个.