(010):将内存中的对象转换为XML

前端之家收集整理的这篇文章主要介绍了(010):将内存中的对象转换为XML前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。


视频演示:http://u.115.com/file/f24db1fdfa

通过 LINQ 查询,可以轻松地在内存中的数据结构、sql 数据库、ADO.NET 数据集和 XML 流或文档之间转换数据。下面的示例将内存中的数据结构中的对象转换为 XML 元素。

List<Student> Students = new List<Student>()
{
    new Student {
        FirstName="Svetlana",LastName="Omelchenko",ID=111,scores = new List<int>{97,92,81,60}},new Student {
        FirstName="Claire",LastName="O’Donnell",ID=112,scores = new List<int>{75,84,91,39}},new Student {
        FirstName="Sven",LastName="Mortensen",ID=113,scores = new List<int>{88,94,65,91}},};

// Create the query.
var StudentsToXML = new XElement("Root",from student in Students
    let scoreString = String.Format("{0},{1},{2},{3}",student.scores[0],student.scores[1],student.scores[2],student.scores[3])
    select new XElement("Student",new XElement("FirstName",student.FirstName),new XElement("LastName",student.LastName),new XElement("scores",scoreString)
            ) 
        );

// Execute the query.
Console.WriteLine(StudentsToXML);

// Keep the console open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();

代码生成下面的 XML 输出

<Root>
  <Student>
    <FirstName>Svetlana</FirstName>
    <LastName>Omelchenko</LastName>
    <scores>97,60</scores>
  </Student>
  <Student>
    <FirstName>Claire</FirstName>
    <LastName>O’Donnell</LastName>
    <scores>75,39</scores>
  </Student>
  <Student>
    <FirstName>Sven</FirstName>
    <LastName>Mortensen</LastName>
    <scores>88,91</scores>
  </Student>
</Root>
原文链接:https://www.f2er.com/xml/299439.html

猜你在找的XML相关文章