// 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;
}
}