[翻译]LINQ Project: Unified Language Features for Object and Relational Queries(3)

Exercise 2 – LINQ to XML: LINQ for XML documents<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

LINQ to XML is an in-memory XML cache that takes advantage of the standard query operators and exposes a simplified way to create XML documents and fragments.

XML LINQ  是利用标准的查询运算符操作内存中的 XML,和公开一个简短方法创建 XML 文档和片断。

In this exercise, you learn how to read XML documents into the XDocument object, how to query elements from that object, and how to create documents and elements from scratch.

在本练习,您学习如何将 XML 文档读入 XDocument 对象、 如何从该对象查询元素以及如何从头开始创建文档和元素。

Task 1 – Adding LINQ to XML Support

1.  The project template used earlier takes care of adding references and using directives automatically.  In Solution Explorer, expand LINQ Overview | References and notice the System.Xml.Linq reference.  In Program.cs add the following directive to use the LINQ to XML namespace:

using System.Xml.Linq;

Task 2 – Querying by Reading in an XML File

For this task, you will query over a set of customers to find those that reside in London.  However as the set of customers increases, you are less likely to store that data in a code file; rather you may choose to store the information in a data file, such as an XML file.  Even though the data source is changing, the query structure remains the same. 

此任务中,您将查询通过一组客户以查找那些居住伦敦。  但是随着客户的增加,您不太可能在一个代码文件中存储该数据;您宁可选择一个数据文件存储信息,如 XML 文件。  即使数据源是更改,查询结构保持不变。

1.  This exercise uses the attached XML file.  Copy the Customers.xml file to the \bin\debug folder located in the current Project folder (by default this should be in   …\My Documents\Visual Studio 2008\Projects\ LINQ Overview\ LINQ Overview\bin\debug).  Change the CreateCustomer method to read the data in from the XML file:

 

static IEnumerable<Customer> CreateCustomers()

{

    return

        from c in XDocument.Load("Customers.xml")

            .Descendants("Customers").Descendants()

        select new Customer

        {

            City = c.Attribute("City").Value,

            CustomerID = c.Attribute("CustomerID").Value

        };

}  

 

2.  Press Ctrl+F5 to build and run the application.  Notice the output still only contains those customers that are located in London.  Now press any key to terminate the application.

 

Notice the query remains the same.  The only method that was altered was the CreateCustomers method.

注意该查询保持不变。  已更改的唯一方法是 CreateCustomers 方法。

Task 3 – Querying an XML File

This task shows how to query data in an XML file without first loading it into custom objects.  Suppose you did not have a Customer class to load the XML data into.  In this task you can query directly on the XML document rather than on collections as shown in Task 2. 

此任务演示如何从首先没有加载到自定义对象中XML 文件中查询数据。  假设您没有一个 加载XML 数据的Customer 类。  此任务中您可以直接从 XML 文档查询而不是任务 2 所示的集合。

1.  Add the following method XMLQuery that loads the xml document and prints it to the screen (also update Main to call the new method):

 

public static void XMLQuery()

{

    var doc = XDocument.Load("Customers.xml");

 

    Console.WriteLine("XML Document:\n{0}",doc);

}

 

static void Main(string[] args)

{

    XMLQuery();

}

 

2.  Press Ctrl+F5 to build and run the application.  The entire XML document is now printed to the screen.  Press any key to terminate the application. 

3.  Return to the XMLQuery method, and  now run the same query as before and print out those customers located in London. 

 

public static void XMLQuery()

{

    var doc = XDocument.Load("Customers.xml");

 

    var results = from c in doc.Descendants("Customer")

      where c.Attribute("City").Value == "London"

                  select c;

 

    Console.WriteLine("Results:\n");

    foreach (var contact in results)

        Console.WriteLine("{0}\n", contact);

}

 

4.  Press Ctrl+F5 to build and run the application.  The entire XML document isnow printed to the screen.  Press any key to terminate the application.

 

Move the mouse over either c or contact to notice that the objects returned from the query and iterated over in the foreach loop are no longer Customers (like they are in the ObjectQuery method).  Instead they are of type XElement.  By querying the XML document directly, there is no longer a need to create custom classes to store the data before performing a query.    

将鼠标移动 ccontact上后注意对象从查询返回的联系人并循环访问通过 foreach 循环中不再是Customers (就像它们是在 ObjectQuery 方法中)。  而替换是它们是XElement类型。  通过直接查询 XML 文档,在数据执行查询之前不再需要创建custom类存储 数据。

Task 4 – Transforming XML Output

This task walks though transforming the output of your previous query into a new XML document.

Suppose you wanted to create a new xml file that only contained those customers located in London.  In this task you write this to a different structure than the Customers.xml file; each customer element stores the city and name as descendent elements rather than attributes. 

此任务指导将您的以前查询结果转换成一个新的 XML 文档。假设您要创建一个只包含位于伦敦客户的新 xml 文件。  在此任务将写和Customers.xml 文件不同的结构 每个客户元素存储city name的子代元素而不是属性。

 

1.  Add the following code that iterates through the results and stores them in this new format.

public static void XMLQuery()

{

    XDocument doc = XDocument.Load("Customers.xml");

 

          var results = from c in doc.Descendants("Customer")

                        where c.Attribute("City").Value == "London"

                  select c;

    XElement transformedResults =

       new XElement("Londoners",

          from customer in results

          select new XElement("Contact",

             new XAttribute("ID", customer.Attribute("CustomerID").Value),

             new XElement("Name", customer.Attribute("ContactName").Value),

             new XElement("City", customer.Attribute("City").Value)));

 

    Console.WriteLine("Results:\n{0}", transformedResults);

}

 

Here a temporary variable, results, was used to store the information returned from the query before altering the structure of the returned data.  

此处临时变量,results,用于存储返回信息,它是从查询中返回更改之前的数据结构。

2.  Press Ctrl+F5 to build and run the application.  The new XML document is printed.  Notice the same data is returned, just structured differently.  Press any key to terminate the application.

3.  Save the output to a file allowing the results of the query to be exported.  To do this add the following line of code.

public static void XMLQuery()

{

    XDocument doc = XDocument.Load("Customers.xml");

 

          var results = from c in doc.Descendants("Customer")

                        where c.Attribute("City").Value == "London"

                  select c;

    XElement transformedResults =

       new XElement("Londoners",

          from customer in results

          select new XElement("Contact",

             new XAttribute("ID", customer.Attribute("CustomerID").Value),

             new XElement("Name", customer.Attribute("ContactName").Value),

             new XElement("City", customer.Attribute("City").Value)));

 

    Console.WriteLine("Results:\n{0}", transformedResults);

    transformedResults.Save("Output.xml");

}

4.  Press Ctrl+F5 to build and run the application.  The new XML document is printed to the screen and written to a file that can be located where you placed your Customers.xml file.  Now the data can be exported as XML to another application.  Last,  press any key to terminate the application.

转载于:https://www.cnblogs.com/pfengk/articles/965830.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值