- XPath資料模式依賴存System.Xml.XPath命名空間的XPathNavigator類。
- XPathNavigator類是一個抽象類別,是一個以指標方式為基礎的瀏覽XML資料的模式,它允許你對XML檔案進行編輯。
- 你可以從任何實現了IXPathNavigable介面的類獲得XPathNavigator類的一個執行個體。XmlDocument和XPathDocument就是實現了這個介面的類。
- XmlDocument返回的XML是可編輯的,XPathDocument返回對象是唯讀。
建立XPathNavigator對象:
1: //功能性範例程式碼:
2: private void button1_Click(object sender, EventArgs e)
3: {
4: XPathNavigator navigator = null;
5: if (radioButton1.Checked)
6: {
7: //XmlDocument類建立XPathNavigator對象
8: XmlDocument doc = new XmlDocument();
9: doc.Load(Application.StartupPath + @"/employees.xml");
10: navigator = doc.CreateNavigator();
11: }
12: else
13: {
14: //XmlPathDocument類建立XPathNavigator對象
15: XPathDocument doc = new XPathDocument(Application.StartupPath + @"/employees.xml");
16: navigator = doc.CreateNavigator();
17: }
18: MessageBox.Show("Navigator created successfully!");
19: }
通過XPathNavigator來瀏覽XML文檔
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: }
參考書籍
XSLT 2.0 and XPath 2.0 Programmer's Reference (Programmer to Programmer)