Create an XML document
First reference System.Xml
namespace
One example 1. Initialization
XmlDocument xd = new XmlDocument();
2. Create XML declaration header file
XmlDeclaration xdt = xd.CreateXmlDeclaration("1.0", "utf-8", null);
xd.AppendChild(xdt);
3. Create a unique root
XmlElement Students = xd.CreateElement("Students");
4. add attributes to the root node (may not be added)
Students.SetAttribute("name", "学生信息");
5. The root node is added to the XML file
xd.AppendChild(Students);
6. Create two nodes
XmlElement student = xd.CreateElement("student");
student.SetAttribute("stuNum", "100100100");
Students.AppendChild(student);
7. padding value to the secondary node
XmlElement name = xd.CreateElement("name");
name.InnerText = "小明";
XmlElement sex = xd.CreateElement("sex");
sex.InnerText = "男";
student.AppendChild(name);
student.AppendChild(sex);
8. Save
xd.Save("StuMS.xml");
9. results
<?xml version="1.0" encoding="utf-8"?>
<Students name="学生信息">
<student stuNum="100100100">
<name>小明</name>
<sex>男</sex>
</student>
</Students>
Read the information in an XML document
First you have to load an XML document
XmlDocument xd = new XmlDocument();
xd.Load("StuMS.xml");
1. read using the index
//查找标签值
string Name = stuNode.ChildNodes[0].InnerText;
//查找标签属性
string StuNum = stuNode.Attributes[0].Value;
2. Using Xpath query
// 常用查询方式
//1. "根节点/父节点/子节点"
//2. "//节点"
//3. "根节点/父节点[@父节点属性 = 'value' ]"
//4. "根节点/父节点[子节点 = 'value' ]"
XmlNode stuNode = xd.SelectSingleNode("Students/student[@stuNum =" + stuNum + "]");//可以获得指定stuNum的一个节点
XmlNodeList stuNodeList = xd.SelectNodes("Students/student[sex = '男' ]");//可以获得指定性别的集合
Modify the information in an XML document
Found -> Edit -> Save
//节点信息修改
stuNode.SelectSingleNode("name").InnerText = value;
stuNode.SelectSingleNode("name").InnerXml = value;
//属性信息修改
student.Attributes["stuNum"].Value = value;
InnerText displays only content 小明 男
InnerXml will be displayed along with the label<name>小明</name><sex>男</sex>
Delete XML document information
//从当前节点获取父节点,从父节点删除当前节点
stuNode.ParentNode.RemoveChild(studentNode);
//从父节点直接删除子节点
stuNode.RemoveChild(studentNode)