C# 如何在Linq中通过属性获取元素的值
我是Linq的新手,所以很抱歉问了一个非常基本的问题 我有以下几种XMLC# 如何在Linq中通过属性获取元素的值,c#,xml,linq,xml-parsing,C#,Xml,Linq,Xml Parsing,我是Linq的新手,所以很抱歉问了一个非常基本的问题 我有以下几种XML <QuestionSet type="MCQ"> <Question> What will the output of following // main() // { // int x = 10, y = 15; // x = x++; // y = ++y; // printf("%d,
<QuestionSet type="MCQ">
<Question>
What will the output of following
// main()
// {
// int x = 10, y = 15;
// x = x++;
// y = ++y;
// printf("%d, %d", x, y);
// }
</Question>"
<Options>
<Option number="1">10, 15</Option>
<Option number="2">10, 16</Option>
<Option number="3">11, 15</Option>
<Option number="4">11, 16</Option>
</Options>
</QuestionSet>
下面的输出是什么
//main()
// {
//int x=10,y=15;
//x=x++;
//y=++y;
//printf(“%d,%d”,x,y);
// }
"
10, 15
10, 16
11, 15
11, 16
我想通过属性1、2、3和4来获取选项值。var d=new-XmlDocument();
var d = new XmlDocument();
d.LoadXml("yuor document text");
d.ChildNodes.OfType<XmlElement>().SelectMany(root => root.ChildNodes.OfType<XmlElement>().Where(x => x.Name == "Options").SelectMany(options => options.ChildNodes.OfType<XmlElement>().Select (option => option.Attributes["number"].Value))).Dump();
d、 LoadXml(“或文档文本”);
d、 ChildNodes.OfType().SelectMany(root=>root.ChildNodes.OfType().Where(x=>x.Name==“Options”).SelectMany(Options=>Options.ChildNodes.OfType().Select(option=>option.Attributes[“number”].Value)).Dump();
可能有点夸张。最好使用foreach或XPATH//options/option[“number”]-(XPATH查询可能错误)
这将返回集合中每个问题的匿名对象集合。所有选项都将位于以数字为键的字典中:
foreach (var question in questions)
{
Console.WriteLine(question.Question);
foreach (var option in question.Options)
Console.WriteLine("{0}: {1}", option.Key, option.Value);
// or ConsoleWriteLine(question.Options[2])
}
如果您只需要此特定xml中的选项:
var options = xdoc.Descendants("Option")
.ToDictionary(o => (int)o.Attribute("number"), o => (string)o);
Console.WriteLine(options[1]); // 10, 15
我尝试了以下方法…mcqTest=XElement.Load(SRI.Stream);var questionSet=来自mcqTest.Elements中的项(“问题集”)选择项;foreach(questionSet中的XElement-eachQuestion){IEnumerable rows=来自questionSet.substands中的行(“选项”)其中(字符串)行。属性(“编号”)=“2”选择行;
var options = xdoc.Descendants("Option")
.ToDictionary(o => (int)o.Attribute("number"), o => (string)o);
Console.WriteLine(options[1]); // 10, 15