C# 读取XML文件示例

有关XML文件编写规范,请参考:http://www.w3school.com.cn/xml/index.asp
XML内容如下(文件名为:Information.xml):
浏览器显示:

<?xml version="1.0" encoding="utf-8"?>
<Infomation>   <ID>001<Name>Choi</Name><Age>21</Age><Gender>Male</Gender><City>GuiLin</City></ID>   <ID>002<Name>Li</Name><Age>18</Age><Gender>Female</Gender><City>Shanghai</City></ID>   <ID>003<Name>Xu</Name><Age>28</Age><Gender>Male</Gender><City>Beijing</City></ID>   <ID>004<Name>Xi</Name><Age>19</Age><Gender>Male</Gender><City>Hongkong</City></ID> </Infomation>  
使用TreeView控件编写代码如下(完整项目文件,请从http://pan.baidu.com/s/1eylW 下载): 

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Xml;

 

namespace WindowsFormsApplication7

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

 

        ListViewItem listViewItem;

        ListViewItem.ListViewSubItem listViewSubItem;

        XmlDocument xml;

 

        private void Form1_Load(object sender, EventArgs e)

        {

            listView1.Columns.Add("ID", 70, HorizontalAlignment.Center);

            listView1.Columns.Add("Name", 70, HorizontalAlignment.Center);

            listView1.Columns.Add("Age", 70, HorizontalAlignment.Center);

            listView1.Columns.Add("Gender", 70, HorizontalAlignment.Center);

            listView1.Columns.Add("City", 70, HorizontalAlignment.Center);

 

            xml = new XmlDocument();

            xml.Load("Information.xml");

            XmlNodeReader reader = new XmlNodeReader(xml);

            string str="";

            reader.Read();

            reader.Read();

 

            while (reader.Read())

            {

                switch (reader.NodeType)

                {

                    case XmlNodeType.Element:

                        str = reader.Name;

                        break;

                    case XmlNodeType.Text:

 

                        if (str == "ID")

                        {

                           listViewItem=listView1.Items.Add(reader.Value);

                            break;

                        }

                        else

                        {

                           listViewSubItem= listViewItem.SubItems.Add(reader.Value);

                        }

                        break;

                }

            }

        }

    }

}

 运行结果:
posted @ 2013-11-09 15:24  cnxy  阅读(3448)  评论(0编辑  收藏  举报
著作版权归 cnxy.me 所有