LINQ to XML除了支援利用XSLT樣式表來轉換XML文件這種標準作法之外,還有另一種選擇:利用LINQ to XML的功能結構(Functional construction) 技術來進行轉換。例如你有一份XML文件如下:

利用功能結構(Functional construction)技術將其轉換為以下格式:

為了達到此目標所使用的步驟如下:
1. 建立一個Console程式。
2. 加入以下命名空間:
1 using System.Xml.Linq;
2 using System.Xml;
3 using System.Xml.Xsl;
3. 在Main方法之中加入以下程式:
1 XDocument doc =
2 new XDocument(
3 new XElement("Employees" , 4 new XElement("Employee" , 5 new XAttribute("id" , "1") , 6 new XElement("Name" , "Vivid Hsu") , 7 new XElement("Department" , "SD")) , 8 new XElement("Employee" , 9 new XAttribute("id" , "2") , 10 new XElement("Name" , "Mary Wang") , 11 new XElement("Department" , "SE")) 12 ));
13
14 Console.WriteLine("原始文件==========="); 15 Console.WriteLine(doc.ToString());
16 doc.Save("EmployeesBefore.xml"); 17 Console.WriteLine();
18 Console.WriteLine("新文件:============"); 19 XDocument docNew = new XDocument(
20 new XElement("員工清單" , 21 doc.Element("Employees") 22 .Elements("Employee") 23 .Select(b => new XElement("員工" , 24 new XAttribute("員工編號" , (int)b.Attribute("id")) , 25 new XAttribute("名稱" , (string)b.Element("Name")) , 26 new XAttribute("部門" , (string)b.Element("Department")) 27 ))));
28
29 Console.WriteLine(docNew.ToString());
30 docNew.Save("Employees.xml");
程式說明分解如下:
- 1-12行先利用XDocument建立原始XML檔案。
- 14-16行將建立的XML文件印出到主控台,並將之儲存成檔案。
- 19行建立一個新的XDocument來處理轉換的過程。
- 20行建立新XML文件的根節點「員工清單」。
- 21-23行建立「員工清單」標籤之中的「員工」元素,為了將來源XML文件中的Employee元素轉換成「員工」,程式之中利用Select運算子來處理。
- 24行將「id」代換成「員工編號」。
- 25-26行將「Name」與「Department」代換成「名稱」與「部門」。
- 29行將產生的新XML印到主控台。
- 30行將產生的新XML儲存成一個檔案。