xml读取

using System;
using System.IO;
using System.Linq;
using System.Xml.Linq;

namespace ThtfWeatherServ
{
    /// <summary>
    /// xml访问类
    /// 2015-12-24
    /// XingSQ
    /// </summary>
    class XMLAccess
    {
        /// <summary>
        /// 构造xmlAccess 对象
        /// </summary>
        /// <param name="fileName">xml文件名</param>
        public XMLAccess(string fileName)
        {
            LoadXML(strXMlfilepath + fileName);
        }

        /// <summary>
        /// 加载xml文件到内存
        /// </summary>
        /// <param name="fullFilePath">xml文件的完整路径包括文件名</param>
        /// <returns></returns>
        private bool LoadXML(string fullFilePath)
        {
            try
            {
                if (File.Exists(fullFilePath))
                {
                    elementObj = XElement.Load(fullFilePath);
                    return true;
                }
                else
                {
                    throw new DirectoryNotFoundException(fullFilePath + "文件不存在");

                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        /// <summary>
        /// 取得对应元素(elementName) 的值,只取发现的第一个此元素的值
        /// </summary>
        /// <param name="elementName">元素</param>
        /// <returns>值</returns>
        public string GetElementValue(string elementName)
        {
            try
            {
                var chileElements = from ele in elementObj.Elements(elementName)
                                    select new { name = elementName, value = ele.Value };
                foreach (var item in chileElements)
                {
                    return item.value.Trim();
                }
                return "";

            }
            catch (Exception e)
            {
                throw e;
            }
        }

        private XElement elementObj;
        private string strXMlfilepath = System.Threading.Thread.GetDomain().BaseDirectory;  //取得执行文件所在目录
    }
}数据库


<?xml version="1.0" encoding="gb2312"?>
<root>
    <!--Web所用数据库所在IP地址 -->
    <IP>10.10.49.13</IP>
    <!-- Web数据库 用户名-->
    <username>xopens</username>
    <!--Web数据库对应上述用户名的密码 -->
    <password>iscs200</password>
    <!--存取天气信息的间隔时间(单位分钟,最小10分钟) -->
    <interval>30</interval>
    <!-- 项目编号 -->
    <projectno>sy</projectno>
    <!--所取天气对应的城市代码 -->
    <citycode>101070101</citycode>
</root>spa

相关文章
相关标签/搜索