2015-06-29 117 views
-1

我有一個XML文件是這樣的:獲取的innerText

<locations> 
    <location country="UK"> 
     <name>London</name> 
     <class>Silver</class> 
    </location> 
    <location country="Germany"> 
     <name>Berlin II</name> 
     <class>Bronze</class> 
    </location> 
</locations> 

當打開一個網頁我扣除值「currentCountry」從URL。現在我想使用該值在XML文件中搜索相應的location條目,並將其子節點的innerHtml值放入變量中。這是我當前的代碼,這是至今沒有工作:

string currentCountry = "Germany" //For testing purposes 
string currentName = ""; 
string currentClass = ""; 

XmlDocument doc = new XmlDocument(); 
doc.Load("C:\\IIS\\Web\\Content\\locations.xml"); 

XmlNodeList xnList = doc.SelectNodes("/locations/location[@country='" + currentCountry + "']"); 
foreach (XmlNode xn in xnList) 
{ 
    currentName = xn.SelectSingleNode("/name").InnerText; 
    currentClass = xn.SelectSingleNode("/class").InnerText; 
} 

我得到的錯誤System.NullReferenceException: Object reference not set to an instance of an object.指向foreach循環中的第一道防線。

任何人都可以指出我正確的方向嗎?

回答

1

好的,只需使用currentName = xn["name"].InnerText;就行了。在這裏發帖後發現,它確實10秒:/

+1

所以你做了沒有研究,然後再發布? =( –

+0

我做了研究,被卡住了,發佈了我的問題,並繼續我的研究。很幸運,我在發佈這裏後偶然發現瞭解決方案。 – Konadi

2

刪除forwardslash,它應該只是罰款:

currentName = xn.SelectSingleNode("name").InnerText; 
       currentClass = xn.SelectSingleNode("class").InnerText; 
+0

我認爲我找到的解決方案更簡單,因爲它不需要另一選擇,但你的幫助是高度讚賞不管。謝謝 – Konadi

+0

它總是一種樂趣! – Oluwafemi