写
//创建xml文档
public void WriteXml()
{
//实例化一个XmlDocument对象
XmlDocument xDoc = new XmlDocument();
//创建一个声明xml文档所需要的语法的变量
XmlDeclaration declaration = xDoc.CreateXmlDeclaration("1.0", "utf-8", "yes");
//添加声明
xDoc.AppendChild(declaration);
//一个xml文档必须要有一个根元素,创建根节点students
XmlElement elem = xDoc.CreateElement("students");
//添加根节点
xDoc.AppendChild(elem);
//创建子节点
XmlElement elem1 = xDoc.CreateElement("student");
//添加节点
elem.AppendChild(elem1);
//给节点添加属性
elem1.SetAttribute("name", "张三");
elem1.SetAttribute("num", "14");
//创建子节点的子节点
XmlElement elem1_1 = xDoc.CreateElement("语文成绩");
//添加节点
elem1.AppendChild(elem1_1);
//增加节点中的数据
elem1_1.InnerText = "90";
//保存
xDoc.Save("students.xml");
}
读
public void WriteXml()
{
//实例化一个XmlDocument对象
XmlDocument xDoc = new XmlDocument();
//加载xml文档
xDoc.Load("students");
//获取根节点students
XmlNode node = xDoc.SelectSingleNode("students");
//获取根节点集合
XmlNodeList nodeList = node.ChildNodes;
foreach(XmlNode node in nodeList)
{
string name = node.Name;
Console.WriteLine(name);
//类型转换
XmlElement elem = (XmlElement)node;
string name = elem.GetAttribute("name");
string age = elem.GetAttribute("age");
Console.WriteLine(name + ":" + age);
XmlNodeList childList = node.ChildNodes;
foreach(XmlNode xn in childList)
{
//类型转换
XmlElement xe = (XmlElement)xn;
string className = xe.Name;
string score = xe.InnerText;
Console.WriteLine(className + ":" + score);
}
}
//生成或者修改xml文档的时候,末尾一定要写save方法
xDoc.Save("students.xml");
}
网友评论