經(jīng)過(guò)努力臀规,終于解決了XmlReader在未知元素的名稱和屬性的名稱的情況下讀取屬性的方法元旬。在沒(méi)有解決前,我的代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace ReadAttribute
{
class Program
{
static void Main(string[] args)
{
string path = @"e:\testfile\myMail.xml";
#region 讀取屬性的第一種方法
//string date;
//try
//{
// XmlReader xr = XmlReader.Create(path);
// xr.ReadToFollowing("mail");
// date = xr.GetAttribute("date");
// Console.Write("信件的日期為:");
// Console.WriteLine(date);
//}
//catch (Exception ex)
//{
// Console.WriteLine(ex.Message);
//}
#endregion
#region 讀取屬性的第二種方法
try
{
XmlReader xr = XmlReader.Create(path);
while (xr.Read())
{
if (xr.HasAttributes)
{
//Console.WriteLine("<" + xr.Name + ">的屬性:");
//for (int i = 0; i < xr.AttributeCount; i++)
//{
//xr.MoveToAttribute(i);
Console.WriteLine("<" + xr.Name + ">的屬性:");
Console.WriteLine("{0}={1}", xr.Name, xr.Value);
//}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
#endregion
Console.ReadKey();
}
}
}
解決后既峡,我的代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace ReadAttribute
{
class Program
{
static void Main(string[] args)
{
string path = @"e:\testfile\myMail.xml";
#region 讀取屬性的第一種方法
//string date;
//try
//{
// XmlReader xr = XmlReader.Create(path);
// xr.ReadToFollowing("mail");
// date = xr.GetAttribute("date");
// Console.Write("信件的日期為:");
// Console.WriteLine(date);
//}
//catch (Exception ex)
//{
// Console.WriteLine(ex.Message);
//}
#endregion
#region 讀取屬性的第二種方法
try
{
XmlReader xr = XmlReader.Create(path);
while (xr.Read())
{
if (xr.HasAttributes)
{
Console.WriteLine("<" + xr.Name + ">的屬性:");
for (int i = 0; i < xr.AttributeCount; i++)
{
xr.MoveToAttribute(i); 43 //Console.WriteLine("<" + xr.Name + ">的屬性:");
Console.WriteLine("{0}={1}", xr.Name, xr.Value);
} 46 }
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
#endregion
Console.ReadKey();
}
}
}
解決后羡榴,上面的代碼可以不用知道元素的名稱和屬性的名稱的情況下讀取XML文件中的所有屬性名及其值。這種方法有點(diǎn)像迭代器遍歷數(shù)組运敢,只不過(guò)這里的元素變成了XML的節(jié)點(diǎn)和元素校仑,而且這里可以把XML的屬性也可以看成是XML的節(jié)點(diǎn)(”可以看成XML元素的子節(jié)點(diǎn)“),這樣元素看成是節(jié)點(diǎn)传惠,屬性也看成是節(jié)點(diǎn)迄沫,都當(dāng)做節(jié)點(diǎn)處理,也就是說(shuō)這個(gè)遍歷可以看成是遍歷XML的節(jié)點(diǎn)卦方。這樣也就可以解釋上面代碼中的 xr.Name羊瘩、xr.Value了,他們分別可以看成是XML的節(jié)點(diǎn)名和節(jié)點(diǎn)值(即屬性名和屬性值)。如此尘吗,這樣的方法便不難理解了逝她!