Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Daniel Solis - Illustrated C# 2010 - 2010.pdf
Скачиваний:
16
Добавлен:
11.06.2015
Размер:
11.23 Mб
Скачать

CHAPTER 21 INTRODUCTION TO LINQ

Other Types of Nodes

Three other types of nodes used in the previous examples are XComment, XDeclaration, and XProcessingInstruction. They’re described in the following sections.

XComment

Comments in XML consist of text between the <!-- and --> tokens. The text between the tokens is ignored by XML parsers. You can insert text in an XML document using the XComment class, as shown in the following line of code:

new XComment("This is a comment")

XDeclaration

XML documents start with a line that includes the version of XML used, the type of character encoding used, and whether the document depends on external references. This is information about the XML, so it’s actually metadata about the metadata! This is called the XML declaration and is inserted using the XDeclaration class. The following shows an example of an XDeclaration statement:

new XDeclaration("1.0", "utf-8", "yes")

XProcessingInstruction

An XML processing instruction is used to supply additional data about how an XML document should be used or interpreted. Most commonly, processing instructions are used to associate a style sheet with the XML document.

You can include a processing instruction using the XProcessingInstruction constructor, which takes two string parameters—a target and a data string. If the processing instruction takes multiple data parameters, those parameters must be included in the second parameter string of the XProcessingInstruction constructor, as shown in the following constructor code. Notice that in this example, the second parameter is a verbatim string, and literal double quotes inside the string are represented by sets of two contiguous double quote marks.

new XProcessingInstruction( "xml-stylesheet",

@"href=""stories"", type=""text/css""")

590

CHAPTER 21 INTRODUCTION TO LINQ

The following code uses all three constructs:

static void Main( )

{

XDocument xd = new XDocument(

new XDeclaration("1.0", "utf-8", "yes"), new XComment("This is a comment"),

new XProcessingInstruction("xml-stylesheet",

@"href=""stories.css"" type=""text/css"""),

new XElement("root",

new XElement("first"), new XElement("second")

)

);

}

This code produces the following output in the output file. Using a WriteLine of xd, however, would not show the declaration statement, even though it is included in the document file.

<?xml version="1.0" encoding="utf-8" standalone="yes"?> <!--This is a comment-->

<?xml-stylesheet href="stories.css" type="text/css"?> <root>

<first /> <second />

</root>

591

CHAPTER 21 INTRODUCTION TO LINQ

Using LINQ Queries with LINQ to XML

You can combine the LINQ XML API with LINQ query expressions to produce simple yet powerful XML tree searches.

The following code creates a simple XML tree, displays it to the screen, and then saves it to a file called SimpleSample.xml. Although there’s nothing new in this code, we’ll use this XML tree in the following examples.

static void Main( )

 

{

 

 

XDocument xd

= new XDocument(

 

new XElement("MyElements",

 

new XElement("first",

 

new

XAttribute("color",

"red"),

new

XAttribute("size",

"small")),

new XElement("second",

 

new

XAttribute("color",

"red"),

new

XAttribute("size",

"medium")),

new XElement("third",

 

new

XAttribute("color",

"blue"),

new

XAttribute("size",

"large"))));

Console.WriteLine(xd);

//

Display XML tree

xd.Save("SimpleSample.xml");

//

Save XML tree

}

 

 

This code produces the following output:

<MyElements>

<first color="red" size="small" /> <second color="red" size="medium" /> <third color="blue" size="large" />

</MyElements>

592

CHAPTER 21 INTRODUCTION TO LINQ

The following example code uses a simple LINQ query to select a subset of the nodes from the XML tree and then displays them in several ways. This code does the following:

It selects from the XML tree only those elements whose names have five characters. Since the names of the elements are first, second, and third, only node names first and third match the search criterion, and therefore those nodes are selected.

It displays the names of the selected elements.

It formats and displays the selected nodes, including the node name and the values of the attributes. Notice that the attributes are retrieved using the Attribute method, and the values of the attributes are retrieved with the Value property.

static void Main( )

 

 

{

XDocument xd = XDocument.Load("SimpleSample.xml");

// Load the document.

 

 

XElement rt = xd.Element("MyElements");

 

// Get the root element.

 

var xyz = from e in rt.Elements()

 

// Select elements whose

 

where e.Name.ToString().Length == 5

// names have 5 chars.

 

select e;

 

 

 

foreach (XElement x in xyz)

 

// Display the

 

Console.WriteLine(x.Name.ToString());

 

// selected elements.

 

Console.WriteLine();

 

 

 

foreach (XElement x in xyz)

 

 

 

Console.WriteLine("Name: {0}, color: {1}, size: {2}",

 

x.Name,

 

 

 

x.Attribute("color").Value,

 

 

x.Attribute("size") .Value);

 

 

 

 

}

 

Get the attribute.

Get the attribute’s value.

This code produces the following output:

first third

Name: first, color: red, size: small

Name: third, color: blue, size: large

593

CHAPTER 21 INTRODUCTION TO LINQ

The following code uses a simple query to retrieve all the top-level elements of the XML tree and creates an object of an anonymous type for each one. The first use of the WriteLine method shows the default formatting of the anonymous type. The second WriteLine statement explicitly formats the members of the anonymous type objects.

using System; using System.Linq;

using System.Xml.Linq;

static void Main( )

{

XDocument xd =

XDocument.Load("SimpleSample.xml"); // Load the document.

XElement rt = xd.Element("MyElements");

// Get the root element.

var xyz = from

e in rt.Elements()

 

 

select new { e.Name, color = e.Attribute("color") };

 

 

 

 

 

foreach (var x

in xyz)

Create an anonymous type.

Console.WriteLine(x);

 

// Default formatting

Console.WriteLine();

 

 

 

foreach (var x

in xyz)

 

 

 

Console.WriteLine("{0,-6},

color: {1, -7}", x.Name, x.color.Value);

}

This code produces the following output. The first three lines show the default formatting of the anonymous type. The last three lines show the explicit formatting specified in the format string of the second WriteLine method.

{Name = first, color = color="red" }

{Name = second, color = color="red" }

{Name = third, color = color="blue" }

first

,

color: red

second,

color: red

third

,

color: blue

 

 

 

From these examples, you can see that you can easily combine the XML API with the LINQ query facilities to produce powerful XML querying capabilities.

594

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]