读取XML数据


已知XML文件如下(app.xml):

<events> 
  <title>Reading XML data!</title> 
  <event> 
    <date>sample date 1</date> 
    <name>sample name 1</name> 
  </event> 
  <event> 
    <date>sample date 2</date> 
    <name>sample name 2</name> 
  </event>
  <test>
    <age>25</age>
    <name>alex zhou</name>
  </test>
</events>

读取XML文件内容并显示:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Xml;
 6 namespace ConsoleApplication1
 7 {
 8     class Program
 9     {
10         static void Main(string[] args)
11         {
12             XmlDocument xmldoc = new XmlDocument();            
13             xmldoc.Load(@"C:\Users\zhoupan\Desktop\XML\app.xml");
14             XmlElement root = xmldoc.DocumentElement;
15             XmlNodeList nodelist = root.SelectNodes("//event");
16             Console.WriteLine("date                    name" );
17             Console.WriteLine("----                    ----");
18             //多行相同的读取
19             foreach(XmlNode xmlnode in nodelist )
20             {
21                 Console.WriteLine(xmlnode["date"].InnerText+"           "+xmlnode["name"].InnerText);
22             }
23 
24             //读取单行的数据
25             XmlNode xmln = xmldoc.DocumentElement.SelectSingleNode("title");            
26             Console.WriteLine(xmln.InnerText);
27             xmln = xmldoc.DocumentElement.SelectSingleNode("test");
28             Console.WriteLine(xmln["age"].InnerText + "                      " + xmln["name"].InnerText);
29             Console.Read();
30         }
31     }
32 }

显示数据如下:

1 Title:
2 Reading XML data!
3 date                    name
4 ----                     ----
5 sample date 1      sample name 1
6 sample date 2      sample name 2
7 25                       alex zhou

 

posted @ 2012-10-19 22:39  zp_Alex  阅读(204)  评论(0编辑  收藏  举报