LINQ to XML 概觀 (C#)LINQ to XML Overview (C#)

LINQ to XML 提供運用 .NET Language-Integrated Query (LINQ) Framework 的記憶體中 XML 程式開發介面。LINQ to XML provides an in-memory XML programming interface that leverages the .NET Language-Integrated Query (LINQ) Framework. LINQ to XML 會使用 .NET 功能,而且相當於更新的、重新設計的文件物件模型 (DOM) XML 程式發展介面。LINQ to XML uses .NET capabilities and is comparable to an updated, redesigned Document Object Model (DOM) XML programming interface.

XML 已被廣泛採用為格式化許多內容之資料的方式。XML has been widely adopted as a way to format data in many contexts. 例如,您可以在 Web、組態檔、Microsoft Office Word 檔案與資料庫中發現 XML。For example, you can find XML on the Web, in configuration files, in Microsoft Office Word files, and in databases.

LINQ to XMLLINQ to XML 是經過重新設計,用以進行 XML 程式設計的最新方法。is an up-to-date, redesigned approach to programming with XML. 它提供文件物件模型 (DOM) 的記憶體中文件修改能力,而且支援 LINQLINQ 查詢運算式。It provides the in-memory document modification capabilities of the Document Object Model (DOM), and supports LINQLINQ query expressions. 雖然這些查詢運算式在語法上與 XPath 不同,但是它們會提供類似的功能。Although these query expressions are syntactically different from XPath, they provide similar functionality.

LINQ to XML 開發人員LINQ to XML Developers

LINQ to XMLLINQ to XML 的目標為各種開發人員。targets a variety of developers. 對於只想要完成某些事情的一般開發人員而言,LINQ to XMLLINQ to XML 會提供類似 SQL 的查詢經驗,讓 XML 更容易。For an average developer who just wants to get something done, LINQ to XMLLINQ to XML makes XML easier by providing a query experience that is similar to SQL. 只要稍微研究,程式設計人員就可以學會如何以自己選擇的程式語言來撰寫簡潔而且功能強大的查詢。With just a bit of study, programmers can learn to write succinct and powerful queries in their programming language of choice.

專業開發人員可以使用 LINQ to XMLLINQ to XML 大量增加其產能。Professional developers can use LINQ to XMLLINQ to XML to greatly increase their productivity. 他們可以利用 LINQ to XMLLINQ to XML 撰寫更明確、更精簡而且功能更強大的較少程式碼。With LINQ to XMLLINQ to XML, they can write less code that is more expressive, more compact, and more powerful. 他們可以同時使用多個資料網域的查詢運算式。They can use query expressions from multiple data domains at the same time.

何謂 LINQ to XML?What Is LINQ to XML?

LINQ to XMLLINQ to XML 是一個啟用 LINQ 的記憶體內部 XML 程式設計介面,可讓您從 .NET Framework 程式設計語言內使用 XML。is a LINQ-enabled, in-memory XML programming interface that enables you to work with XML from within the .NET Framework programming languages.

LINQ to XMLLINQ to XML 如同文件物件模型 (DOM),它會將 XML 文件帶到記憶體中。is like the Document Object Model (DOM) in that it brings the XML document into memory. 您可以查詢與修改文件,並在修改後儲存到檔案,或將其序列化並透過網際網路傳送。You can query and modify the document, and after you modify it you can save it to a file or serialize it and send it over the Internet. 不過,LINQ to XMLLINQ to XML 與 DOM 不同:它所提供的新物件模型較為輕量且較容易使用,且會利用 C# 中的語言功能。However, LINQ to XMLLINQ to XML differs from DOM: It provides a new object model that is lighter weight and easier to work with, and that takes advantage of language features in C#.

LINQ to XMLLINQ to XML 最重要的優點為其與 Language-Integrated Query (LINQ)Language-Integrated Query (LINQ) 的整合能力。The most important advantage of LINQ to XMLLINQ to XML is its integration with Language-Integrated Query (LINQ)Language-Integrated Query (LINQ). 這種整合可讓您在記憶體中 XML 文件上撰寫查詢以擷取項目和屬性的集合。This integration enables you to write queries on the in-memory XML document to retrieve collections of elements and attributes. LINQ to XMLLINQ to XML 的查詢功能相當於 (雖然語法上不同) XPath 和 Xquery 的功能。The query capability of LINQ to XMLLINQ to XML is comparable in functionality (although not in syntax) to XPath and XQuery. 整合 C# 中的 LINQLINQ 時,可提供更強的型別、編譯時間檢查功能,以及改善的偵錯工具支援。The integration of LINQLINQ in C# provides stronger typing, compile-time checking, and improved debugger support.

LINQ to XMLLINQ to XML 的另一項優點是將查詢結果當做 XElementXAttribute 物件建構函式參數的功能,可提供建立 XML 樹狀結構的強大方法。Another advantage of LINQ to XMLLINQ to XML is the ability to use query results as parameters to XElement and XAttribute object constructors enables a powerful approach to creating XML trees. 此方法稱為「功能建構」,可讓開發人員輕鬆將 XML 樹狀結構從某種圖形轉換為另一種圖形。This approach, called functional construction, enables developers to easily transform XML trees from one shape to another.

例如,您可能有一個典型的 XML 訂購單,如以下連結所述:XML 範例檔:典型訂購單 (LINQ to XML)For example, you might have a typical XML purchase order as described in Sample XML File: Typical Purchase Order (LINQ to XML). 您可以使用 LINQ to XMLLINQ to XML 執行下列查詢,以便在採購訂單中取得每個項目的零件編號屬行值:By using LINQ to XMLLINQ to XML, you could run the following query to obtain the part number attribute value for every item element in the purchase order:

// Load the XML file from our project directory containing the purchase orders
var filename = "PurchaseOrder.xml";
var currentDirectory = Directory.GetCurrentDirectory();
var purchaseOrderFilepath = Path.Combine(currentDirectory, filename);

XElement purchaseOrder = XElement.Load(purchaseOrderFilepath);

IEnumerable<string> partNos =  from item in purchaseOrder.Descendants("Item")
                               select (string) item.Attribute("PartNumber");

這可以用方法語法的形式改寫:This can be rewritten in method syntax form:

IEnumerable<string> partNos = purchaseOrder.Descendants("Item").Select(x => (string) x.Attribute("PartNumber"));

另一個範例是,您可能會想要一份值大於 $100 之項目的清單 (以零件編號排序)。As another example, you might want a list, sorted by part number, of the items with a value greater than $100. 若要取得此資訊,您可以執行下列查詢:To obtain this information, you could run the following query:

// Load the XML file from our project directory containing the purchase orders
var filename = "PurchaseOrder.xml";
var currentDirectory = Directory.GetCurrentDirectory();
var purchaseOrderFilepath = Path.Combine(currentDirectory, filename);

XElement purchaseOrder = XElement.Load(purchaseOrderFilepath);

IEnumerable<XElement> pricesByPartNos =  from item in purchaseOrder.Descendants("Item")
                                 where (int) item.Element("Quantity") * (decimal) item.Element("USPrice") > 100
                                 orderby (string)item.Element("PartNumber")
                                 select item;

同樣地,這可以用方法語法的形式改寫:Again, this can be rewritten in method syntax form:

IEnumerable<XElement> pricesByPartNos = purchaseOrder.Descendants("Item")
                                        .Where(item => (int)item.Element("Quantity") * (decimal)item.Element("USPrice") > 100)
                                        .OrderBy(order => order.Element("PartNumber"));

除了這些 LINQLINQ 功能以外,LINQ to XMLLINQ to XML 還提供了改善的 XML 程式設計介面。In addition to these LINQLINQ capabilities, LINQ to XMLLINQ to XML provides an improved XML programming interface. 利用 LINQ to XMLLINQ to XML,您可以:Using LINQ to XMLLINQ to XML, you can:

  • 檔案資料流載入 XML。Load XML from files or streams.

  • 將 XML 序列化為檔案或資料流。Serialize XML to files or streams.

  • 使用功能結構從頭開始建立 XML。Create XML from scratch by using functional construction.

  • 使用類似 XPath 的座標軸查詢 XML。Query XML using XPath-like axes.

  • 使用 AddRemoveReplaceWithSetValue 之類的方法管理記憶體中 XML 樹狀結構。Manipulate the in-memory XML tree by using methods such as Add, Remove, ReplaceWith, and SetValue.

  • 使用 XSD 驗證 XML 樹狀結構。Validate XML trees using XSD.

  • 使用這些功能的組合,將 XML 樹狀結構從一個組織結構轉換為另一個組織結構。Use a combination of these features to transform XML trees from one shape into another.

建立 XML 樹狀結構Creating XML Trees

使用 LINQ to XMLLINQ to XML 進行程式設計其中一項最重要的優點是,建立 XML 樹狀結構很容易。One of the most significant advantages of programming with LINQ to XMLLINQ to XML is that it is easy to create XML trees. 例如,若要建立小型 XML 樹狀結構,您可以使用下列方式來撰寫程式碼:For example, to create a small XML tree, you can write code as follows:

XElement contacts =
new XElement("Contacts",
    new XElement("Contact",
        new XElement("Name", "Patrick Hines"),
        new XElement("Phone", "206-555-0144",
            new XAttribute("Type", "Home")),
        new XElement("phone", "425-555-0145",
            new XAttribute("Type", "Work")),
        new XElement("Address",
            new XElement("Street1", "123 Main St"),
            new XElement("City", "Mercer Island"),
            new XElement("State", "WA"),
            new XElement("Postal", "68042")
        )
    )
);

如需詳細資訊,請參閱建立 XML 樹狀結構 (C#)For more information, see Creating XML Trees (C#).

另請參閱See also