C# 读取XML文件时出错
我有一个这样的XML文件C# 读取XML文件时出错,c#,xml,C#,Xml,我有一个这样的XML文件 <?xml version="1.0" encoding="utf-8" ?> <conStr> <server>192.168.1.25;</server> <initial_catalog>chargdb;</initial_catalog> <uid>sa;</uid> <pwd>1;</pwd> <
<?xml version="1.0" encoding="utf-8" ?>
<conStr>
<server>192.168.1.25;</server>
<initial_catalog>chargdb;</initial_catalog>
<uid>sa;</uid>
<pwd>1;</pwd>
</conStr>
但每次我都会给出这样的错误消息:“对象引用未设置为对象的实例。”
请帮助我,我能做些什么来阅读我的文件?谢谢
xd.DocumentElement.ChildNodes[0]
指的是
元素。你需要看看孩子们
考虑使用get导航文档。
xd.DocumentElement.ChildNodes[0]
指的是
元素。你需要看看孩子们
考虑使用get来浏览文档。要正确回答您的问题,以下是Jakub的意思:
string conStr = string.Empty;
conStr += "server=";
conStr += xd.DocumentElement.SelectSingleNode("./server").InnerText;
conStr += "initial catalog=";
conStr += xd.DocumentElement.SelectSingleNode("./initial_catalog").InnerText;
conStr += "uid=";
conStr += xd.DocumentElement.SelectSingleNode("./uid").InnerText;
conStr += "pwd=";
conStr += xd.DocumentElement.SelectSingleNode("./pwd").InnerText;
MessageBox.Show(conStr);
对于记录Jakub,xd.DocumentElement.ChildNodes[0],是根元素('conStr')…要正确回答您的问题,这就是Jakub的意思:
string conStr = string.Empty;
conStr += "server=";
conStr += xd.DocumentElement.SelectSingleNode("./server").InnerText;
conStr += "initial catalog=";
conStr += xd.DocumentElement.SelectSingleNode("./initial_catalog").InnerText;
conStr += "uid=";
conStr += xd.DocumentElement.SelectSingleNode("./uid").InnerText;
conStr += "pwd=";
conStr += xd.DocumentElement.SelectSingleNode("./pwd").InnerText;
MessageBox.Show(conStr);
对于记录Jakub,xd.DocumentElement.ChildNodes[0],是根元素('conStr')…您的现有代码正在
元素中查找属性。这是行不通的,因为您应该在根元素中查找元素
我要做两个改变:
- 使用LINQ to XML获取值
- 使用
而不是作为字符串构建连接字符串SqlConnectionStringBuilder
XDocument doc = XDocument.Load(...);
var root = doc.Root;
var builder = new SqlConnectionStringBuilder
{
DataSource = root.Element("server").Value,
InitialCatalog = root.Element("initial_catalog").Value,
UserID = root.Element("uid").Value,
Password = root.Element("pwd").Value
};
var connectionString = builder.ToString();
现有代码正在
元素中查找属性。这是行不通的,因为您应该在根元素中查找元素
我要做两个改变:
- 使用LINQ to XML获取值
- 使用
而不是作为字符串构建连接字符串SqlConnectionStringBuilder
XDocument doc = XDocument.Load(...);
var root = doc.Root;
var builder = new SqlConnectionStringBuilder
{
DataSource = root.Element("server").Value,
InitialCatalog = root.Element("initial_catalog").Value,
UserID = root.Element("uid").Value,
Password = root.Element("pwd").Value
};
var connectionString = builder.ToString();
否,
xd.DocumentElement.ChildNodes[0]
指的是
元素。我刚刚在一个测试应用程序中对此进行了验证。否,xd.DocumentElement.ChildNodes[0]
指的是
元素。我刚刚在一个测试应用程序中尝试了这一点来确认。如果你只有一个连接配置,我认为这是最好的答案@JFTxJ:如果有多个配置,我将使用基本相同的代码-只需将创建连接字符串的位提取到接受XElement
@Jon极好答案的方法,但是需要更改XML文件以省略额外的分号代码>如果您只有一个连接配置,我认为这是最好的答案@JFTxJ:如果有多个配置,我将使用基本相同的代码-只需将创建连接字符串的位提取到接受XElement
@Jon极好答案的方法,但是需要更改XML文件以省略额外的分号
No,xd.DocumentElement.ChildNodes[0]
是
元素。No,xd.DocumentElement.ChildNodes[0]
是
元素。