2017-01-29 88 views
0

我的計劃是使用下面的XML隨機選擇一個event節點,然後將每個choice節點的一些節點分配給字符串(每個事件最終會有更多choice節點)。然而,在我完成所有選擇之前,我遇到了一個障礙。問題與SelectSingleNode

我使用這段代碼:

XmlDocument xmlDoc = new XmlDocument(); 
xmlDoc.Load("XMLFile1.xml"); 
XmlNode mainNode = xmlDoc.SelectSingleNode("events"); 

XmlNodeList nodeList = mainNode.ChildNodes; 
int random = Program.rand.Next(0, nodeList.Count); 

XmlNode optionNode = mainNode.SelectSingleNode(string.Format("event[@id='{0}']", random)); 
Console.WriteLine(mainNode.InnerText); 
Console.WriteLine(optionNode.InnerText); 

這會導致NullReferenceException的最後一行。

這裏是XML:

<events> 
    <event id="333"> 
     <name>Test event 1</name> 
     <text>Something something</text> 
    <choices> 
     <choice id="1"> 
      <choicebutton>Button 1 from choice 1</choicebutton> 
      <choiseresulttext>Something happened</choiseresulttext> 
     </choice> 
     <choice id="2"> 
      <choicebutton>Button 2 from choice 1</choicebutton> 
      <choiseresulttext>Something else happened</choiseresulttext> 
     </choice> 
    </choices> 
</event> 
<event id="2"> 
    <name>Test event 2</name> 
    <text>Something something more</text> 
    <choices> 
     <choice id="1"> 
      <choicebutton>Button 1 from choice 2</choicebutton> 
      <choiseresulttext>Something happened</choiseresulttext> 
     </choice> 
     <choice id="2"> 
      <choicebutton>Button 2 from choice 2</choicebutton> 
      <choiseresulttext>Something else happened</choiseresulttext> 
     </choice> 
    </choices> 
</event> 

Console.WriteLine(mainNode.InnerText);行執行得當,所以我想這個問題是我的節點分配給optionNode的方式。我在這份聲明中犯了什麼錯誤,還是這是我的一些更大的誤解?

+0

'nodeList.Count - 1' –

+0

第一事件具有ID 333.如果你正在使用從0隨機ID來計算事件的 –

+0

感謝您指出我的愚蠢應該從ID =「0」開始,@ SergeyBerezovskiy。 :) – Weathervane

回答

0
XmlDocument xmlDoc = new XmlDocument(); 
xmlDoc.Load("XMLFile1.xml"); 
XmlNode mainNode = xmlDoc.SelectSingleNode("events"); 

XmlNodeList nodeList = mainNode.ChildNodes; 
int random = Program.rand.Next(0, nodeList.Count - 1); 

XmlNode optionNode = nodeList[random]; 
Console.WriteLine(mainNode.InnerText); 
Console.WriteLine(optionNode.InnerText);