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

CHAPTER 21 INTRODUCTION TO LINQ

Adding Nodes and Manipulating XML

You can add a child element to an existing element using the Add method. The Add method allows you to add as many elements as you like in a single method call, regardless of the node types you are adding.

For example, the following code creates a simple XML tree and displays it. It then uses the Add method to add a single node to the root element. Following that, it uses the Add method a second time to add three elements—two XElements and an XComment. Notice the results in the output:

using System;

using System.Xml.Linq;

class Program

 

{

 

static void Main()

 

{

 

XDocument xd = new XDocument(

// Create XML tree

new XElement("root",

 

new XElement("first")

 

)

 

);

 

Console.WriteLine("Original tree");

Console.WriteLine(xd); Console.WriteLine(); // Display the tree.

XElement rt

= xd.Element("root");

// Get the first element.

rt.Add( new

XElement("second"));

// Add a child element.

rt.Add( new

XElement("third"),

// Add three more children.

new

XComment("Important Comment"),

 

new

XElement("fourth"));

 

Console.WriteLine("Modified tree");

 

Console.WriteLine(xd);

// Display modified tree

}

}

584

CHAPTER 21 INTRODUCTION TO LINQ

This code produces the following output:

<root> <first />

</root>

<root> <first /> <second /> <third />

<!--Important Comment--> <fourth />

</root>

The Add method places the new child nodes after the existing child nodes, but you can place the nodes before and between the child nodes as well, using the AddFirst, AddBeforeSelf, and

AddAfterSelf methods.

Table 21-3 lists some of the most important methods for manipulating XML. Notice that some of the methods are applied to the parent node and others to the node itself.

Table 21-3. Methods for Manipulating XML

Method Name

Call From

Description

Add

Parent

Adds new child nodes after the existing child nodes of the current

 

 

node

AddFirst

Parent

Adds new child nodes before the existing child nodes of the current

 

 

node

AddBeforeSelf

Node

Adds new nodes before the current node at the same level

AddAfterSelf

Node

Adds new nodes after the current node at the same level

Remove

Node

Deletes the currently selected node and its contents

RemoveNodes

Node

Deletes the currently selected XElement and its contents

SetElement

Parent

Sets the contents of a node

ReplaceContent

Node

Replaces the contents of a node

 

 

 

585

CHAPTER 21 INTRODUCTION TO LINQ

Working with XML Attributes

Attributes give additional information about an XElement node. They’re placed in the opening tag of the XML element.

When you functionally construct an XML tree, you can add attributes by just including XAttribute constructors within the scope of the XElement constructor. There are two forms of the XAttribute constructor; one takes a name and a value, and the other takes a reference to an already existing XAttribute.

The following code adds two attributes to root. Notice that both parameters to the XAttribute constructor are strings; the first specifies the name of the attribute, and the second gives the value.

XDocument xd

= new XDocument(

 

 

 

 

 

 

Name

Value

 

 

 

new XElement("root",

 

 

 

new

XAttribute("color", "red"),

//

Attribute

constructor

new

XAttribute("size", "large"),

//

Attribute

constructor

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

)

);

Console.WriteLine(xd);

This code produces the following output. Notice that the attributes are placed inside the opening tag of the element.

<root color="red" size="large"> <first />

<second /> </root>

586

CHAPTER 21 INTRODUCTION TO LINQ

To retrieve an attribute from an XElement node, use the Attribute method, supplying the name of the attribute as the parameter. The following code creates an XML tree with a node with two attributes— color and size. It then retrieves the values of the attributes and displays them.

static void Main( )

 

 

 

{

 

 

 

XDocument xd = new XDocument(

// Create XML tree

new XElement("root",

 

 

 

new XAttribute("color", "red"),

 

 

new XAttribute("size", "large"),

 

 

new XElement("first")

 

 

)

 

 

 

);

 

 

 

Console.WriteLine(xd); Console.WriteLine();

// Display

XML tree

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

// Get the

element.

XAttribute color = rt.Attribute("color");

// Get the

attribute.

XAttribute size = rt.Attribute("size");

// Get the

attribute.

Console.WriteLine("color

is {0}", color.Value);

// Display

attr. value

Console.WriteLine("size

is {0}", size.Value);

// Display

attr. value

}

 

 

 

This code produces the following output:

<root color="red" size="large"> <first />

</root>

color is red size is large

587

CHAPTER 21 INTRODUCTION TO LINQ

To remove an attribute, you can select the attribute and use the Remove method or use the SetAttributeValue method on its parent and set the attribute value to null. The following code demonstrates both methods:

static void Main( ) {

XDocument xd = new XDocument( new XElement("root",

new XAttribute("color", "red"), new XAttribute("size", "large"), new XElement("first")

)

);

 

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

// Get the element.

rt.Attribute("color").Remove();

// Remove the color attribute.

rt.SetAttributeValue("size", null);

// Remove the size attribute.

Console.WriteLine(xd);

 

}

 

This code produces the following output:

<root> <first />

</root>

588

CHAPTER 21 INTRODUCTION TO LINQ

To add an attribute to an XML tree or change the value of an attribute, you can use the SetAttributeValue method, as shown in the following code:

static void Main( ) {

XDocument xd = new XDocument( new XElement("root",

new XAttribute("color", "red"), new XAttribute("size", "large"), new XElement("first")));

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

// Get

the element.

 

rt.SetAttributeValue("size", "medium");

//

Change

attribute

value

rt.SetAttributeValue("width", "narrow");

//

Add

an

attribute.

Console.WriteLine(xd); Console.WriteLine();

}

This code produces the following output:

<root color="red" size="medium" width="narrow"> <first />

</root>

589

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