随机选择具有相同名称的XML节点

时间:2013-04-25 12:13:35

标签: c# xml random

我有这个XML文件:

<Main>
<QA>
    <question>What is your favorite color?</question>
    <!--pick random!-->
    <answer>Blue</answer>
    <answer>Red</answer>
    <answer>Green</answer>
    <answer>Yellow</answer>
</QA>

<QA>
    <question>What is your favorite programming language?</question>
    <!--pick random!-->
    <answer>PHP</answer>
    <answer>C#</answer>
    <answer>Java</answer>
    <answer>VB.Net</answer>
</QA>

我想当用户输入上面xml文件中指定的问题之一时,程序从节点中选择一个随机答案。 例如,当用户输入“您最喜欢的编程语言是什么?”时在TextBox中, 程序必须随机生成PHP,C#,Java或VB.Net。

这是我的代码,但不正确:

XmlDocument xml = new XmlDocument();
xml.Load("QA.xml");

XmlNodeList xList = xml.SelectNodes("Main/QA");
foreach (XmlNode xn in xList)
{
    string Question = xn["question"].InnerText;
    if (Question == txtQuestion.Text)
    {
        XmlNodeList answerlist = xml.SelectNodes("Main/QA/answer");
        foreach (XmlNode ans in answerlist)
        {
            Console.WriteLine(ans.InnerText);
        }
    }
}  

输出:

蓝 红色 绿色 黄色 PHP C# Java的 VB.Net

请帮忙。

2 个答案:

答案 0 :(得分:2)

使用Linq To Xml,

Random rnd = new Random();
var xDoc = XDocument.Load("QA.xml");

var question = xDoc.Descendants("QA")
                   .First(d => d.Element("question").Value == txtQ.Text);

var answer = question.Elements()
                     .Skip(rnd.Next(0, question.Elements().Count()))
                     .First().Value;

答案 1 :(得分:2)

试试这个:

XmlDocument xml = new XmlDocument();
xml.Load("QA.xml");

XmlNodeList xList = xml.SelectNodes("Main/QA");
foreach (XmlNode xn in xList)
{
    string Question = xn["question"].InnerText;
    if (Question == txtQuestion.Text)
    {
        XmlNodeList answerlist = xn.SelectNodes("./answer");
        foreach (XmlNode ans in answerlist
            .Cast<XmlNode>()
            .OrderBy(elem => Guid.NewGuid()))
        {
            Console.WriteLine(ans.InnerText);
        }
    }
}