问题
I have a probleme to parse multiple XML field
This a the style of the 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>
I can parse it for the simple field like student_id and student_name but when there are multiple repetition of a same field I don't know how to do :/ This is my source code of the parsing.
I made two classes :
- Subject containing the name of the school subject
- student containing id and name and a list of class Subject.
Now the source code :
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;
Thanks for reading and sorry for my very bad english.
回答1:
According to your xml student can have several subjects. So, you need collection of subjects as property of student:
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; }
}
And here is parsing. To fill get student's subjects you need to do sub query:
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 I think you can use simple string to hold subject name - you don't really need class for that.
回答2:
since you have multiple subjects in xml s_subject
should be a list
of 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>()
);
来源:https://stackoverflow.com/questions/13904414/parsing-xml-with-linq-with-multiple-descendants