我已经阅读了关于如何从XML文件中读取的所有内容,但我无法完成任何工作.我想从XML文件中读取一个简单而简单的连接字符串,仅此而已.
我的XML看起来像
<?xml version="1.0" standalone="yes"?>
<connectionString>
<conn>"adsf"</conn>
</connectionString>
Run Code Online (Sandbox Code Playgroud)
我已经尝试过varios方式了
XmlDocument doc = new XmlDocument();
XmlTextReader reader = new XmlTextReader(xmlLoc);
while (reader.MoveToNextAttribute())
{
XmlNode a = doc.ReadNode(reader);
textBox1.Text = Text + a.Name;
}
XmlDocument xml = new XmlDocument();
xml.LoadXml(xmlLoc); //myXmlString is the xml file in string //copying xml to string: string myXmlString = xmldoc.OuterXml.ToString();
XmlNodeList xnList = xml.SelectNodes("/connectionString");
foreach (XmlNode xn in xnList)
{
XmlNode example = xn.SelectSingleNode("conn");
if (example != null)
{
string na = example["Name"].InnerText;
string no = example["NO"].InnerText;
}
}
Run Code Online (Sandbox Code Playgroud)
我错过了什么,我不知道是什么,这应该是一个非常简单的任务,但我无法完成它.有帮助吗?
我正在尝试在WIndows表单应用程序中执行此操作.
我错过了什么?
是..NET有一个用于存储连接字符串的内置机制,在App.config文件中,没有理由手动存储它并自己解析它.
右键单击您的项目,转到添加 - >新项
然后,添加"应用程序配置文件":

打开后,向其添加一个connectionStrings节点,如下所示:
// This is an example of a connectionString node. You may add child
// values to it as follows
<connectionStrings>
<add name="YourConnectionStringKey"
providerName="System.Data.SqlClient"
connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=YourDB;Trusted_Connection=Yes" />
</connectionStrings>
Run Code Online (Sandbox Code Playgroud)
然后,您使用ConfigurationManager.ConnectionStrings以下方法访问它:
string connectionString =
ConfigurationManager.ConnectionStrings["YourConnectionStringKey"].ConnectionString;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6104 次 |
| 最近记录: |