如何读取XML文档 c#

第一步 先建立一个xml文档 看文档如下 也可以用代码来写入xml

<?xml version="1.0" encoding="gb2312"?>
<paramentList>  
    <paramentEntity id="niname">     
        <id>{$Niname$}</id>    
        <value>称呼</value>    
    </paramentEntity>
    <paramentEntity id="sign">    
        <id>{$Sign$}</id>    
        <value>签名</value>    
    </paramentEntity>
</paramentList>

第二步 写一个对于的实体类

using System;
using System.Collections.Generic;
using System.Text;

namespace APlusEmail.Model
{
    public class ParamentEntity
    {
        private string id;

        public string Id
        {
            get { return id; }
            set { id = value; }
        }
        private string value;

        public string Value
        {
            get { return this.value; }
            set { this.value = value; }
        }
    }
}

第三步 写一个工具类 来操作

using System;
using System.Collections.Generic;
using System.Text;
using APlusEmail.Model;
using System.Xml;

namespace APlusEmail.Common
{
    public static class XMLHelper
    {
        public static List<ParamentEntity> GetAllParament(string xmlPath)
        {
            List<ParamentEntity> paramentList = new List<ParamentEntity>();
            //创建xmldoc对象
            XmlDocument xmlDoc = new XmlDocument();
            //装载xml
            xmlDoc.Load(xmlPath);
            //获取xml的节点
            XmlNode xn = xmlDoc.SelectSingleNode("paramentList");
            //获取该节点的所有子节点
            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;
                ParamentEntity parementEntity = new ParamentEntity();
                parementEntity.Id = xnf1[0].InnerText;
                parementEntity.Value = xnf1[1].InnerText;
                // Console.WriteLine(xn2.InnerText);//显示子节点点文本
                paramentList.Add(parementEntity);
            }
            return paramentList;
        }
    }
}

这样就返回一个对应的实体列表了 就可以供使用了

posted @ 2012-12-14 14:08  麦田HH  阅读(356)  评论(0编辑  收藏  举报