0

I have following xml file. I want to parse it without Serilization in C#.

<StudentList>
<StudentCount>5</StudentCount>
<Student>
    <Id>1</Id>
    <Name>Abc</Name>
</Student>
<Student>
    <Id>2</Id>
    <Name>Efg</Name>
</Student>
<Student>
    <Id>3</Id>
    <Name>Ghi</Name>
</Student>
<Student>
    <Id>4</Id>
    <Name>Jkl</Name>
</Student>
<Student>
    <Id>5</Id>
    <Name>Mno</Name>
</Student>
</StudentList>

I want to store above xml data in List of Student class

List<Student>

Class Student
{
    public int Id = 0;
    public string Name = "";
}

Here i also want a Xpath of each value node For Ex :

StudentList\StudentCount
StudentList\Student\Id
StudentList\Student\Name

Please help me How do i achieve this???

pravprab
  • 2,301
  • 3
  • 26
  • 43
Vimesh Shah
  • 129
  • 2
  • 15

2 Answers2

1

Try to parse the .xml using LINQ (check LINQ to read XML for an example on how to do this). You should be able to implement your other requirements from there - try it yourself and ask for help if you get stuck while coding :)

Community
  • 1
  • 1
H W
  • 2,556
  • 3
  • 21
  • 45
1

Quick solution to get you started:

Create an XElement:

    XElement studentXml = XElement.Parse (
    @"<StudentList>
    <StudentCount>5</StudentCount>
    <Student>
        <Id>1</Id>
    <Name>Abc</Name>
    </Student>
    <Student>
        <Id>2</Id>
        <Name>Efg</Name>
    </Student>
    <Student>
        <Id>3</Id>
        <Name>Ghi</Name>
    </Student>
    <Student>
        <Id>4</Id>
    <Name>Jkl</Name>
    </Student>
    <Student>
        <Id>5</Id>
    <Name>Mno</Name>
    </Student>
    </StudentList>");

..And select from it:

var students = 
    studentXml
        .Descendants()
        .Where(node => node.Name == "Student")
        .Select(node => 
                 new Student {
                   Id = int.Parse(node.Descendants()
                                      .First(item => item.Name == "Id")
                                      .Value), 
                   Name = node.Descendants()
                                      .First(item => item.Name == "Name")
                                      .Value
                 });
Kjartan
  • 18,591
  • 15
  • 71
  • 96