c#如何读写xml文件 c#操作xml节点的实例

C#中操作XML常用XmlDocument和XDocument。1. XmlDocument采用DOM模型,适合复杂结构:可创建声明、元素、属性,通过Load/S*e读写文件,SelectNodes查询节点,修改后保存。2. XDocument基于LINQ to XML,语法简洁:使用XElement构建层次结构,Descendants查找元素,Add添加节点,推荐新项目使用。两者均可实现XML的增删改查,XDocument更现代清晰。

c#如何读写xml文件 c#操作xml节点的实例

在C#中读写XML文件非常常见,通常使用System.Xml命名空间下的类来操作。最常用的是XmlDocumentXDocument(LINQ to XML)。下面通过实例演示如何创建、读取、修改和保存XML文件。

使用XmlDocument读写XML文件

XmlDocument是传统的DOM方式操作XML,适合处理结构较复杂的文档。

百度文心百中 百度文心百中

百度大模型语义搜索体验中心

百度文心百中 263 查看详情 百度文心百中 // 示例:创建并保存一个XML文件

var doc = new XmlDocument();
var declaration = doc.CreateXmlDeclaration("1.0", "utf-8", null);
doc.AppendChild(declaration);

var root = doc.CreateElement("Users");
doc.AppendChild(root);

var user = doc.CreateElement("User");
user.SetAttribute("Id", "1");

var name = doc.CreateElement("Name");
name.InnerText = "张三";
user.AppendChild(name);

var age = doc.CreateElement("Age");
age.InnerText = "25";
user.AppendChild(age);

root.AppendChild(user);
doc.S*e("users.xml"); // 保存到文件

// 示例:读取XML文件

var doc = new XmlDocument();
doc.Load("users.xml"); // 从文件加载

var users = doc.SelectNodes("//User");
foreach (XmlNode node in users)
{
   var id = node.Attributes["Id"]?.Value;
   var name = node["Name"]?.InnerText;
   var age = node["Age"]?.InnerText;
   Console.WriteLine($"ID: {id}, 姓名: {name}, 年龄: {age}");
}

// 示例:修改XML节点

var doc = new XmlDocument();
doc.Load("users.xml");

var userNode = doc.SelectSingleNode("//User[@Id='1']");
if (userNode != null)
{
   userNode["Name"].InnerText = "李四";
   doc.S*e("users.xml");
}

使用XDocument(LINQ to XML)操作XML

XDocument是LINQ to XML的一部分,语法更简洁,推荐用于新项目。

// 示例:创建并保存XML

var doc = new XDocument(
   new XElement("Users",
      new XElement("User",
         new XAttribute("Id", "1"),
         new XElement("Name", "王五"),
         new XElement("Age", "30")
      )
   )
);
doc.S*e("users_linq.xml");

// 示例:读取XML

var doc = XDocument.Load("users_linq.xml");
var users = doc.Descendants("User");
foreach (var user in users)
{
   var id = user.Attribute("Id")?.Value;
   var name = user.Element("Name")?.Value;
   var age = user.Element("Age")?.Value;
   Console.WriteLine($"ID: {id}, 姓名: {name}, 年龄: {age}");
}

// 示例:添加新节点

var doc = XDocument.Load("users_linq.xml");
doc.Root?.Add(
   new XElement("User",
      new XAttribute("Id", "2"),
      new XElement("Name", "赵六"),
      new XElement("Age", "28")
   )
);
doc.S*e("users_linq.xml");

常见操作总结

  • 创建元素:使用 CreateElement 或 new XElement
  • 设置属性:SetAttribute 或 new XAttribute
  • 查找节点:SelectSingleNode / SelectNodes 或 Descendants()
  • 修改内容:直接赋值 InnerText 或 Value
  • 保存文件:S*e() 方法
基本上就这些。两种方式都能有效操作XML,选择哪个取决于项目需求和个人偏好。XDocument 更现代,代码更清晰。

以上就是c#如何读写xml文件 c#操作xml节点的实例的详细内容,更多请关注其它相关文章!

本文转自网络,如有侵权请联系客服删除。