C# 读写XML文件示例

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

namespace MSCL
{
    /// <summary>
    /// 配置文件帮助类
    /// </summary>
    public class ConfigExtHelper
    {
        /*
            <?xml version="1.0" encoding="utf-8" ?>
            <config>
              <token>king</token>
              <cookie>123456</cookie>
              <pwd>123456</pwd>
            </config>
         */
        /// <summary>
        /// xml文件路径
        /// </summary>
        public static string filepath =  System.Web.HttpContext.Current.Server.MapPath("/XML/config.xml");

        /// <summary>
        /// 设置值
        /// </summary>
        /// <param name="key">key</param>
        /// <param name="value">value</param>
        public static void Set(string key, string value)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(filepath);
            XmlNode node;
            node = xmlDoc.SelectSingleNode("config/" + key);
            if (node == null)
            {
                XmlElement n = xmlDoc.CreateElement(key);
                n.InnerText = value;
                xmlDoc.SelectSingleNode("config").AppendChild(n);
            }
            else
            {
                node.InnerText = value;
            }
            xmlDoc.Save(filepath);
        }

        /// <summary>
        /// 根据key获取value
        /// </summary>
        /// <param name="key">key</param>
        /// <returns></returns>
        public static string Get(string key)
        {
            //获得数据
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(filepath);
            XmlNode node;
            node = xmlDoc.SelectSingleNode("config/" + key);
            string str = node == null ? "" : node.InnerText;
            return str;
        }
    }
}

 

posted @ 2017-10-14 11:39  深南大道  阅读(2102)  评论(0编辑  收藏  举报