class Program
{
class Student
{
public int SID { get; set; }
public string Name { get; set; }
public string Major { get; set; }
public List<SubjGrade> SubjectGrades { get; set; }
}
class SubjGrade
{
public string Subject { get; set; }
public decimal grade { get; set; }
}
static List<Customer> LoadCustomers(string file) {}
static void Main(string[] args)
{
var Students = LoadStudents(@"C:\Users\Chris\Documents\Students.txt");
var studXML =
new XElement("Root",
from student in Students
select new XElement("Student",
new XElement("SID",student.SID),
new XElement("Name",student.Name),
new XElement("Major",student.Major)
// ????
// I cannot figure out how to create XElements
// for the SubjGrade list
) // end student
); // end root
Console.WriteLine(studXML);
// this test works just fine but not what i am trying achive
IEnumerable<Student> studs = from student in Students select student;
foreach (var s in studs)
{
Console.WriteLine("{0} {1}\t{2}",
s.SID.ToString(), s.Name, s.Major);
Console.WriteLine("Class Cnt: {0}",
s.SubjectGrades.Count.ToString());
foreach (var g in s.SubjectGrades)
{
Console.WriteLine("\t{0}\t{1}",
g.Subject, g.grade.ToString());
}
}
}
答案 0 :(得分:3)
这样您就可以在Student元素下创建多个Grade元素。
var studXML =
new XElement("Root",
from student in Students
select new XElement("Student",
new XElement("SID", student.SID),
new XElement("Name", student.Name),
new XElement("Major", student.Major),
new XElement("Grades",
from subjectGrade in student.SubjectGrades
select new XElement("Grade",
new XElement("Subject", subjectGrade.Subject),
new XElement("Grade", subjectGrade.grade)))
) // end student
); // end root
Console.WriteLine(studXML);
请注意,这并不能防止SubjectGrades为空。