我正在尝试解析XML文件,并以所需的格式获得一些输出。
这是我的XML文件格式。
<?xml version="1.0" encoding="utf-8" ?>
<Sample>
<Student name="Tom" id="0" batch="1">
<Performance>
<Previous id="1">Marks 1</Previous>
<Next mid="2">Marks 2</Next>
<Next mid="3">Marks 3</Next>
</Performance>
</Student>
<Student name="Jerry" id="1" batch="1">
<Previous mid="1">Marks 4</Previous>
<Next mid="2">Marks 5</Next>
<Next mid="3">Marks 6</Next>
<Next mid="4">Marks 12</Next>
</Student>
<Student name="Kate" id="5" batch="2">
<Previous mid="2">Marks 7</Previous>
<Previous mid="3">Marks 8</Previous>
<Next mid="4">Marks 6</Next>
</Student>
</Sample>
我想要获得的输出是来自此XML文件的字典:
0 - Collecion of (Previous and Next Marks)
1 - Collecion of (Previous and Next Marks)
5 - Collecion of (Previous and Next Marks)
其中0,1,5是学生的ID,相应地是该学生的标记集合。
为此,我写了这个查询,它并没有给我输出:
更新(已添加查询)
XDocument xdoc = XDocument.Load("XMLfile1.xml");
var content = xdoc.Descendants("Student")
.Select(st => st.Descendants("Previous")
.Union(st.Descendants("Next"))
.Select(terms => new Marks { MarksId = terms.Attribute("mid").Value, MarksName = terms.Value })).ToDictionary<Marks, int>(key => key.StudentId) ;
问题:
1.我无法选择学生节点的Attribute
ID
2.我无法使用key => key.StudentID
选择使用字典的密钥,并且它会产生一些错误。
我在这里用来解析的类文件:
class Marks
{
public int StudentID
{
get;
set;
}
public string MarksId
{
get;
set;
}
public string MarksName
{
get;
set;
}
答案 0 :(得分:2)
检查一下:
var dictionary = (from student in xElement.Descendants("Student")
let marks = student.Descendants()
.Where(e => new []{"Previous" ,"Next"}
.Contains(e.Name.ToString()))
select new {student, marks})
.ToDictionary(t => t.student.Attribute("id").Value,
t => t.marks.Select(mark => new Data {
MarkId = mark.Attribute("mid").Value,
MarkName = mark.Value
}).ToList());
请注意,您的XML可能有错误:
而不是<Previous id="1">Marks 1</Previous>
应该有<Previous mid="1">Marks 1</Previous>