我的XML为
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<recordsDirectory>F:/model_RCCMREC/</recordsDirectory>
<transferDirectory>F:/model_RCCMrecTransfered/</transferDirectory>
<logDirectory>F:/model_RCCMLOG/</logDirectory>
<connectionstring>Data Source=192.168.1.7;Initial Catalog=RCCMdb;User ID=genesys;Password=genesys</connectionstring>
<table>RCCMrec</table>
<DBdestination>
<val1>ANI</val1>
<val2>DNIS</val2>
<val3>Date</val3>
<val4>Time</val4>
<val5>ConnId</val5>
<val6>UUID</val6>
<val7>EmployeeId</val7>
<val8>AgentDN</val8>
</DBdestination>
</configuration>
我需要recordsDirectory标记的值。 我试过这个,
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load("C:/Users/yachna/Desktop/RCCM_TOOL/configRCCM.xml");
string bvalue = xmldoc.SelectSingleNode("recordsDirectory").InnerText.ToString();
但是说错误
对象引用未设置为对象的实例。
答案 0 :(得分:3)
是的,SelectSingleNode("recordsDirectory")
将返回null,因为您正在将该XPath应用于文档本身 - 它在顶层没有recordsDirectory
元素,它有{{1}元素。你想要:
configuration
或者通过根元素:
xmldoc.SelectSingleNode("configuration/recordsDirectory")
(或者您可以获取所有后代元素调用xmldoc.DocumentElement.SelectSingleNode("recordsDirectory")
等。这里有很多选项。)
我个人建议你改用LINQ to XML,因为这是一种使用XML,IMO的简单方法。到目前为止,你所提供的代码并不算太糟糕,但是当你用recordsDirectory
做更多的事情时,你会遇到一些痛苦 - 相对而言,无论如何。
您还应该考虑将“获取节点”与获取文本分开,这样您就可以验证您找到了所需的文本:
XmlDocument
答案 1 :(得分:2)
在SelectSingleNode
XmlNode node = doc.SelectSingleNode("/configuration/recordsDirectory");
string s = node.InnerText.ToString();
答案 2 :(得分:1)
嗨要阅读需要执行的recordsDirectory标记:
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load("C:/Users/yachna/Desktop/RCCM_TOOL/configRCCM.xml");
string bvalue = xmldoc.SelectSingleNode("configuration/recordsDirectory").InnerText.ToString();
它可以正常工作