首页 > IT职业 > IT图书 > XML的序列化读取方式
C#中如何读取XML文件?如何读取最快?我的回答是,使用XmlTextReader读取的速度是最快的。但也不乏一些效率稍低但也非常有效的读取方式,比如序列化方式。这里详细介绍一下步骤吧。
使用Visual Studio的CreateSchema工具,或者XMLSpy等第三方的工具,打开需要读取的XML文件,并创建XSD(推荐使用Visual Studio自带的工具)
比如我有个文件是students.xml,内容如下:
在使用工具生成xsd以后,获得students.xsd内容如下:
|
1
2
3
4
5
6
7
8
9
|
xml version="1.0" encoding="utf-8"?>
student>
student>
students>
|
将生成的students.cs文件添加到你的项目中。此时如果你的xsd文件和这个cs文件在相同目录下,那么在你的“解决方案资源管理器”中,会将两者关联起来使用xsd.exe生成类文件,如下:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
xml version="1.0" encoding="utf-8"?>
xs:sequence>
xs:complexType>
xs:element>
xs:sequence>
xs:complexType>
xs:element>
xs:schema>
|
使用下面的代码读取你的students.xml文件:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
using System;
using System.IO;
using System.Xml.Serialization;
namespace XmlRead
{ class Program
{
static void Main(string[] args)
{
XmlSerializer serializer = new XmlSerializer(typeof(students));
using (FileStream fs = new FileStream(@"c:students.xml", FileMode.Open))
{
students studs = (students)serializer.Deserialize(fs);
foreach (var stud in studs.student)
{
Console.WriteLine("{0}: Age = {1}, Registered = {2}",
stud.name,
stud.age,
stud.registered);
}
fs.Close();
}
}
}
} |
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/1451/viewspace-2799959/ ,如需转载,请注明出处,否则将追究法律责任。