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

在C#中使用LINQ to XML可以非常方便地动态创建和修改XML文档。通过XDocument、XElement、XAttribute等类,你可以以声明式的方式构建、查询和更新XML结构,代码简洁且易于维护。
使用XDocument和XElement可以从零开始构建一个完整的XML文档。
<?xml version="1.0" encoding="utf-8"?>)示例:创建一个表示书籍信息的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,然后通过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#对象一样自然,适合配置文件、数据交换等场景。不复杂但容易忽略的是命名空间和空值判断,实际使用中要注意健壮性处理。
以上就是C# LINQ to XML动态创建和修改xml的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号