SelectSingleNode

时间:2017-01-29 10:30:19

标签: c# xml

我的计划是使用下面的XML随机选择一个event节点,然后将每个choice节点的一些节点分配给字符串(最终会更多{{ 1}}每个事件中的节点)。然而,在我完成所有选择之前,我遇到了麻烦。

我使用这段代码:

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

这是XML:

NullReferenceException

<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);的方式有关。我在这个陈述中是否犯了错误,或者这对我有什么更大的误解?

1 个答案:

答案 0 :(得分: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);