- The XPath data mode depends on the XPathNavigator class stored in the System. Xml. XPath namespace.
- The XPathNavigator class is an abstract class. It is a pointer-based XML data browsing mode that allows you to edit XML files.
- You can obtain an instance of the XPathNavigator class from any class that implements the IXPathNavigable interface. XmlDocument and XPathDocument are the classes that implement this interface.
- The XML returned by XmlDocument is editable, and the returned object of XPathDocument is read-only.
Create an XPathNavigator object:
1: // functional sample code:
2: private void button1_Click(object sender, EventArgs e)
3: {
4: XPathNavigator navigator = null;
5: if (radioButton1.Checked)
6: {
7: // create an XPathNavigator object in the XmlDocument class
8: XmlDocument doc = new XmlDocument();
9: doc.Load(Application.StartupPath + @"/employees.xml");
10: navigator = doc.CreateNavigator();
11: }
12: else
13: {
14: // create an XPathNavigator object in the XmlPathDocument class
15: XPathDocument doc = new XPathDocument(Application.StartupPath + @"/employees.xml");
16: navigator = doc.CreateNavigator();
17: }
18: MessageBox.Show("Navigator created successfully!");
19: }
Use XPathNavigator to browse XML documents
1: protected void Button1_Click(object sender, EventArgs e)
2: {
3: XPathDocument doc =new XPathDocument(xmlFilePath);
4: XPathNavigator navigator = doc.CreateNavigator();
5: navigator.MoveToRoot();
6: navigator.MoveToFirstChild();
7: TreeNode root = TreeView1.Nodes.Add("Employees");
8: while (navigator.MoveToNext())
9: {
10: if (navigator.HasChildren)
11: {
12: navigator.MoveToFirstChild();
13: do
14: {
15: string id = navigator.GetAttribute("employeeid", "");
16: TreeNode empnode = new TreeNode("Employee ID :" + id);
17: root.Nodes.Add(empnode);
18: navigator.MoveToFirstChild();
19: do
20: {
21: string name = navigator.Name;
22: TreeNode node = new TreeNode(name + " : " + navigator.Value);
23: empnode.Nodes.Add(node);
24: } while (navigator.MoveToNext());
25: navigator.MoveToParent();
26: }
27: while (navigator.MoveToNext());
28: }
29: }
30: }
Reference books
XSLT 2.0 and XPath 2.0 Programmer's Reference (Programmer to Programmer)