C#的XML操作

一、读取web.config的appSettings与connectionStrings。

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

namespace PaoTiao.Common
{
    
/// <summary>
    
/// 读取web.config的appSettings与connectionStrings
    
/// </summary>
    public class PTXml
    {
        
/// <summary>
        
/// 构造函数
        
/// </summary>
        
/// <param name="xmlPath">xml文档物理路径</param>
        public PTXml(string xmlPath)
        {
            
this.doc = new XmlDocument();
            
this.doc.Load(xmlPath);
            
this.root = doc.DocumentElement;
        }

        
private XmlDocument doc;
        
private XmlElement root;

        
/// <summary>
        
/// 获取web.config中appSettings中节点值
        
/// </summary>
        
/// <param name="key">key不区分大小写</param>
        
/// <returns></returns>
        public string GetAppSetting(string key)
        {
            
string s = "";

            
foreach (XmlNode node1 in this.root.ChildNodes)
            {
                
if (node1.Name == "appSettings")
                {
                    
foreach (XmlNode node2 in node1.ChildNodes)
                    {
                        
if (node2.Name == "add")
                        {
                            
if (node2.Attributes["key"].Value.ToLower() == key.ToLower())
                            {
                                s 
= node2.Attributes["value"].Value;
                            }
                        }
                    }
                }
            }

            
return s;
        }

        
/// <summary>
        
/// 获取web.config中connectionStrings中节点值
        
/// </summary>
        
/// <param name="name">name不区分大小写</param>
        
/// <returns></returns>
        public string GetConnectionString(string name)
        {
            
string s = "";

            
foreach (XmlNode node1 in this.root.ChildNodes)
            {
                
if (node1.Name == "connectionStrings")
                {
                    
foreach (XmlNode node2 in node1.ChildNodes)
                    {
                        
if (node2.Name == "add")
                        {
                            
if (node2.Attributes["name"].Value.ToLower() == name.ToLower())
                            {
                                s 
= node2.Attributes["connectionString"].Value;
                            }
                        }
                    }
                }
            }

            
return s;
        }

    }
//end class
}//end namespace

 

posted on 2009-03-13 10:17  吴剑  阅读(337)  评论(0编辑  收藏  举报

导航