使用LINQ to XML可通过XDocument和XElement动态创建、修改XML,支持添加、删除节点及处理命名空间,代码简洁且易于维护。

在C#中使用LINQ to XML可以非常方便地动态创建和修改XML文档。通过XDocument、XElement、XAttribute等类,你可以以声明式的方式构建、查询和更新XML结构,代码简洁且易于维护。
动态创建XML文档
使用XDocument和XElement可以从零开始构建一个完整的XML文档。
- 创建根元素,并添加子元素和属性
- 支持嵌套结构,直接用构造函数或链式调用添加内容
- 可选是否包含XML声明(如
)
示例:创建一个表示书籍信息的XML
XDocument doc = new XDocument(
new XElement("Books",
new XElement("Book",
new XAttribute("Id", "1"),
new XElement("Title", "C#入门详解"),
new XElement("Author", "张三"),
new XElement("Price", 69.8)
),
new XElement("Book",
new XAttribute("Id", "2"),
new XElement("Title", "LINQ编程指南"),
new XElement("Author", "李四"),
new XElement("Price", 59.9)
)
)
);
doc.Save("books.xml");
Console.WriteLine(doc.ToString());
加载并修改现有XML
你可以从文件或字符串加载XML,然后通过LINQ查询找到需要修改的节点并进行更新。
- 使用
XDocument.Load()读取文件 - 利用
Descendants()、Elements()等方法查找节点 - 直接设置
.Value或调用.Add()、.Remove()来修改内容
示例:修改某本书的价格
XDocument doc = XDocument.Load("books.xml");
var book = doc.Descendants("Book")
.FirstOrDefault(b => b.Attribute("Id")?.Value == "1");
if (book != null)
{
book.Element("Price").Value = "75.0";
}
doc.Save("books.xml");
动态添加和删除节点
在运行时根据条件插入新元素或移除旧数据也很常见。
添加一本新书:
doc.Root.Add(
new XElement("Book",
new XAttribute("Id", "3"),
new XElement("Title", "ASP.NET实战"),
new XElement("Author", "王五"),
new XElement("Price", 88.0)
)
);
删除某本书:
var bookToRemove = doc.Descendants("Book")
.FirstOrDefault(b => b.Element("Author")?.Value == "李四");
bookToRemove?.Remove();
处理命名空间
如果XML使用了命名空间,需在创建和查询时保持一致。
XNamespace ns = "http://example.com/books";
XDocument docWithNs = new XDocument(
new XElement(ns + "Books",
new XElement(ns + "Book",
new XAttribute("Id", "1"),
new XElement(ns + "Title", "带命名空间的书")
)
)
);
查询时也必须使用相同的命名空间前缀。
基本上就这些。LINQ to XML让操作XML变得像写C#对象一样自然,适合配置文件、数据交换等场景。不复杂但容易忽略的是命名空间和空值判断,实际使用中要注意健壮性处理。










