Linq如何实现XML转换

本篇文章给大家分享的是有关Linq如何实现XML转换,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

学习Linq时,经常会遇到Linq实现XML转换问题,这里将介绍Linq实现XML转换问题的解决方法。

Linq实现XML转换,将内存中的对象转换为XML

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

  1. class XMLTransform  

  2. {  

  3. static void Main()  

  4. {  

  5. // Create the data source by using a collection initializer.  

  6. List<Student> students = new List<Student>()  

  7. {  

  8. new Student {First="Svetlana"Last="Omelchenko"ID=111
    Scores = new List<int>{97, 92, 81, 60}},  

  9. new Student {First="Claire"Last="O’Donnell"ID=112
    Scores = new List<int>{75, 84, 91, 39}},  

  10. new Student {First="Sven"Last="Mortensen"ID=113
    Scores = new List<int>{88, 94, 65, 91}},  

  11. };  

  12.  

  13. // Create the query.  

  14. var studentsToXML = new XElement("Root",  

  15. from student in students  

  16. let x = String.Format("{0},{1},{2},{3}", student.Scores[0],  

  17. student.Scores[1], student.Scores[2], student.Scores[3])  

  18. select new XElement("student",  

  19. new XElement("First", student.First),  

  20. new XElement("Last", student.Last),  

  21. new XElement("Scores", x)  

  22. ) // end "student"  

  23. ); // end "Root"  

  24.  

  25. // Execute the query.  

  26. Console.WriteLine(studentsToXML);  

  27.  

  28. // Keep the console open in debug mode.  

  29. Console.WriteLine("Press any key to exit.");  

  30. Console.ReadKey();  

  31. }  

Linq实现XML转换,此代码生成下面的XML输出:

< Root>   <student>     <First>Svetlana</First>     <Last>Omelchenko</Last>     <Scores>97,92,81,60</Scores>   </student>   <student>     <First>Claire</First>     <Last>O'Donnell</Last>     <Scores>75,84,91,39</Scores>   </student>   <student>     <First>Sven</First>     <Last>Mortensen</Last>     <Scores>88,94,65,91</Scores>   </student> </Root>

以上就是Linq如何实现XML转换,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注行业资讯频道。