600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > C#学习——7.xml文件读写

C#学习——7.xml文件读写

时间:2019-04-13 00:32:18

相关推荐

C#学习——7.xml文件读写

一、程序介绍

1.界面设计
2.设计思路

点击写入xml按钮,将构造的数据信息写入指定的xml文件,然后点击读xml按钮将xml文件中的信息读取并循环加载显示到TreeView中。点击读取指定节点时,显示xml文件中name节点的个数。

3.构造数据信息:

//0.全校学生信息集合Dictionary<string, List<Student>> allstudengts = new Dictionary<string, List<Student>>();List<Student> class1List = new List<Student>();class1List.Add(new Student("张三", 16, "c101"));class1List.Add(new Student("李四", 23, "c102"));class1List.Add(new Student("王五", 31, "c103"));allstudengts.Add("c100", class1List);List<Student> class2List = new List<Student>();class2List.Add(new Student("李诞", 32, "c201"));class2List.Add(new Student("池子", 18, "c202"));class2List.Add(new Student("卡姆", 29, "c203"));allstudengts.Add("c200", class2List);

二、XmlDocument类

1、写方法

#region 1.【XmlDocument】方法写入xml文件//1.1实例化xml对象,并添加文档说明信息XmlDocument xml = new XmlDocument();XmlDeclaration xmldeclaration = xml.CreateXmlDeclaration("1.0", "utf-8", "yes");xml.AppendChild(xmldeclaration);//1.2根节点:学校XmlElement rootElement = xml.CreateElement("school");xml.AppendChild(rootElement);//依次写入各个班级学生信息foreach (var item in allstudengts){//1.3根节点的子节点:班级XmlElement classElement = xml.CreateElement("class");//创建属性XmlAttribute classAttribute = xml.CreateAttribute("id");classAttribute.Value = item.Key;classElement.Attributes.Append(classAttribute);rootElement.AppendChild(classElement);//依次该班级每名学生信息foreach (Student stu in item.Value){//1.4班级节点的子节点:学生XmlElement studentElement = xml.CreateElement("student");XmlAttribute studentAttribute = xml.CreateAttribute("sid");studentAttribute.Value = stu.SId;studentElement.Attributes.Append(studentAttribute);//1.5学生子节点:姓名、年龄XmlElement nameElement = xml.CreateElement("name");nameElement.InnerText = stu.Name;XmlElement ageElement = xml.CreateElement("age");ageElement.InnerText = stu.Age.ToString();//1.6依次插入节点到根节点classElement.AppendChild(studentElement);studentElement.AppendChild(nameElement);studentElement.AppendChild(ageElement);}}//2.写入文件(没有根节点不能写入)xml.Save("demo.xml");#endregion

2、读方法

#region 2.读取xml文件(XmlDocument)XmlDocument xmlDoc = new XmlDocument();xmlDoc.Load("demo2.xml");//获取根节点XmlElement rootElement = xmlDoc.DocumentElement;//将根节点加载到TreeView上TreeNode rootNode = treeView1.Nodes.Add(rootElement.Name);//递归加载LoadXmlByXmlDocument(rootElement, rootNode.Nodes);rootNode.Expand();#endregion

LoadXmlByXmlDocument()函数定义如下:

//读取xml文件(XmlDocument)private void LoadXmlByXmlDocument(XmlElement rootElement, TreeNodeCollection treeNodeCollection){//循环rootElement下的所有子元素(直接子元素)foreach (XmlNode item in rootElement.ChildNodes){if (item.NodeType == XmlNodeType.Element){TreeNode node = treeNodeCollection.Add(item.Name);LoadXmlByXmlDocument((XmlElement)item, node.Nodes);}else if (item.NodeType == XmlNodeType.Text || item.NodeType == XmlNodeType.CDATA){treeNodeCollection.Add(item.InnerText);}}}

三、XDocument类

1、写方法

//1.创建dom对象XDocument xDoc = new XDocument();XDeclaration xDec = new XDeclaration("1.0", "utf-8", null);xDoc.Declaration = xDec;//2.创建根节点XElement rootElement = new XElement("school");xDoc.Add(rootElement);//3.循环加载学生信息foreach (var item in allstudengts){//根节点的子节点:班级XElement classElement = new XElement("class");classElement.SetAttributeValue("cid", "c100");rootElement.Add(classElement);//依次该班级每名学生信息foreach (Student stu in item.Value){//1.4班级节点的子节点:学生XElement stuElement = new XElement("student");stuElement.SetAttributeValue("sid", stu.SId);classElement.Add(stuElement);//1.5学生子节点:姓名、年龄XElement nameElement = new XElement("name");nameElement.Value = stu.Name;stuElement.Add(nameElement);XElement ageElement = new XElement("age");ageElement.Value = stu.Age.ToString();stuElement.Add(ageElement);}}//4.保存到文本文件xDoc.Save("demo2.xml");

