我有一个问题来解析多个XML字段
这是XML的风格:
<students>
<student>
<student_id>1</student_id>
<student_name>Mike</student_name>
<subjects>
<subject>
<school_subject>History</school_subject>
</subject>
<subject>
<school_subject>Maths</school_subject>
</subject>
<subject>
<school_subject>English</school_subject>
</subject>
</subjects>
</student>
<student>
...
</student>
</students>
我可以解析像student_id和student_name这样的简单字段,但是当同一字段有多次重复时,我不知道该怎么做:/ 这是我解析的源代码。
我做了两节课:
现在源代码:
List<Student> L1 = new List<Student>();
XDocument doc = XDocument.Load(s);
var q = from b in doc.Descendants("student")
select new
{
s_id = (string)b.Element("student_id"),
s_name = (string)b.Element("student_name"),
s_subject = (Subject)b.Elements("school_subject")
};
foreach (var p in q)
{
L1.Add(new Student() { id = p.s_id, name = p.s_name, subject = p.s_subject });
}
listBox1.ItemsSource = L1;
感谢您阅读并抱歉我的英语非常糟糕。
答案 0 :(得分:5)
根据你的xml学生可以有几个科目。因此,您需要收集作为学生财产的科目:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public List<Subject> Subjects { get; set; }
}
public class Subject
{
public string Name { get; set; }
}
这是解析。要填写学生的科目,您需要进行子查询:
XDocument xdoc = XDocument.Load(s);
IEnumerable<Student> students =
from s in xdoc.Descendants("student")
select new Student()
{
Id = (int)s.Element("student_id"), // you can cast to int
Name = (string)s.Element("student_name"),
Subjects = s.Element("subjects") // here goes sub query
.Elements("subject")
.Select(subj => new Subject() {
Name = (string)subj.Element("school_subject")
}).ToList()
};
BTW我认为你可以用简单的字符串来保存主题名称 - 你真的不需要上课。
答案 1 :(得分:0)
因为您在xml中有多个主题s_subject
应该是list
Subject
doc.Elements("Student").Select(
x=>
s_id = (string)x.Element("student_id"),
s_name = (string)x.Element("student_name"),
s_subject = x.Element("subjects").Elements("subject")
.Select(s=>s.Element("school_subject").Value)
.ToList<Subject>()
);