c#操作XML文件的方法

// XML文件SQL_Connection_Info.xml

<?xml version="1.0" encoding="utf-8"?>
<ConnectionInfo>
  <DataConnection Name="Info64">
    <DataSource>INFO64/sqlexpress</DataSource>
    <InitialCatalog>worklog</InitialCatalog>
    <UserID>sa</UserID>
    <Password>xxx</Password>
  </DataConnection>
 
  <DataBase Name="Other">
    <DataSource></DataSource>
    <InitialCatalog>2</InitialCatalog>
    <UserID>3</UserID>
    <Password>4</Password>
  </DataBase>
</ConnectionInfo>

// ******************************************************************
// 用LINQ操作XML文件
// 需要用到的名空間
using System.Xml.Linq;
using System.Linq;

// 判斷XML文件是否存在
if (!System.IO.File.Exists("SQL_Connection_Info.xml")) return;

string strDataSource, strInitialCatalog, strUserID, strPassword;

// 讀取SQL_Connection_Info.xml文件到root
XElement root = XElement.Load("SQL_Connection_Info.xml");
// 查詢DataConnection節點Name等於Info64的子元素集合
IEnumerable<XElement> DataConnection = from el in root.Elements("DataConnection") where (string)el.Attribute("Name") == "Info64" select el;

// 查詢上面DataConnection集合中節點名稱爲DataSource的文本內容
strDataSource = (string)(from eo in DataConnection.Descendants("DataSource") select eo).First();

strInitialCatalog = (string)(from eo in DataConnection.Descendants("InitialCatalog") select eo).First();
strUserID = (string)(from eo in DataConnection.Descendants("UserID") select eo).First();
strPassword = (string)(from eo in DataConnection.Descendants("Password") select eo).First();
//******************************************************************


// ******************************************************************
// 用XmlDocument操作XML文件
// 需要用到的名空間
using System.Xml;

// 判斷XML文件是否存在
if (!System.IO.File.Exists("SQL_Connection_Info.xml")) return;

XmlDocument xmlDoc = new XmlDocument();

// 加載XML文件
xmlDoc.Load("SQL_Connection_Info.xml");

// 選擇ConnectionInfo節,並獲取該節點的所有子節點
XmlNodeList ResultNodesList = xmlDoc.SelectSingleNode("ConnectionInfo").ChildNodes;

XmlElement xe, xe2;

string strDataSource, strInitialCatalog, strUserID, strPassword;

// 遍歷ConnectionInfo下的所有子節點
foreach (XmlNode xnf in ResultNodesList)
{
    xe = (XmlElement)xnf;
    // 查找節點爲DataConnection,屬性Name爲Info64的節點
    if (xe.Name == "DataConnection" && xe.GetAttribute("Name") == "Info64")
    {
        // 獲取所有子節點
        XmlNodeList xn = xe.ChildNodes;
        // 遍歷所有子節點
        foreach (XmlNode xn1 in xn)
        {
            xe2 = (XmlElement)xn1;
            if (xe2.Name == "DataSource")
                strDataSource = xe2.InnerText;

            if (xe2.Name == "InitialCatalog")
                strInitialCatalog = xe2.InnerText;

            if (xe2.Name == "UserID")
                strUserID = xe2.InnerText;

            if (xe2.Name == "Password")
                strPassword = xe2.InnerText;
        }
        break;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章