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.
According to your xml student can have several subjects. So, you need collection of subjects as property of student:
And here is parsing. To fill get student's subjects you need to do sub query:
BTW I think you can use simple string to hold subject name - you don't really need class for that.
since you have multiple subjects in xml
s_subject
should be alist
ofSubject