接上一篇
显示所有结点的内容
1 原xml文件 bookstore.xml
<?xml version="1.0" encoding="gb2312"?>
<bookstore>
<book ISBN="1234123">
<title>who am i </title>
<author>who</author>
<price>999</price>
</book>
<book>
</book>
</bookstore>
2 program.cs
using System;
using System.Xml;
namespace ReadXml
{
class Class1
{
static void Main(string[] args)
{
//实例化一个XmlDocument对象
XmlDocument xmlDoc = new XmlDocument();
//实例对象读取要写入的XML文件
xmlDoc.Load("bookstore.xml");
XmlNode xn = xmlDoc.SelectSingleNode("bookstore");
XmlNodeList xnl = xn.ChildNodes;
foreach (XmlNode xnf in xnl)
{
XmlElement xe = (XmlElement)xnf;
//该属性没有,不显示,但不会报错
Console.WriteLine(xe.GetAttribute("genre"));
//显示属性值
Console.WriteLine(xe.GetAttribute("ISBN"));
XmlNodeList xnf1 = xe.ChildNodes;
foreach (XmlNode xn2 in xnf1)
{
Console.WriteLine(xn2.InnerText);//显示子节点点文本
}
}
}
}
}
3 显示结果
1234123
who am i
who
999