读取XML属性值
GetAttribute方法和MoveToNextAttribute方法的联合使用可以读取XML文件的属性值,GetAttribute方法用于获得属性,而MoveToNextAttribute方法用于移动到下一个属性。其访问过程类似于一个循环,即“访问-移动-访问”的过程。
修改XML文件如下:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--This is a letter-->
<mail date="01-01-06">
<to>Li</to>
<from>Zhang</from>
<title>Hello</title>
<body>How are you?</body>
</mail>
可以使用XmlReader.GetAttribute方法获得相应的属性,步骤如下。
using System.Xml;
class program
{
static void Main(string[ ] args)
{
//XML文件路径
string path = @"c:\mail.xml";
string date=string.Empty;
//尝试读取该XML文件
try
{
XmlReader myReader=XmlReader.Create(path);//初始化myReader的实例
myReader.IsStartElement("mail");//直接跳至mail元素
date=myReader.GetAttribute("date");//获取当前元素即mail元素的date属性
Console.WriteLine("信件的日期为:“);
Console.WriteLine(date);
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
}
程序运行结果如下
信件的日期为:
01-01-06
这种方法必须给出元素的名称和属性的名称,还可以通过另一种方法在不提供这两项信息的情况下输出XML文件中所有的属性,步骤如下:
using System.Xml;
class program
{
static void Main(string[ ] args)
{
//XML文件路径
string path =@"c:\mail.xml";
string date=string.Empty;
//尝试读取该XML文件
try
{
XmlReader myReader=XmlReader.Create(path);//初始化myReader的实例
while(myReader.Read())
{
//检测当前myReader是否含有属性
if(myReader.HasAttributes)
{
Console.WriteLine("<" + myReader.Name + ">的属性: ");
while(myReader.MoveToNextAttribute() )
{
Console.WriteLine(" {0}={1}",myReader.Name,myReader.Value);
}
myReader.MoveToElement(); //移至下一个元素
}
}
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
}
程序运行结果如下
<xml>的属性:
version=1.0
encoding=ISO-8859-1
<mail>的属性:
Date=01-01-06