308343 HOW TO:使用 Visual C# .NET 通过 XPathNavigator 类浏览 XML (From MKBA)

有关本文的 Microsoft Visual Basic .NET 版本,请参见 301111

本文引用下面的 Microsoft .NET 框架类库名称空间:
  • System.Xml
  • System.Xml.XPath

本任务的内容

概要

本分步指南介绍了如何用从 XPathDocument 对象创建的 XPathNavigator 对象浏览可扩展标记语言 (XML) 文档。本示例用 XML 数据加载 XpathDocument 对象,针对该数据创建一个作为视图的 XPathNavigator 对象,并通过遍历该文档显示 XML。

返回页首

要求

下面的列表列出了推荐使用的硬件、软件、网络基础结构以及所需的服务包:
  • Microsoft Visual C# .NET
本文假定您熟悉下列主题:
  • XML 术语
  • 创建和读取 XML 文件
  • XML 路径语言 (XPath) 语法
返回页首

如何使用 XPathNavigator 类浏览 XML

  1. 在 Visual Studio. NET 中新建一个 Visual C# .NET 控制台应用程序。

    备注:本示例使用名为 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. Xml XPath 名称空间上使用 using 语句,这样以后就不需要在代码中限定这些名称空间中的声明了。using 语句必须在所有其他声明之前使用,如下所示:
    using System.Xml;
    using System.Xml.XPath;
  4. 声明合适的变量。声明 XPathDocument 对象以保存 XML 文档,并声明 XPathNavigator 对象以计算 XPath 表达式并遍历该文档。声明 String 对象以保存 XPath 表达式。在 Module1 的 Main 过程中添加声明代码。
    XPathNavigator nav; 
    XPathDocument docNav;
  5. 用示例文件 Books.xml 加载 XPathDocument 对象。XPathDocument 类使用可扩展样式表语言转换 (XSLT) 为 XML 文档处理提供快速和面向性能的缓存。它类似于 XML 文档对象模型 (DOM),但经过了高度优化,以用于 XSLT 处理和 XPath 数据模型。
    // Open the XML.
    docNav = new XPathDocument(@"c:/books.xml");
  6. 从文档创建 XPathNavigator 对象。XPathNavigator 使您能够在 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. 使用 Console 对象的 ReadLine 方法在控制台显示的末尾添加 pause,以便更容易地显示上述结果。
    //Pause.
    Console.ReadLine();
  13. 生成并运行 Visual C#.NET 项目。
返回页首

完整代码列表

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();
     }
   }
}
返回页首

疑难解答

在测试代码时,您可能会收到以下异常错误信息:
An unhandled exception of type 'System.Xml.XmlException' occurred in system.xml.dll

Additional information:System error.
该异常错误发生在以下代码行上:
docNav = new XPathDocument("c://books.xml");
该异常错误是由无效的处理指令导致的。例如,处理指令可能包含多余的空格。下面是无效处理指令的示例:
<?xml version='1.0'?>
若要解决该异常,请执行以下操作之一:
  • 纠正无效的处理指令。下面是有效处理指令的示例:
    <?xml version='1.0'?>
    - 或 -
  • 下面是有效处理指令的示例:从 Books.xml 文件中删除 XML 处理指令。
返回页首

参考

下列文件可从 Microsoft 下载中心下载:

下载立即下载 Books.xml

有关更多信息,请访问以下 Microsoft Web 站点:

XML in .NET: .NET Framework XML Classes and C# Offer Simple, Scalable Data Manipulation(.NET 中的 XML:.NET 框架 XML 类和 C# 提供简单的可缩放的数据操作)R/> http://msdn.microsoft.com/msdnmag/issues/01/01/xml/xml.asp

XPathNavigator Class(XPathNavigator 类)
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemXmlXPathXPathNavigatorClassTopic.asp

XPathDocument Class(XPathDocument 类)
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemXmlXPathXPathDocumentClassTopic.asp

XSLT Transformations with the XslTransform Class(使用 XslTransform 类 的 XSLT 转换)
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconxslttransformationswithxsltransformclass.asp

XPath Examples(XPath 示例)
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/xmlsdk30/htm/xmrefxpathexamples.asp

有关 XPath 的更多信息,请访问下列 WWW 联合会 (W3C) Web 站点:

XML 路径语言 (XPath)
1.0 版:W3C 在 1999 年 11 月 16 日提出的建议
http://www.w3.org/TR/1999/REC-xpath-19991116

返回页首

这篇文章中的信息适用于:

  • Microsoft .NET 框架类库
  • Microsoft Visual C# .NET (2002)
最近更新:2004-8-13 (2.2)
关键字:kbdownload kbHOWTOmaster kbXML KB308343
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值