天天看點

c#讀取xml檔案的一個節點

我的xml檔案内容很簡單,如下所示:

<?xml version="1.0" encoding="utf-8" ?>

<connString>

             Data Source=.;Initial Catalog=KTV;Persist Security Info=True;User ID=sa;Password=123456;

</connString>

---------------------------------------------------------------------------------------------------------------------------------------------------

現在我想用代碼讀取該檔案中連接配接資料庫的字元串,我該如何做呢?

實作代碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Windows.Forms;

namespace HouseRentHelper.db
{
    class MyXml
    {
        public static string GetConnString()
        {
            try
            {
                //注意要引入命名空間 using System.Xml;
                XmlDocument doc = new XmlDocument();
                doc.Load(@"db.xml");//加載xml檔案
                XmlNode node = doc.SelectSingleNode("connString"); //擷取節點connString
                return node.InnerText;//擷取節點的文本内容
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString()+ex.Message);
                return null;
            }
        }
    }
           

----------------------------------------------------------------------------------------------------------------------------------------------------------------

效果截圖如下:

 MessageBox.Show(MyXml.GetConnString()); //調用語句

----------------------------------------------------------------------------------------------------------------------------------------------------------------

c#讀取xml檔案的一個節點

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

c#讀取xml檔案的一個節點

您的十分滿意是我追求的宗旨。

您的一點建議是我後續的動力。