LINQ to XML更推荐用于新项目,因其语法简洁、性能好且支持LINQ查询;XmlDocument适合老系统维护,遵循DOM模型,控制精细。两者选择取决于项目需求:现代开发优选LINQ to XML,传统场景可选XmlDocument。

在C#中操作XML文件是开发中常见的需求,比如读取配置、交换数据或生成报告。.NET提供了多种方式处理XML,其中LINQ to XML和XmlDocument是最常用的两种。它们各有特点,适用于不同场景。
LINQ to XML:现代、简洁的XML操作方式
LINQ to XML 是 .NET 3.5 引入的轻量级API,基于LINQ语法,使用更直观,代码更简洁。它适合大多数现代开发场景。
常用类:
-
XElement:表示XML元素,最常用。
-
XDocument:表示整个XML文档,包含声明、注释等。
- XAttribute:表示属性。
创建XML文件
使用XElement可以快速构建XML结构:
XElement root = new XElement("Books",
new XElement("Book",
new XAttribute("Id", "1"),
new XElement("Title", "C#入门详解"),
new XElement("Author", "张三")
),
new XElement("Book",
new XAttribute("Id", "2"),
new XElement("Title", "深入理解LINQ"),
new XElement("Author", "李四")
)
);
root.Save("books.xml");
读取XML文件
加载XML后,可使用LINQ查询提取数据:
XElement doc = XElement.Load("books.xml");
var books = from b in doc.Elements("Book")
select new
{
Id = b.Attribute("Id")?.Value,
Title = b.Element("Title")?.Value,
Author = b.Element("Author")?.Value
};
foreach (var book in books)
{
Console.WriteLine($"{book.Id}: {book.Title} by {book.Author}");
}
修改XML
可以直接修改节点内容或属性:
XElement doc = XElement.Load("books.xml");
XElement firstBook = doc.Element("Book");
firstBook.Element("Title").Value = "C#高级编程";
firstBook.SetAttributeValue("Id", "101");
doc.Save("books.xml");
删除节点
XElement doc = XElement.Load("books.xml");
doc.Element("Book")?.Remove();
doc.Save("books.xml");
XmlDocument:传统的DOM式操作
XmlDocument 是基于W3C DOM标准的老式方法,适合需要兼容旧项目或复杂节点操作的场景。它以树形结构加载整个文档,操作较繁琐但控制精细。
常用对象:
-
XmlDocument:整个文档对象。
-
XmlNode / XmlElement:节点与元素。
- XmlAttribute:属性节点。
加载并遍历XML
XmlDocument doc = new XmlDocument();
doc.Load("books.xml");
XmlNode root = doc.DocumentElement;
foreach (XmlNode node in root.ChildNodes)
{
if (node.Name == "Book")
{
string id = node.Attributes["Id"]?.Value;
string title = node["Title"]?.InnerText;
string author = node["Author"]?.InnerText;
Console.WriteLine($"{id}: {title} by {author}");
}
}
创建新节点
XmlDocument doc = new XmlDocument();
doc.Load("books.xml");
XmlElement newBook = doc.CreateElement("Book");
newBook.SetAttribute("Id", "3");
XmlElement title = doc.CreateElement("Title");
title.InnerText = "ASP.NET Core实战";
newBook.AppendChild(title);
XmlElement author = doc.CreateElement("Author");
author.InnerText = "王五";
newBook.AppendChild(author);
doc.DocumentElement.AppendChild(newBook);
doc.Save("books.xml");
修改和删除节点
// 修改 XmlNode firstBook = doc.DocumentElement.FirstChild; firstBook["Title"].InnerText = "更新后的书名";// 删除 doc.DocumentElement.RemoveChild(firstBook); doc.Save("books.xml");
LINQ to XML vs XmlDocument:如何选择?
两者都能完成XML操作,关键看项目需求:
- LINQ to XML 更推荐:语法简洁,支持LINQ查询,性能好,适合新项目。
- XmlDocument 更传统:适合维护老系统,或需要严格遵循DOM模型的场景。
- 内存占用:LINQ to XML 通常更轻量。
- 学习成本:LINQ to XML 更易上手,尤其是熟悉LINQ的开发者。
实用建议
处理XML时注意以下几点:
- 始终检查节点是否存在,避免NullReferenceException。
- 大文件考虑使用 XmlReader/XmlWriter 流式处理,避免内存溢出。
- 保存时指定编码:
new XmlWriterSettings { Encoding = Encoding.UTF8 }。 - 使用XElement时,命名空间可通过XNamespace处理。
基本上就这些。LINQ to XML 简洁高效,XmlDocument 兼容性强,根据项目情况选择即可。掌握两者,应对各种XML场景都不成问题。











