XML参考 :XmlReader 详解、实例(2)-- 读取XML节点
.NET Framework 类库
XmlReader 类
表示提供对 XML 数据进行快速、非缓存、只进访问的读取器,即 对 XML 数据流的只进只读访问。XmlReader 类符合 W3C 可扩展标记语言 (XML) 1.0 和“XML 中的命名空间”建议。
二.实例,读取XML节点
1. 我们先创建一个Employees.xml的文件
<?xml version="1.0" encoding="utf-8" ?>
<employees>
<employee id="1">
<name>
<firstName>Jack</firstName>
<lastName>Wang</lastName>
</name>
<city>BeiJing</city>
<state>BeiJing</state>
<zipCode>100061</zipCode>
</employee>
<employee id="2">
<name>
<firstName>DeHua</firstName>
<lastName>Liu</lastName>
</name>
<city>Hongkong</city>
<state>China</state>
<zipCode>000061</zipCode>
</employee>
</employees>
<employees>
<employee id="1">
<name>
<firstName>Jack</firstName>
<lastName>Wang</lastName>
</name>
<city>BeiJing</city>
<state>BeiJing</state>
<zipCode>100061</zipCode>
</employee>
<employee id="2">
<name>
<firstName>DeHua</firstName>
<lastName>Liu</lastName>
</name>
<city>Hongkong</city>
<state>China</state>
<zipCode>000061</zipCode>
</employee>
</employees>
2.读取元素的代码:
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
namespace JackDong.XmlReaderDemo
{
class XmlReaderDemo
{
private static string xmlFilePath = @"..\..\EmployeeInfo.xml";// @"D:\\EmployeeInfo.xml"
public static string ReadXml()
{
string result = "";
try
{
using (XmlReader reader = XmlReader.Create(xmlFilePath))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
for (int count = 0; count < reader.Depth; count++)
{
result += "---";
}
result += "->" + reader.Name + "\n";
}
}
}
}
catch (Exception ex){
result += "An Exception occured: " + ex.Message;
}
return result;
}
}
class Program
{
static void Main()
{
string strReturn = XmlReaderDemo.ReadXml();
Console.WriteLine(strReturn);
Console.ReadLine();
}
}
}
using System.Collections.Generic;
using System.Text;
using System.Xml;
namespace JackDong.XmlReaderDemo
{
class XmlReaderDemo
{
private static string xmlFilePath = @"..\..\EmployeeInfo.xml";// @"D:\\EmployeeInfo.xml"
public static string ReadXml()
{
string result = "";
try
{
using (XmlReader reader = XmlReader.Create(xmlFilePath))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
for (int count = 0; count < reader.Depth; count++)
{
result += "---";
}
result += "->" + reader.Name + "\n";
}
}
}
}
catch (Exception ex){
result += "An Exception occured: " + ex.Message;
}
return result;
}
}
class Program
{
static void Main()
{
string strReturn = XmlReaderDemo.ReadXml();
Console.WriteLine(strReturn);
Console.ReadLine();
}
}
}
3.执行效果如下: