2013-10-31 46 views
0

變量的值,我有我的XML作爲讀取XML獲得C#

<?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(); 

,但得到一個錯誤說

對象引用不設置到對象的實例。

+1

在選擇節點使用'配置/ recordsDirectory' –

回答

3

是,SelectSingleNode("recordsDirectory")將返回null,因爲你申請了XPath文檔本身 - 這並不在頂層有一個recordsDirectory元素,它具有configuration元素。你想:

xmldoc.SelectSingleNode("configuration/recordsDirectory") 

或通過根元素去:(或者你可以獲取所有後代元素調用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? 
} 
+0

謝謝@Jon Skeet –

2

嘗試在SelectSingleNode

這一個
XmlNode node = doc.SelectSingleNode("/configuration/recordsDirectory"); 
string s = node.InnerText.ToString(); 
1

喜要閱讀recordsDirectory標籤,你需要做的:

XmlDocument xmldoc = new XmlDocument(); 
      xmldoc.Load("C:/Users/yachna/Desktop/RCCM_TOOL/configRCCM.xml"); 
      string bvalue = xmldoc.SelectSingleNode("configuration/recordsDirectory").InnerText.ToString(); 

它將工作不完全