使用 Visual C# 通过 XPathNavigator 类导航 XML 文档

本文介绍如何使用 XPathNavigatorXPathDocument 对象创建的对象导航 XML 文档。

原始产品版本: Visual C#
原始 KB 数: 308343

总结

此示例使用 XML 数据加载对象 XPathDocument ,创建 XPathNavigator 对象作为数据视图,并通过浏览文档来显示 XML。

本文介绍以下Microsoft .NET Framework 类库命名空间:

  • System.Xml
  • System.Xml.XPath

有关本文的 Microsoft Visual Basic .NET 版本,请参阅 如何使用 Visual Basic 通过 XPathNavigator 类导航 XML。

要求

本文假定你熟悉以下主题:

  • Visual C#
  • XML 术语
  • 创建和读取 XML 文件
  • XML 路径语言 (XPath) 语法

如何使用 XPathNavigator 类导航 XML

  1. 在 Visual Studio 中创建新的 Visual C# 控制台应用程序。

    注意

    此示例使用名为 Books.xml的文件。 可以创建自己的 Books.xml 文件,也可以使用 .NET 软件开发工具包(SDK)快速入门中包含的示例。 如果没有安装快速入门并不想安装它们,请参阅Books.xml下载位置的“参考”部分。 如果已安装快速入门, Books.xml 位于以下文件夹中:
    \Program Files\Microsoft.NET\FrameworkSDK\Samples\Quickstart\Howto\Samples\Xml\Transformxml\VB

    可以将Books.xml复制到\Bin\Debug创建此项目的文件夹下的文件夹。

  2. 确保项目引用 System.Xml 命名空间。

  3. using命名空间使用XPath语句Xml,以便你无需在代码后面限定这些命名空间中的声明。 可以在任何其他声明之前使用该 using 语句,如下所示:

    using System.Xml;
    using System.Xml.XPath;
    
  4. 声明相应的变量。 声明一个 XPathDocument 对象以保存 XML 文档和一个 XPathNavigator 对象来计算 XPath 表达式并移动文档。 声明要 String 保存 XPath 表达式的对象。 在 Module1 中的 Main 过程中添加声明代码。

    XPathNavigator nav;
    XPathDocument docNav;
    
  5. XPathDocument使用示例文件Books.xml加载对象。 该 XPathDocument 类使用可扩展样式表语言转换(XSLT)为 XML 文档处理提供快速且面向性能的缓存。 它类似于 XML 文档对象模型(DOM),但针对 XSLT 处理和 XPath 数据模型进行高度优化。

    // Open the XML.
    docNav = new XPathDocument(@"c:\books.xml");
    
  6. 从文档创建对象 XPathNavigatorXPathNavigator 使你能够同时浏览 XML 文档中的属性节点和命名空间节点。

    // Create a navigator to query with XPath.
    nav = docNav.CreateNavigator();
    
  7. 使用 MoveToRoot 该方法移动到文档的根目录。 MoveToRoot 将导航器设置为包含整个节点树的文档节点。

    //Initial XPathNavigator to start at the root.
    nav.MoveToRoot();
    
  8. MoveToFirstChild使用该方法移动到 XML 文档的子级。 该方法 MoveToFirstChild 将移动到当前节点的第一个子级。 如果有Books.xml源,将从根文档移动到子文档、“注释”部分和 Bookstore 节点。

    //Move to the first child node (comment field).
    nav.MoveToFirstChild();
    
  9. 使用该方法 MoveToNext 循环访问同级级别的节点。 该方法 MoveToNext 将移动到当前节点的下一个同级。

    //Loop through all of the root nodes.
    do
    {
    } while (nav.MoveToNext());
    
  10. NodeType使用属性确保只处理元素节点,并使用Value该属性显示元素的文本表示形式。

    do
    {
       //Find the first element.
       if (nav.NodeType == XPathNodeType.Element)
       {
            //Determine whether children exist.
            if (nav.HasChildren == true)
            {
                //Move to the first child.
                nav.MoveToFirstChild();
    
                //Loop through all the children.
                do
                {
                    //Display the data.
                    Console.Write("The XML string for this child ");
                    Console.WriteLine("is '{0}'", nav.Value);
                } while (nav.MoveToNext());
            }
        }
    } while (nav.MoveToNext());
    
  11. 使用该 HasAttributes 属性确定节点是否具有任何属性。 还可以使用其他方法(例如 MoveToNextAttribute)移动到属性并检查其值。

    注意

    此代码段仅遍历根节点的后代,而不是整个树。

    do
    {
       //Find the first element.
       if (nav.NodeType == XPathNodeType.Element)
       {
            //if children exist
            if (nav.HasChildren == true)
            {
                //Move to the first child.
                nav.MoveToFirstChild();
                //Loop through all the children.
                do
                {
                    //Display the data.
                    Console.Write("The XML string for this child ");
                    Console.WriteLine("is '{0}'", nav.Value);
    
                    //Check for attributes.
                    if (nav.HasAttributes == true)
                    {
                        Console.WriteLine("This node has attributes");
                    }
                } while (nav.MoveToNext());
            }
        }
    } while (nav.MoveToNext());
    
  12. ReadLine使用对象的方法Console在控制台显示结束时添加暂停,以便更方便地显示上述结果。

    //Pause.
    Console.ReadLine();
    
  13. 生成并运行 Visual C# 项目。

完整代码清单

using System;
using System.Xml;
using System.Xml.XPath;

namespace q308343
{
    class Class1
    {
        static void Main(string[] args)
        {
            XPathNavigator nav;
            XPathDocument docNav;

            docNav = new XPathDocument(@"c:\books.xml");
            nav = docNav.CreateNavigator();
            nav.MoveToRoot();

            //Move to the first child node (comment field).
            nav.MoveToFirstChild();

            do
            {
                //Find the first element.
                if (nav.NodeType == XPathNodeType.Element)
                {
                    //Determine whether children exist.
                    if (nav.HasChildren == true)
                    {
                        //Move to the first child.
                        nav.MoveToFirstChild();
                        //Loop through all of the children.
                        do
                        {
                            //Display the data.
                            Console.Write("The XML string for this child ");
                            Console.WriteLine("is '{0}'", nav.Value);
                            //Check for attributes.
                            if (nav.HasAttributes == true)
                            {
                                Console.WriteLine("This node has attributes");
                            }
                        } while (nav.MoveToNext());
                    }
                }
            } while (nav.MoveToNext());
            //Pause.
            Console.ReadLine();
        }
    }
}

故障排除

测试代码时,可能会收到以下异常错误消息:

system.Xml.XmlException 类型的未经处理的异常发生在system.xml.dll
其他信息:意外的 XML 声明。 XML 声明必须是文档中的第一个节点,并且不允许在它之前显示空格字符。 第 1 行,位置

异常错误发生在以下代码行上:

docNav = new XPathDocument("c:\\books.xml");

若要解决此错误,请删除books.xml文档中第一个节点前面的空格字符(s)。

参考