Linq實現XML轉換淺談
作者:佚名
這里介紹Linq實現XML轉換,通過 LINQ 查詢,可以輕松地在內存中的數據結構、SQL 數據庫、ADO.NET 數據集和XML流或文檔之間轉換數據。
學習Linq時,經常會遇到Linq實現XML轉換問題,這里將介紹Linq實現XML轉換問題的解決方法。
Linq實現XML轉換,將內存中的對象轉換為XML
通過 LINQ 查詢,可以輕松地在內存中的數據結構、SQL 數據庫、ADO.NET 數據集和XML流或文檔之間轉換數據。下面的示例是Linq實現XML轉換,將內存中的數據結構中的對象轉換為XML元素。
- class XMLTransform
- {
- static void Main()
- {
- // Create the data source by using a collection initializer.
- List<Student> students = new List<Student>()
- {
- new Student {First="Svetlana", Last="Omelchenko", ID=111,
Scores = new List<int>{97, 92, 81, 60}},- new Student {First="Claire", Last="O’Donnell", ID=112,
Scores = new List<int>{75, 84, 91, 39}},- new Student {First="Sven", Last="Mortensen", ID=113,
Scores = new List<int>{88, 94, 65, 91}},- };
- // Create the query.
- var studentsToXML = new XElement("Root",
- from student in students
- let x = String.Format("{0},{1},{2},{3}", student.Scores[0],
- student.Scores[1], student.Scores[2], student.Scores[3])
- select new XElement("student",
- new XElement("First", student.First),
- new XElement("Last", student.Last),
- new XElement("Scores", x)
- ) // end "student"
- ); // end "Root"
- // Execute the query.
- Console.WriteLine(studentsToXML);
- // Keep the console open in debug mode.
- Console.WriteLine("Press any key to exit.");
- Console.ReadKey();
- }
- }
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>
【編輯推薦】
責任編輯:佚名
來源:
IT168