Reputation: 2041
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
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();
I hope it help you
Upvotes: 1
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