15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Using XPathnavigators ❘ 921<br />

This time, you see the total cost of the books evaluated in the text<br />

box (see Figure 33-3).<br />

Now let’s say that you need to add a node for discount. You can<br />

use the InsertAfter method to get this done fairly easily. Here is<br />

the code:<br />

private void button3_Click(object sender, EventArgs e)<br />

{<br />

XmlDocument doc = new XmlDocument();<br />

doc.Load("books.xml");<br />

XPathNavigator nav = doc.CreateNavigator();<br />

if (nav.CanEdit)<br />

{<br />

XPathNodeIterator iter =<br />

nav.Select("/bookstore/book/price");<br />

while (iter.MoveNext())<br />

{<br />

iter.Current.InsertAfter("5");<br />

}<br />

}<br />

doc.Save("newbooks.xml");<br />

}<br />

figure 33-3<br />

code snippet frmNavigator.cs<br />

Here, you add the 5 element after the price elements. First, all of the price nodes are<br />

selected. The XPathNodeIterator is used to iterate over the nodes, <strong>and</strong> the new node is inserted. The<br />

modified document is saved with a new name, newbooks.xml. The new version looks like the following:<br />

<br />

<br />

<br />

<br />

The Autobiography of Benjamin Franklin<br />

<br />

Benjamin<br />

Franklin<br />

<br />

8.99<br />

5<br />

<br />

<br />

The Confidence Man<br />

<br />

Herman<br />

Melville<br />

<br />

11.99<br />

5<br />

<br />

<br />

The Gorgias<br />

<br />

Plato<br />

<br />

9.99<br />

5<br />

<br />

<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!