具有嵌套循环的Linq XML查询

时间:2012-05-07 19:52:13

标签: c# xml linq

我想阅读下面的XML并按以下顺序打印输出。你能帮忙查询一下吗?

enter image description here

10 Subject1 A1 10主题2 B1 10主题3 C1 20主题1 B2 20主题2 A1 20 Subject3 C2

提前致谢

1 个答案:

答案 0 :(得分:0)

这是一个如何以您想要的形式查询的示例:

XDocument doc = XDocument.Load("test.xml");
var query = from l in doc.Descendants("L1")
            let id = l.Attribute("id").Value
            from subject in l.Descendants("Subject")
            select new
            {
                Id = id,
                SubjectName = (string)subject.Attribute("SubjectName"),
                Score = (string)subject.Attribute("Score")
            };

foreach (var result in query)
{
    Console.WriteLine(result);
}

<强>输出:

{ Id = 10, SubjectName = Subject1, Score = A1 }
{ Id = 10, SubjectName = Subject2, Score = B1 }
{ Id = 10, SubjectName = Subject3, Score = C1 }
{ Id = 20, SubjectName = Subject1, Score = B2 }
{ Id = 20, SubjectName = Subject2, Score = A1 }
{ Id = 20, SubjectName = Subject3, Score = C2 }