首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SelectSingleNode的问题

SelectSingleNode的问题
EN

Stack Overflow用户
提问于 2017-01-29 18:30:19
回答 1查看 84关注 0票数 0

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

我使用这段代码:

代码语言:javascript
复制
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:

代码语言:javascript
复制
<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的方式上。我在这句话中有没有犯错,或者这是我的一些更大的误解?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-01-29 18:33:54

代码语言:javascript
复制
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);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41919885

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档