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
XPathNavigatorfor 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
XPathNodeIteratorthat allows you to move through your results, retrieving anXPathNavigatorfor 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 into ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access