2、读方法

#region 1.读取xml文件(XDocument)XDocument xDoc = XDocument.Load("demo2.xml");//2.获取根节点XElement rootElement = xDoc.Root;//3.将根节点加载到TreeView上TreeNode rootNode = treeView1.Nodes.Add(rootElement.Name.ToString());//4.递归加载LoadXmlToTreeView(rootElement, rootNode.Nodes);#endregion

LoadXmlToTreeView()定义如下:

private void LoadXmlToTreeView(XElement rootElement, TreeNodeCollection treeNodeCollection){//获取根元素rootElement下的所有子元素(直接子元素)foreach (XElement item in rootElement.Elements()){if(item.Elements().Count()==0){TreeNode node = treeNodeCollection.Add(item.Name.ToString());node.Nodes.Add(item.Value.ToString());}else{TreeNode node = treeNodeCollection.Add(item.Name.ToString());LoadXmlToTreeView(item, node.Nodes);}}}

四、完整源代码

1.Student.cs

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace _2Xml读写操作{class Student{public Student(string name,int age,string sid){this.Name = name;this.Age = age;this.SId = sid;}public string Name{get;set;}public int Age{get;set;}public string SId{get;set;}}}

2.Form1.cs

using System;using System.Collections.Generic;using ponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;using System.Xml;using System.Xml.Linq;namespace _2Xml读写操作{public partial class Form1 : Form{public Form1(){InitializeComponent();}/// <summary>/// 写入xml文件/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void button2_Click(object sender, EventArgs e){//0.全校学生信息集合Dictionary<string, List<Student>> allstudengts = new Dictionary<string, List<Student>>();List<Student> class1List = new List<Student>();class1List.Add(new Student("张三", 16, "c101"));class1List.Add(new Student("李四", 23, "c102"));class1List.Add(new Student("王五", 31, "c103"));allstudengts.Add("c100", class1List);List<Student> class2List = new List<Student>();class2List.Add(new Student("李诞", 32, "c201"));class2List.Add(new Student("池子", 18, "c202"));class2List.Add(new Student("卡姆", 29, "c203"));allstudengts.Add("c200", class2List);#region 1.【XmlDocument】方法写入xml文件1.1实例化xml对象,并添加文档说明信息//XmlDocument xml = new XmlDocument();//XmlDeclaration xmldeclaration = xml.CreateXmlDeclaration("1.0", "utf-8", "yes");//xml.AppendChild(xmldeclaration);1.2根节点:学校//XmlElement rootElement = xml.CreateElement("school");//xml.AppendChild(rootElement);依次写入各个班级学生信息//foreach (var item in allstudengts)//{// //1.3根节点的子节点:班级// XmlElement classElement = xml.CreateElement("class");// //创建属性// XmlAttribute classAttribute = xml.CreateAttribute("id");// classAttribute.Value = item.Key;// classElement.Attributes.Append(classAttribute);// rootElement.AppendChild(classElement);// //依次该班级每名学生信息// foreach (Student stu in item.Value)// {// //1.4班级节点的子节点:学生// XmlElement studentElement = xml.CreateElement("student");// XmlAttribute studentAttribute = xml.CreateAttribute("sid");// studentAttribute.Value = stu.SId;// studentElement.Attributes.Append(studentAttribute);// //1.5学生子节点:姓名、年龄// XmlElement nameElement = xml.CreateElement("name");// nameElement.InnerText = stu.Name;// XmlElement ageElement = xml.CreateElement("age");// ageElement.InnerText = stu.Age.ToString();// //1.6依次插入节点到根节点// classElement.AppendChild(studentElement);// studentElement.AppendChild(nameElement);// studentElement.AppendChild(ageElement);// }//}2.写入文件(没有根节点不能写入)//xml.Save("demo.xml");#endregion#region 2.【XDocument】方法写入xml文件//1.创建dom对象XDocument xDoc = new XDocument();XDeclaration xDec = new XDeclaration("1.0", "utf-8", null);xDoc.Declaration = xDec;//2.创建根节点XElement rootElement = new XElement("school");xDoc.Add(rootElement);//3.循环加载学生信息foreach (var item in allstudengts){//根节点的子节点:班级XElement classElement = new XElement("class");classElement.SetAttributeValue("cid", "c100");rootElement.Add(classElement);//依次该班级每名学生信息foreach (Student stu in item.Value){//1.4班级节点的子节点:学生XElement stuElement = new XElement("student");stuElement.SetAttributeValue("sid", stu.SId);classElement.Add(stuElement);//1.5学生子节点:姓名、年龄XElement nameElement = new XElement("name");nameElement.Value = stu.Name;stuElement.Add(nameElement);XElement ageElement = new XElement("age");ageElement.Value = stu.Age.ToString();stuElement.Add(ageElement);}}//4.保存到文本文件xDoc.Save("demo2.xml");#endregionMessageBox.Show("写入xml文件完毕!", "写xml");}private void button1_Click(object sender, EventArgs e){#region 1.读取xml文件(XDocument)//XDocument xDoc = XDocument.Load("demo2.xml");2.获取根节点//XElement rootElement = xDoc.Root;3.将根节点加载到TreeView上//TreeNode rootNode = treeView1.Nodes.Add(rootElement.Name.ToString());4.递归加载//LoadXmlToTreeView(rootElement, rootNode.Nodes);#endregion#region 2.读取xml文件(XmlDocument)XmlDocument xmlDoc = new XmlDocument();xmlDoc.Load("demo2.xml");//获取根节点XmlElement rootElement = xmlDoc.DocumentElement;//将根节点加载到TreeView上TreeNode rootNode = treeView1.Nodes.Add(rootElement.Name);//递归加载LoadXmlByXmlDocument(rootElement, rootNode.Nodes);rootNode.Expand();#endregionMessageBox.Show("读取xml文件完毕!", "读xml");}//读取xml文件(XmlDocument)private void LoadXmlByXmlDocument(XmlElement rootElement, TreeNodeCollection treeNodeCollection){//循环rootElement下的所有子元素(直接子元素)foreach (XmlNode item in rootElement.ChildNodes){if (item.NodeType == XmlNodeType.Element){TreeNode node = treeNodeCollection.Add(item.Name);LoadXmlByXmlDocument((XmlElement)item, node.Nodes);}else if (item.NodeType == XmlNodeType.Text || item.NodeType == XmlNodeType.CDATA){treeNodeCollection.Add(item.InnerText);}}}private void LoadXmlToTreeView(XElement rootElement, TreeNodeCollection treeNodeCollection){//获取根元素rootElement下的所有子元素(直接子元素)foreach (XElement item in rootElement.Elements()){if(item.Elements().Count()==0){TreeNode node = treeNodeCollection.Add(item.Name.ToString());node.Nodes.Add(item.Value.ToString());}else{TreeNode node = treeNodeCollection.Add(item.Name.ToString());LoadXmlToTreeView(item, node.Nodes);}}}private void button3_Click(object sender, EventArgs e){#region 1.XmlDocumentXmlDocument document = new XmlDocument();//加载OpenFileDialog openDialog = new OpenFileDialog();openDialog.Filter = "XML文件(*.xml)|*.xml";DialogResult result = openDialog.ShowDialog();string path = string.Empty;if (result == System.Windows.Forms.DialogResult.OK){path = openDialog.FileName;}document.Load(path);XmlNodeList nodeList = document.GetElementsByTagName("name");MessageBox.Show(nodeList.Count.ToString(), "指定name节点");//string msg = string.Empty;//foreach (XmlNode item in nodeList)//{// msg += item.Name + " ";//}//MessageBox.Show(msg,"指定name节点");#endregion#region 2.XDocument//加载//OpenFileDialog openDialog = new OpenFileDialog();//openDialog.Filter = "XML文件(*.xml)|*.xml";//DialogResult result = openDialog.ShowDialog();//string path = string.Empty;//if (result == System.Windows.Forms.DialogResult.OK)//{// path = openDialog.FileName;//}//XDocument xd = XDocument.Load(path);根节点//XElement rootElement = xd.Root;//XElement nameXElement = rootElement.Element("name");//IEnumerable<XElement> ie = rootElement.Descendants("class");//MessageBox.Show(path);#endregion}private void Form1_Load(object sender, EventArgs e){}}}

五、生成的xml文件

欢迎关注我的公众号。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。