Linq實現(xiàn)XML轉(zhuǎn)換淺談
學(xué)習(xí)Linq時,經(jīng)常會遇到Linq實現(xiàn)XML轉(zhuǎn)換問題,這里將介紹Linq實現(xiàn)XML轉(zhuǎn)換問題的解決方法。
Linq實現(xiàn)XML轉(zhuǎn)換,將內(nèi)存中的對象轉(zhuǎn)換為XML
通過 LINQ 查詢,可以輕松地在內(nèi)存中的數(shù)據(jù)結(jié)構(gòu)、SQL 數(shù)據(jù)庫、ADO.NET 數(shù)據(jù)集和XML流或文檔之間轉(zhuǎn)換數(shù)據(jù)。下面的示例是Linq實現(xiàn)XML轉(zhuǎn)換,將內(nèi)存中的數(shù)據(jù)結(jié)構(gòu)中的對象轉(zhuǎn)換為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實現(xiàn)XML轉(zhuǎn)換,此代碼生成下面的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>
【編輯推薦】