c# - 从 linq to xml 中只选择一个随机节点

标签 c# xml linq var

我有一个 XML 文件,我只想选择一个随机节点。好像我快到了,但是带有 var 的 foreach 正在循环。如何只选择一个节点并返回?

XML:

<human_check>
  <qa>
    <q>2 + 2</q>
    <a>4</a>
  </qa>
  <qa>
    <q>1 + 2</q>
    <a>3</a>
  </qa>
  <qa>
    <q>6 + 3</q>
    <a>9</a>
  </qa>
  <qa>
    <q>3 + 5</q>
    <a>7</a>
  </qa>
</human_check>

C#

public class human_check
{

    public static string get_q()
    {
        try
        {
            string h = string.Empty;
            Random rnd = new Random();
            XDocument questions = XDocument.Load(@"C:\Users\PETERS\Desktop\human_check.xml");
            var random_q = from q in questions.Descendants("qa")
                           select new
                           {
                               question = q.Descendants("q").OrderBy(r => rnd.Next()).First().Value
                           };

            foreach (var rq in random_q)
            {
                h = rq.question.ToString();
            }

            return h;

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

}

提前致谢

EP

最佳答案

无需设置顺序,您只需选择一个随机元素即可。

var qas = questions.Descendants("qa");
int qaCount = qas.Count();
h = qas.ElementAt(rnd.Next(0, qaCount - 1)).Element("q").Value;

关于c# - 从 linq to xml 中只选择一个随机节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12487763/

相关文章:

c# - 如何从 wcf ksoap2 响应中填充字典

c# - 为什么在使用 Entity Framework 实现存储库模式时使用接口(interface)?

java - JAXB - 使用 XML 字符串字段编码 java 对象

c# - Entity Framework 中的 Linq 嵌套投影

c# - 通过GroupBy求Max值抛出Sequence不包含元素异常

c# - 找不到 C# 程序集中的 Ghostscript 调用

c# - 仅在第一次使用 Azure Function HttpTrigger 从主题获取消息时使用 MessageReceiver

c# - 按两个值对我的类(class)进行排序

xml - 是否可以流解析XML父元素而不解析其子元素?

java - 获取一个 XML 文件和一个 XSL 文件并从中生成一个 HTML 字符串?