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

相關文章
相關標籤/搜索