[英]Reading XML to get value of a tag c#
I have my XML as 我有我的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>
I need the value of the recordsDirectory tag. 我需要recordsDirectory标记的值。 I tried this,
我试过了
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load("C:/Users/yachna/Desktop/RCCM_TOOL/configRCCM.xml");
string bvalue = xmldoc.SelectSingleNode("recordsDirectory").InnerText.ToString();
But got an error saying 但是有一个错误说
Object reference not set to an instance of an object.
你调用的对象是空的。
Yes, SelectSingleNode("recordsDirectory")
will return null, because you're applying that XPath to the document itself - which doesn't have a recordsDirectory
element at the top level, it has a configuration
element. 是的,
SelectSingleNode("recordsDirectory")
将返回null,因为您正在将该XPath应用于文档本身-顶层没有recordsDirectory
元素,而是具有configuration
元素。 You want: 你要:
xmldoc.SelectSingleNode("configuration/recordsDirectory")
Or go via the root element: 或通过根元素:
xmldoc.DocumentElement.SelectSingleNode("recordsDirectory")
(Or you can fetch all descendant elements call recordsDirectory
, etc. There are plenty of options here.) (或者,您可以获取所有后代元素,调用
recordsDirectory
,等等。这里有很多选项。)
Personally I'd suggest changing to use LINQ to XML if you can, as it's a simpler way of using XML, IMO. 我个人建议,如果可以的话,建议改用LINQ to XML,因为这是使用XML的一种简单方法,即IMO。 It's not too bad in the code you've given so far, but as you do more things with
XmlDocument
you'll run into it being a bit of a pain - relatively speaking, anyway. 到目前为止,您提供的代码还不错,但是当您使用
XmlDocument
做更多的事情时,您会遇到一些XmlDocument
-无论如何,相对而言。
You should also consider separating the "fetching the node" from getting the text, so you can validate that you've found the one you want: 您还应该考虑从获取文本中分离“获取节点”,以便可以验证是否已找到所需的文本:
XmlNode node = xmldoc.DocumentElement.SelectSingleNode("recordsDirectory");
if (node != null)
{
// Use it
}
else
{
// No such node. What do you want to do?
}
Try this one in your SelectSingleNode
在您的
SelectSingleNode
尝试这个
XmlNode node = doc.SelectSingleNode("/configuration/recordsDirectory");
string s = node.InnerText.ToString();
Hi To read the recordsDirectory tag you need to do : 嗨要读取recordsDirectory标签,您需要执行以下操作:
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load("C:/Users/yachna/Desktop/RCCM_TOOL/configRCCM.xml");
string bvalue = xmldoc.SelectSingleNode("configuration/recordsDirectory").InnerText.ToString();
It will work perfactly 它会完美地工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.