using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//引用XML命名空间
using System.Xml;
namespace XML文件读写操作
{
public class WriteReadXML
{
public void WriteXml()
{
//首先,创建xml文档
//1、实例化一个xmlDocument类
XmlDocument xDoc = new XmlDocument();
//创建一个声明xml文档所需要的语法的变量
XmlDeclaration declaration = xDoc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
//添加指定字符到xml文档的末尾
xDoc.AppendChild(declaration);
//一个xml文档创建时,必须要有一个根元素
//创建根节点students
XmlElement xe = xDoc.CreateElement("students");
//把根节点添加到文档中去
xDoc.AppendChild(xe);
//生成一个随机数
Random rd = new Random();
for (int i = 0; i < 10; i++)
{
//添加子节点
XmlElement xe1 = xDoc.CreateElement("student");
//将子节点添加到根节点
xe.AppendChild(xe1);
//给节点添加属性
xe1.SetAttribute("姓名", "张三");
xe1.SetAttribute("ID", i.ToString());
XmlElement xe1_1 = xDoc.CreateElement("语文成绩");
//将子节点添加到根节点
xe1.AppendChild(xe1_1);
//添加节点中的数据
xe1_1.InnerText = rd.Next(80, 120).ToString();
XmlElement xe1_2 = xDoc.CreateElement("数学成绩");
//将子节点添加到根节点
xe1.AppendChild(xe1_2);
//添加节点中的数据
xe1_2.InnerText = rd.Next(80, 120).ToString();
XmlElement xe1_3 = xDoc.CreateElement("英语成绩");
//将子节点添加到根节点
xe1.AppendChild(xe1_3);
//添加节点中的数据
xe1_3.InnerText = rd.Next(80, 120).ToString();
}
//保存生成或修改过的xml文件
xDoc.Save("students.xml");
}
//读取Xml文档
public void ReadXml()
{
//1、实例化一个xmlDocument类
XmlDocument xDoc = new XmlDocument();
xDoc.Load("students.xml");
//获取根节点
XmlNode xNode = xDoc.SelectSingleNode("students");
XmlNodeList xNodeList = xNode.ChildNodes;
foreach (XmlNode item in xNodeList)
{
//类型显示转换
XmlElement xe = (XmlElement)item;
string name = xe.GetAttribute("ID");
Console.WriteLine(name);
//获取子节点的所有节点
XmlNodeList xnList = item.ChildNodes;
foreach (XmlNode items in xnList)
{
XmlElement xe1 = (XmlElement)items;
string name1 = xe1.Name;
string count = xe1.InnerText;
Console.WriteLine(name1+":"+ count);
}
}
//保存生成或修改过的xml文件
xDoc.Save("students.xml");
Console.ReadKey();
}
}
}
© 版权声明
文章版权归本站所有,未经允许请勿转载。
THE END
暂无评论内容