如何使用XmlDocument获取属性的值,当它包含更多键/值时

时间:2017-09-21 11:11:15

标签: c# xml xpath connection-string xmldocument

<connectionStrings>
    <add connectionString="Data Source=foo; Initial Catalog=bar;"/>
</connectionStrings>

如何使用密钥foo获取值Data Source

var doc = new XmlDocument();
doc.LoadXml(sectionXml);

// node
var node = doc.DocumentElement.SelectSingleNode("/connectionStrings/add");

// attribute
var attr = node.SelectSingleNode("@connectionString").Value; // "Data Source=foo; Initial Catalog=bar;"

解决方案(感谢Skeet)

var connectionString = nodeAttr_connectionString;
var builder = new System.Data.Common.DbConnectionStringBuilder
{
    ConnectionString = connectionString
};

var dbserver = (string)builder["Data Source"];
var database = (string)builder["Initial Catalog"];
var user = (string)builder["User ID"];
var password = (string)builder["Password"];

session["CONN_STR_SERVER"] = dbserver;
session["CONN_STR_DATABASE"] = database;
session["CONN_STR_USERNAME"] = user;
session["CONN_STR_PASSWORD"] = password;

0 个答案:

没有答案