C# 读取XML以获取标记c的值#
我把我的XML作为C# 读取XML以获取标记c的值#,c#,xml-parsing,C#,Xml Parsing,我把我的XML作为 F:/model\u RCCMREC/ F:/model\rccmrectransfer/ F:/model\u RCCMLOG/ 数据源=192.168.1.7;初始目录=RCCMdb;用户ID=genesys;密码=genesys RCCMrec 安尼 德尼斯 日期 时间 康尼德 UUID 雇员ID 代理 我需要recordsDirectory标记的值。 我试过这个 XmlDocument xmldoc = new XmlDocument(); xmldoc.Loa
F:/model\u RCCMREC/
F:/model\rccmrectransfer/
F:/model\u RCCMLOG/
数据源=192.168.1.7;初始目录=RCCMdb;用户ID=genesys;密码=genesys
RCCMrec
安尼
德尼斯
日期
时间
康尼德
UUID
雇员ID
代理
我需要recordsDirectory标记的值。
我试过这个
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load("C:/Users/yachna/Desktop/RCCM_TOOL/configRCCM.xml");
string bvalue = xmldoc.SelectSingleNode("recordsDirectory").InnerText.ToString();
但是有个错误说
对象引用未设置为对象的实例
是的,
SelectSingleNode(“recordsDirectory”)
将返回null,因为您正在将该XPath应用于文档本身-文档顶层没有recordsDirectory
元素,它有一个配置
元素。你想要:
xmldoc.SelectSingleNode("configuration/recordsDirectory")
或者通过根元素:
xmldoc.DocumentElement.SelectSingleNode("recordsDirectory")
(或者,您可以通过调用记录目录
等获取所有子元素。这里有很多选项。)
就我个人而言,我建议如果可以的话改用LINQ to XML,因为这是一种更简单的使用XML的方法,IMO。到目前为止,您给出的代码还不错,但是当您使用XmlDocument
做更多事情时,您会遇到一点麻烦——无论如何,相对而言
您还应该考虑将“获取节点”分隔成文本,这样您就可以验证您找到了想要的文本:
XmlNode node = xmldoc.DocumentElement.SelectSingleNode("recordsDirectory");
if (node != null)
{
// Use it
}
else
{
// No such node. What do you want to do?
}
是的,
SelectSingleNode(“recordsDirectory”)
将返回null,因为您正在将该XPath应用于文档本身-文档顶层没有recordsDirectory
元素,它有一个配置
元素。你想要:
xmldoc.SelectSingleNode("configuration/recordsDirectory")
或者通过根元素:
xmldoc.DocumentElement.SelectSingleNode("recordsDirectory")
(或者,您可以通过调用记录目录
等获取所有子元素。这里有很多选项。)
就我个人而言,我建议如果可以的话改用LINQ to XML,因为这是一种更简单的使用XML的方法,IMO。到目前为止,您给出的代码还不错,但是当您使用XmlDocument
做更多事情时,您会遇到一点麻烦——无论如何,相对而言
您还应该考虑将“获取节点”分隔成文本,这样您就可以验证您找到了想要的文本:
XmlNode node = xmldoc.DocumentElement.SelectSingleNode("recordsDirectory");
if (node != null)
{
// Use it
}
else
{
// No such node. What do you want to do?
}
在
选择SingleNode
XmlNode node = doc.SelectSingleNode("/configuration/recordsDirectory");
string s = node.InnerText.ToString();
在
选择SingleNode
XmlNode node = doc.SelectSingleNode("/configuration/recordsDirectory");
string s = node.InnerText.ToString();
您好要阅读recordsDirectory标记,您需要执行以下操作:
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load("C:/Users/yachna/Desktop/RCCM_TOOL/configRCCM.xml");
string bvalue = xmldoc.SelectSingleNode("configuration/recordsDirectory").InnerText.ToString();
读取您需要执行的Records目录标记时,它将正常工作:
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load("C:/Users/yachna/Desktop/RCCM_TOOL/configRCCM.xml");
string bvalue = xmldoc.SelectSingleNode("configuration/recordsDirectory").InnerText.ToString();
它将在选择节点使用
配置/记录目录
中的选择节点使用配置/记录目录
中正常工作