XPathDocument

You might not want to load a complete XmlDocument just to use XPath. An XmlDocument brings with it all the DOM overhead, allowing you to not only read but to write to the XML node tree. For read-only access, there is the XPathDocument class. Like XmlNode, it implements IXPathNavigable; but unlike XmlNode, it represents a read-only view of the XML document.

XPathDocument does not maintain node identity like XmlDocument, nor does it do any rule checking required by the DOM. It is optimized for XPath queries and XSLT processing.

Tip

Starting to get the idea that this stuff is all intertwined? XSLT is covered in Chapter 7.

XPathDocument ’s sole purpose is to serve as an implementation of IXPathNavigable. It has constructors that take a Stream, a URL, a TextReader, and an XmlReader, respectively, and its only other method is CreateNavigator( ).

An XPathNodeIterator obtained from an XPathDocument does not implement IHasXmlNode. Each element of the XPathNodeIterator is actually an XPathDocumentNavigator, and does not have a GetNode( ) method. Remember that the XPathDocument is not an XmlDocument; that is, it does not implement the DOM specification, so it is not navigable as a tree of XmlNode instances. If it’s important to you that you be able to access the nodes using DOM, use XmlDocument.CreateNavigator( ).

XPathDocumentNavigator does have some properties and methods with which you can access node-specific information. XPathDocumentNavigator implements the following abstract properties and methods of XPathNavigator: HasAttributes, HasChildren, IsEmptyElement, LocalName, Name, NamespaceURI, NodeType (which returns an XPathNodeType, not an XmlNodeType), Value, and GetAttribute( ).

With the following modifications to your XPath query code, the current node’s name is written to the console:

XPathDocument document = new XPathDocument(filename);

XPathNavigator navigator = document.CreateNavigator( );
XPathNodeIterator iterator = navigator.Select(xpathExpression);
Console.WriteLine("{0} nodes matched.", iterator.Count);
while (iterator.MoveNext( )) {
  Console.WriteLine(iterator.Current.LocalName);
}
writer.Close( );

Warning

Again, be careful what you cast. An XPathNodeIterator obtained by calling XmlNode.GetNavigator( ) will implement IHasXmlNode, but one obtained by calling XPathDocument.GetNavigator( ) will not.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.61.142