c# 求一段关于xml简单的代码

来源:百度知道 编辑:UC知道 时间:2024/05/22 14:39:14
已知xml文件内容如下:
<?xml version="1.0" encoding="iso-8859-1"?>
<albums>
<photoset name="LeChayim for David and Debbie" imagebase="samples/">
<photo>
<ptitle title="Shenandoah Hike to Falls" />
<pimage src="img25.jpg" />
<pcaption caption="At LeChayim for David and Debbie on their engagement" />
<pdate picdate = "Feb. 01, 2004" />
</photo>
<photo>
<ptitle title="Shenandoah Hike to Falls" />
<pimage src="img28.jpg" />
<pcaption caption="David and Debbie at engagement get-together" />
<pdate picdate = "Feb. 01, 2004" />
</photo>
</photose

先添加一个根节点,要不然xml文档是错误的,就不能读取了。

代码如下:
XmlDocument xmlDoc = new XmlDocument();

void readXml()
{
//加载xml文件, 假设你的xml文件名是xmlFile.xml
xmlDoc.Load(@"xmlFile.xml");
//得到根节点
XmlNode root = xmlDoc.DocumentElement;
//定义一个ArrayList,用来存放图片的名称
ArrayList imgName = new ArrayList();
//得到根节点下的所有albums节点
for (int i = 0; i < root.SelectNodes("albums").Count; i++)
{
//遍历每个albums节点下的所有photoset节点
for (int j = 0; i < root.SelectNodes("albums")[i].SelectNodes("photeset").Count; j++)
{
//遍历每个photoset下的photo节点
for (int k = 0; k < root.SelectNodes("albums")[i].SelectNodes("photeset")[j].SelectNodes("photo").Count; k++)
{
XmlNode imgNameNode = root.SelectNodes("albums")[i].SelectNodes("photeset"