我的计划是使用下面的XML随机选择一个event节点,然后将每个choice节点的一些节点分配给字符串(最终,每个事件中将有更多的choice节点)。然而,在我浏览所有的选择之前,我遇到了一个障碍。
我使用这段代码:
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的方式上。我在这句话中有没有犯错,或者这是我的一些更大的误解?
发布于 2017-01-29 18:33:54
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);https://stackoverflow.com/questions/41919885
复制相似问题