C#读取XML⽂件⾸先添加头⽂件using System.Xml;
然后,主要是⼏个步骤:
1. 创建 XML ⽂档操作对象;
2. 加载 XML ⽂档到⽂档对象中;
3. 获取 XML ⽂档根⽬录;
4. 遍历匹配节点信息,将对象信息放置list集合中。
Student.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace XMLOperateSelfExercise
{
class Student
{
public string StuName { get; set; }
public int StuAge { get; set; }
public string Gender { get; set; }
public string ClassName { get; set; }
}
}
Form1.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
// 添加操作 XML 的头⽂件
using System.Xml;
namespace XMLOperateSelfExercise
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.dataGridView1.RowHeadersVisible = false;
}
// 加载XML⽂件
private void btnLoadXML_Click(object sender, EventArgs e)
{
// [1] 创建 XML ⽂档操作对象
XmlDocument objDoc = new XmlDocument();
// [2] 加载 XML ⽂档到⽂档对象中
objDoc.Load(@"./l");
// [3] 获取 XML ⽂档根⽬录
XmlNode rootNode = objDoc.DocumentElement;
List<Student> stuNodeInfo = new List<Student>();// 创建集合对象,⽤来存放对象信息
foreach (XmlNode item in rootNode.ChildNodes) {
if (item.Name == "Student") {
Student objStu = new Student();
foreach (XmlNode stuInnerNode in item) {
switch (stuInnerNode.Name) {
case "StuName":
objStu.StuName = stuInnerNode.InnerText;
break;
case "StuAge":
objStu.StuAge = Convert.ToInt32(stuInnerNode.InnerText);
break;
case "Gender":
objStu.Gender = stuInnerNode.InnerText;
break;
case "ClassName":
objStu.ClassName = stuInnerNode.InnerText;
break;
}
}
stuNodeInfo.Add(objStu);
}
}
this.dataGridView1.DataSource = stuNodeInfo;
}
// 加载版本信息
private void btnVersion_Click(object sender, EventArgs e)
{
// 创建 XML 读取器
XmlTextReader xmlTReader = new XmlTextReader(@"./l");
string versionInfo = string.Empty;
// 循环查询
while(xmlTReader.Read()) {
if (xmlTReader.Name == "Version") {
versionInfo = "版本:" + xmlTReader.GetAttribute("vNo") + "发布时间:" + xmlTReader.GetAttribute("pTime"); break;
}
}
MessageBox.Show(versionInfo, "版本信息");
}
}
}
<?xml version="1.0" encoding="utf-8" ?>
<Students>
<Student>
<StuName>令狐冲</StuName>
<StuAge>19</StuAge>
<Gender>男</Gender>
<ClassName>1班</ClassName>
</Student>
<Student>
<StuName>岳灵珊</StuName>
<StuAge>16</StuAge>
<Gender>⼥</Gender>
<ClassName>2班</ClassName>
</Student>
<Student>
<StuName>岳不</StuName>
<StuAge>40</StuAge>
<Gender>男</Gender>
<ClassName>3班</ClassName>
</Student>
<Student>
<StuName>乔峰</StuName>
<StuAge>23</StuAge>
<Gender>男</Gender>
<ClassName>4班</ClassName>
</Student>
<Student>
<StuName>韦⼩宝</StuName>
<StuAge>20</StuAge>
<Gender>男</Gender>
<ClassName>5班</ClassName>
</Student>
<DataInfo>system的头文件
<Version vNo="1.2" pTime="2018-10-22">数据版本信息</Version>
</DataInfo>
</Students>
输出效果:
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论