Tải bản đầy đủ - 0 (trang)
6-15. Query XML with LINQ

6-15. Query XML with LINQ

Tải bản đầy đủ - 0trang

CHAPTER 6 ■ XML PROCESSING



Solution

Use the XML tree as the data source for a LINQ query.



How It Works

The System.Xml.Linq.XElement class is a valid data source for LINQ queries. The basic sequence for

querying an XML tree is the same as the one we used in Chapter 2 when querying a collection:

1.



Start a new LINQ query using the from keyword, providing a variable name that

you will use to make selections (for example, from element in

root.Elements()).



2.



Identify the conditions to use in selecting elements with the where keyword.



3.



Indicate what value will be added to the result set from each matching element

using the select keyword.



4.



Specify the way in which you wish the results to be sorted using the orderby

keyword.



When using XElement as the LINQ source, the result is an IEnumerable of XElements, containing those

elements from your XML tree that match your search criteria. LINQ queries can be written using the

keywords that have been added to C# (from, where, select, etc.), or by using instance methods that fulfill

the same purpose—in the case of XElement, you should call the Elements instance method to obtain an

IEnumerable to use as the basis for your queries.

To select an element, you use the properties and methods of the XElement class. For example, to find

all elements in an XML tree that have an attribute color with value blue, you would call

from element in root.Elements() where (string)element.Attribute("color")

== "blue" select element;

To achieve the same result using instance methods, you would call

root.Elements().Where(e => (string)e.Attribute("color") == "blue").Select(e => e);

The result type from a LINQ query depends on what kind of element you retrieve with the select

keyword, but will always return an instance of IEnumerable, which you can use in a foreach loop to run

through the matched elements, or as the basis for further LINQ queries. The preceding example calls

(which are functionally equivalent) return an IEnumerable. If you use the select keyword to

obtain a value representing a characteristic of an element, such as an attribute value, then the generic

type of IEnumerable will be different.



The Code

The following example loads an XML tree from the file store.xml, which is included in the sample code.

Elements that are named Products and that have a value of 16 for the child element CategoryID are

selected, and the value of the ModelName child element is printed out. The query is performed once using

the LINQ keywords and again using the instance methods and lambda expressions—it is a matter of

preference as to which technique you adopt.



301



www.it-ebooks.info



CHAPTER 6 ■ XML PROCESSING



using

using

using

using

using



System;

System.Collections.Generic;

System.Linq;

System.Text;

System.Xml.Linq;



namespace Recipe06_15

{

class Recipe06_15

{

static void Main(string[] args)

{

// Load the XML tree from the sample file.

XElement rootElement = XElement.Load(@"..\..\store.xml");

// Select the name of elements who have a category ID of 16.

IEnumerable catEnum = from elem in rootElement.Elements()

where (elem.Name == "Products" &&

((string)elem.Element("CategoryID"))

== "16")

select ((string)elem.Element("ModelName"));

foreach (string stringVal in catEnum)

{

Console.WriteLine("Category 16 item: {0}", stringVal);

}

Console.WriteLine("Press enter to proceed");

Console.ReadLine();

// Perform the select again using instance methods.

IEnumerable catEnum2 = rootElement.Elements().Where(e

=> e.Name == "Products"

&& (string)e.Element("CategoryID") == "16").Select(

e => (string)e.Element("ModelName"));

foreach (string stringVal in catEnum2)

{

Console.WriteLine("Category 16 item: {0}", stringVal);

}

}

}

}



302



www.it-ebooks.info



CHAPTER 6 ■ XML PROCESSING



6-16. Modify an XML Tree with LINQ

The Problem

You need to add, remove, or modify elements in an XML tree.



The Solution

Use the Add, Replace*, and Remove* methods of the XElement class.



How It Works

The first step to add, remove, or modify an XML tree is to select the element you wish to change. You can

do this by using a LINQ query, or through the Attribute and Element methods of XElement.

To add a new element, call the Add method of the XElement you wish to use as the parent.

To modify elements, perform a LINQ query to select the elements of interest and enumerate the

results, calling the ReplaceAttributes or ReplaceNodes methods to modify the XElement you have

selected, or the ReplaceWith method to replace the selected element with a new element.

To remove an element, call the Remove method on the XElement instance that you no longer require.



The Code

The following example loads an XML file called ProductCatalog.xml, which is included with the source

code for this chapter. After printing out the XML that has been loaded, the following tasks are performed:



using

using

using

using



1.



Find all elements called product and modify the value of the attribute id.



2.



Remove all elements that contain the word tea in a child node called

description.



3.



Create a new element and add it to a suitable parent.



System;

System.Collections.Generic;

System.Linq;

System.Xml.Linq;



namespace Recipe06_16

{

class Recipe06_16

{

static void Main(string[] args)

{

// Load the XML tree from the file.

XElement rootElem = XElement.Load(@"..\..\ProductCatalog.xml");



303



www.it-ebooks.info



CHAPTER 6 ■ XML PROCESSING



// Write out the XML.

Console.WriteLine(rootElem);

Console.WriteLine("Press enter to continue");

Console.ReadLine();

// Select all of the product elements.

IEnumerable prodElements

= from elem in rootElem.Element("products").Elements()

where (elem.Name == "product")

select elem;

// Run through the elements and change the ID attribute.

foreach(XElement elem in prodElements)

{

// Get the current product ID.

int current_id = Int32.Parse((string)elem.Attribute("id"));

// Perform the replace operation on the attribute.

elem.ReplaceAttributes(new XAttribute("id", current_id + 500));

}

Console.WriteLine(rootElem);

Console.WriteLine("Press enter to continue");

Console.ReadLine();

// Remove all elements that contain the word "tea" in the description.

IEnumerable teaElements = from elem in

rootElem.Element("products").Elements()

where (((string)elem.Element("description")).Contains("tea"))

select elem;

foreach (XElement elem in teaElements)

{

elem.Remove();

}

Console.WriteLine(rootElem);

Console.WriteLine("Press enter to continue");

Console.ReadLine();

// Define and add a new element.

XElement newElement = new XElement("product",

new XAttribute("id", 3000),

new XElement("productName", "Chrome French Press"),

new XElement("description",

"A simple and elegant way of making great coffee"),

new XElement("productPrice", 25.00),

new XElement("inStock", true));



304



www.it-ebooks.info



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

6-15. Query XML with LINQ

Tải bản đầy đủ ngay(0 tr)

×