C#如何操作XML文件 C#使用XmlDocument和LINQ to XML解析XML

来源:这里教程网 时间:2026-02-21 17:30:19 作者:

在C#中操作XML文件是常见的需求,尤其是在处理配置文件、数据交换或Web服务时。.NET 提供了多种方式来读取、修改和创建 XML 文件,其中 XmlDocumentLINQ to XML 是两种最常用的方法。下面分别介绍它们的使用方式和适用场景。

使用 XmlDocument 操作 XML

XmlDocument 是基于 DOM(文档对象模型)的类,它会将整个 XML 文档加载到内存中,形成树形结构,适合对 XML 进行频繁的增删改查操作。

示例:读取并遍历 XML 节点

假设有一个 XML 文件 books.xml

<Books>
  <Book Id="1">
    <Title>C# 入门经典</Title>
    <Author>John Doe</Author>
  </Book>
  <Book Id="2">
    <Title>深入理解 C#</Title>
    <Author>Jane Smith</Author>
  </Book>
</Books>

使用 XmlDocument 加载并读取内容:

XmlDocument doc = new XmlDocument();
doc.Load("books.xml"); // 或 LoadXml(string xml)
<p>XmlNodeList bookNodes = doc.SelectNodes("//Book");
foreach (XmlNode node in bookNodes)
{
string id = node.Attributes["Id"]?.Value;
string title = node["Title"]?.InnerText;
string author = node["Author"]?.InnerText;</p><pre class='brush:php;toolbar:false;'>Console.WriteLine($"ID: {id}, Title: {title}, Author: {author}");

}

修改 XML 示例

添加一个新节点:

XmlElement newBook = doc.CreateElement("Book");
newBook.SetAttribute("Id", "3");
<p>XmlElement titleElem = doc.CreateElement("Title");
titleElem.InnerText = "LINQ 实战";
newBook.AppendChild(titleElem);</p><p>XmlElement authorElem = doc.CreateElement("Author");
authorElem.InnerText = "Tom Lee";
newBook.AppendChild(authorElem);</p><p>doc.DocumentElement?.AppendChild(newBook);
doc.Save("books.xml"); // 保存更改</p>

使用 LINQ to XML 操作 XML

LINQ to XML 是一种更现代、更简洁的方式,它结合了 LINQ 的查询能力,语法更直观,适合函数式编程风格。

示例:加载并查询 XML

同样以上面的 books.xml 为例:

XDocument xDoc = XDocument.Load("books.xml");
<p>var books = from book in xDoc.Descendants("Book")
select new
{
Id = book.Attribute("Id")?.Value,
Title = book.Element("Title")?.Value,
Author = book.Element("Author")?.Value
};</p><p>foreach (var b in books)
{
Console.WriteLine($"ID: {b.Id}, Title: {b.Title}, Author: {b.Author}");
}</p>

创建 XML 示例

LINQ to XML 创建 XML 更加简洁:

XDocument newDoc = new XDocument(
    new XElement("Books",
        new XElement("Book", new XAttribute("Id", "1"),
            new XElement("Title", "C# 高级编程"),
            new XElement("Author", "Jeffrey Richter")
        ),
        new XElement("Book", new XAttribute("Id", "2"),
            new XElement("Title", "CLR via C#"),
            new XElement("Author", "Jeffrey Richter")
        )
    )
);
<p>newDoc.Save("new_books.xml");</p>

修改 XML 示例

更新某个节点的内容:

XDocument xDoc = XDocument.Load("books.xml");
var book = xDoc.Descendants("Book")
               .FirstOrDefault(b => b.Attribute("Id")?.Value == "1");
if (book != null)
{
    book.Element("Title")!.Value = "C# 精通之路";
}
<p>xDoc.Save("books.xml");</p>

XmlDocument 与 LINQ to XML 对比

XmlDocument:适合复杂操作、需要完整 DOM 树、兼容老项目;语法略显繁琐。 LINQ to XML:语法简洁、支持 LINQ 查询、创建和修改更直观;推荐用于新项目。

如果只是简单读取或生成 XML,优先选择 LINQ to XML。如果需要精确控制节点类型、命名空间或进行复杂的节点操作,XmlDocument 依然可靠。

基本上就这些。根据项目需求选择合适的方式,都能高效地完成 XML 操作任务。

相关推荐