在C#中处理XML数据,LINQ to XML提供了一套基于内存对象模型的API,比早期的XmlDocument更简洁。它把XML元素映射为XElement,属性映射为XAttribute,配合标准查询运算符就能完成复杂的数据提取与变更。

加载与基本查询
使用XDocument.Load或XDocument.Parse可将XML读入内存。之后通过Descendants方法获取指定名称的所有子代元素,并结合Where进行条件过滤。
using System;
using System.Linq;
using System.Xml.Linq;
class Demo
{
static void Main()
{
string xml = @"<root>
<user id="1">Alice</user>
<user id="2">Bob</user>
</root>";
XDocument doc = XDocument.Parse(xml);
// 查询id为2的用户名
var name = doc.Descendants("user")
.Where(u => (string)u.Attribute("id") == "2")
.Select(u => u.Value)
.FirstOrDefault();
Console.WriteLine(name);
}
}
创建与修改XML
构造XML时可以直接使用函数式语法,把元素和属性嵌套写入。修改已有节点则通过SetValue或ReplaceWith完成。
using System;
using System.Xml.Linq;
class BuildDemo
{
static void Main()
{
XElement root = new XElement("root",
new XElement("item", new XAttribute("price", 10), "Apple"),
new XElement("item", new XAttribute("price", 20), "Banana")
);
// 修改第一个item的价格
root.Elements("item").First().Attribute("price").SetValue(15);
Console.WriteLine(root);
}
}
常见操作对照
| 需求 | LINQ to XML写法 |
|---|---|
| 查找所有子元素 | doc.Descendants("name") |
| 按属性过滤 | Where(e => (int)e.Attribute("id") == 1) |
| 删除节点 | element.Remove() |
| 新增子节点 | parent.Add(new XElement("child")) |
注意事项
- 命名空间需要使用XNamespace,不能直接写带前缀的字符串。
- 频繁读写大文件时,可考虑XmlReader配合LINQ以提高性能。
- 代码中写<input>这类标签名仅表示说明,并非调用DOM方法。
LINQ to XML的优势在于把查询与构造统一到C#语法中,避免拼接XPath字符串带来的低级错误。
C#LINQ_to_XMLXML操作修改时间:2026-07-31 11:03:16