user763554
user763554

Reputation: 2041

How do I create a class from XML elements?

I have an anonymous type used in a Linq query and want to make this a class instead of anonymous type.

The fields are: Age and an XML node that has a couple of elements. How do I declare the class so that I can access the XML elements?

Here's the partially declared class:

class Student {
    int Age;
    // ??? What to use here for the XML node? XElement? 
}

Upvotes: 0

Views: 201

Answers (2)

Silagy
Silagy

Reputation: 3083

Maybe this is what you looking for..

To explain i have created an example..

I have created student class that look like this

   public class Student
{
    public int Age { get; set; }
    public string XmlData { get; set; }

    public Student()
    {

    }


}

I created Course class. this class will be initiate by the values from the xml

   public class Course
{
    public string Name { get; set; }
    public int Grade { get; set; }

    public Course()
    {

    }
}

now look the code...

Student student = new Student();
        student.Age = 120;
        student.XmlData = "<root><courses><course id='0'><name>Name a</name><grade>88</grade></course><course id='1'><name>Name a</name><grade>88</grade></course><course id='2'><name>Name a</name><grade>88</grade></course><course id='3'><name>Name a</name><grade>88</grade></course></courses></root>";

        XDocument doc = XDocument.Parse(student.XmlData);

        List<Course> coursesData = (from c in doc.Element("root").Element("courses").Elements("course")
                                   select new Course()
                                              {
                                                  Name = c.Element("name").Value,
                                                  Grade = Convert.ToInt16(c.Element("grade").Value)
                                              }).ToList();
  • create new instance of a student.
  • insert the value 120 for age
  • insert xml value to student.Xmldata parameter
  • create linq query and initiate list of courses

I hope it help you

Upvotes: 1

David Esteves
David Esteves

Reputation: 1604

From what I understand is you have some XML something like this:

<student>
    <age></age>
    <innerNode>
        <node1></node1>
        <node2></node2>
    <innerNode>
</student>

and you want to represent this in a c# class. I would suggest having 2 classes. 1 for the Student and then another for the innerNode.

In your Student class you will have the properties:

int Age { get; };
innerNodeClass Inner { get; }

Then you will be able to do Student.Inner.Node1.

Upvotes: 1

Related Questions