Edit an XML Document with XPathNavigator

The XPathNavigator is the XML interface of choice for Visual Basic 2005 applications. And in .NET 2.0, it doesn't just work as a view onto read-only XML data—it also allows you to change XML documents, such as by modifying text content, inserting new elements, or removing a branch of nodes.

Note

The best feature of the XPathNavigator is its new support for editing and inserting content.

How do I do that?

In the previous lab, Section 5.10, you learned how to load XML data into an XPathDocument, and then browse and search through it using an XPathNavigator. If you want to make changes, you still start with the same XPathDocument. The secret is that you also use a couple of additional methods in the XPathNavigator:

SetValue( )

This method inserts a new value in the current element, replacing the existing value.

DeleteCurrent( )

This method removes the current node from the document.

Remember, you have two basic choices for creating an XPathNavigator:

Use the XPathDocument.CreateNavigator( ) method

This method returns an XPathNavigator for the whole document. You can then move to the portion of the document you want to change.

Use the XPathDocument.Select( ) method with an XPath expression

This returns an XPathNodeIterator that allows you to move through your results, retrieving an XPathNavigator for each selected node.

Example 5-12 modifies the XML document shown in Example 5-10. It increases all the prices by 10% and then deletes nodes that don't fall ...

Get Visual Basic 2005: A Developer's Notebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.