[英]Reading XML to get value of a tag c#
我有我的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();
但是有一個錯誤說
你調用的對象是空的。
是的, SelectSingleNode("recordsDirectory")
將返回null,因為您正在將該XPath應用於文檔本身-頂層沒有recordsDirectory
元素,而是具有configuration
元素。 你要:
xmldoc.SelectSingleNode("configuration/recordsDirectory")
或通過根元素:
xmldoc.DocumentElement.SelectSingleNode("recordsDirectory")
(或者,您可以獲取所有后代元素,調用recordsDirectory
,等等。這里有很多選項。)
我個人建議,如果可以的話,建議改用LINQ to XML,因為這是使用XML的一種簡單方法,即IMO。 到目前為止,您提供的代碼還不錯,但是當您使用XmlDocument
做更多的事情時,您會遇到一些XmlDocument
-無論如何,相對而言。
您還應該考慮從獲取文本中分離“獲取節點”,以便可以驗證是否已找到所需的文本:
XmlNode node = xmldoc.DocumentElement.SelectSingleNode("recordsDirectory");
if (node != null)
{
// Use it
}
else
{
// No such node. What do you want to do?
}
在您的SelectSingleNode
嘗試這個
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();
它會完美地工作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.