摘抄:https://www.cnblogs.com/xing2/archive/2022/02/10/15879108.html
xpath表达式:https://www.runoob.com/xpath/xpath-syntax.html
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//引用命名空间
using System.Xml;
namespace 读写xml
{
public class RWXml
{
/// <summary>
/// 生成一个XML文档
/// </summary>
public void WriteXml()
{
Random rd = new Random();
//首先创建XML文档
/*1、实例化一个XmlDocument类*/
XmlDocument xDoc = new XmlDocument();
//创建XML声明
XmlDeclaration declaration = xDoc.CreateXmlDeclaration("1.0", "UTF-8", "yes");//版本号,编码格式,返回值是一个声明
//将指定的节点添加到该节点的子节点的列表的末尾,此处是添加声明
xDoc.AppendChild(declaration);
//一个XML文档,至少得有一个根元素
//创建根节点,返回值是一个元素
XmlElement elem = xDoc.CreateElement("students");//创建具有指定名称的元素
xDoc.AppendChild(elem);//添加根节点
for (int i = 1; i < 10; i++)
{
//添加子节点到根节点里面
XmlElement elem1 = xDoc.CreateElement("student");//创建子节点
elem.AppendChild(elem1);//将第一级的子节点添加到根节点后面
添加子节点的节点
//XmlElement elsm1_1 = xDoc.CreateElement("name");
//elem1.AppendChild(elsm1_1);
//给节点添加属性
elem1.SetAttribute("姓名", "张三");//设置具有指定名称的属性的值,属性名称,属性值
elem1.SetAttribute("学号", i.ToString());
//添加子节点的节点
XmlElement elem1_1 = xDoc.CreateElement("语文成绩");
elem1.AppendChild(elem1_1);
elem1_1.InnerText = rd.Next(40, 120).ToString();
XmlElement elem1_2 = xDoc.CreateElement("数学成绩");
elem1.AppendChild(elem1_2);
elem1_2.InnerText = rd.Next(40, 120).ToString();
XmlElement elem1_3 = xDoc.CreateElement("英语成绩");
elem1.AppendChild(elem1_3);
elem1_3.InnerText = rd.Next(40, 120).ToString();
}
xDoc.Save("students.xml");
}
/// <summary>
/// 读取XML文档
/// </summary>
public void ReadXml()
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load("students.xml");
//获取到根节点
XmlNode rootNode = xDoc.SelectSingleNode("students");
XmlNodeList nodeList = rootNode.ChildNodes;//获取节点的所有子节点
foreach (XmlNode no in nodeList)
{
//类型显示转换
XmlElement elem = (XmlElement)no;//将节点转换为元素,方便后面获取属性
string name = elem.GetAttribute("姓名");
string number = elem.GetAttribute("学号");
//输出名字和学号信息
Console.WriteLine("姓名:" + name + " 学号:" + number);
//获取子节点的所有节点
XmlNodeList childList = elem.ChildNodes;
foreach (XmlNode child in childList)
{
XmlElement childElem = (XmlElement)child;//节点转换为元素
string className = childElem.Name;//获取节点的名称
string score = childElem.InnerText;//获取节点的值
Console.WriteLine(className + ":" + score);
//修改指定学号的学生的指定科目成绩
if (number == "3")
{
if (childElem.Name == "语文成绩")
{
childElem.InnerText = "120";
}
if (childElem.Name == "数学成绩")
{
childElem.InnerText = "120";
}
}
}
}
xDoc.Save("students.xml");
Console.ReadLine();
}
}
}