A simple understanding of some basic methods of JavaScript manipulating XPath _javascript tips

Source: Internet
Author: User
Tags xpath

XPath is now rarely used by us because JSON is now prevalent. But in the age of XML as a data Interchange format, XPath plays a very important role when we randomly access large XML document structures. Perhaps many of you are now not aware that the DOM level 3 XPath-specified interface has been implemented by Firefox,safari, Chrome, and opera. The core interface they implement is Xpathevaluator, which includes methods to work with XPath expressions, the most important of which is evaluate (), It can accept five parameters 1.xpath query string 2. Indicates which node the XPath query string should start with 3. The namespace parser (described later) 4. The result type returned is 5. The returned results should be added to that object (rarely used because the result is mainly via evaluate ()) Returned).

There are 10 different return types in the main. Each one represents a constant of the Xpathresult object.

    • Xpathresult.any_type data types that are appropriate for XPath expressions
    • Xpathresult.any_unordered_node_type returns a collection of matching nodes, which may be different in order from the document.
    • Xpathresult.boolean_type returns a BOOLEAN type
    • Xpathresult.first_ordered_node_type returns the first node of a matching node in the document.
    • Xpathresult.number_type return num Type
    • Xpathresult.ordered_node_iterator_type returns a collection of matching nodes, in the same order as in the document
    • Xpathresult.ordered_node_snapshot_type returns a node collection fragment that captures the node outside the document so that any future modifications to the document will not affect the node collection. The order in the node collection is the same as in the document.
    • Xpathresult.string_type returns a STRING type
    • Xpathresult.unordered_node_iterator_type returns a collection of matching nodes, which may be different in order from the document.
    • Xpathresult.unordered_node_snapshot_type returns a node collection fragment that captures the node outside the document so that any future modifications to the document will not affect the node collection. The order in the node collection is not necessarily the same as in the document.

Introduced so much, so how do we use these APIs to operate?
The information returned by the evaluate () function depends entirely on the result type of the request.
To perform an XPath query, you need to use the Xpathevaluator object, you can generate a new object or you can use the built-in object, and if you generate a new object, initialize the Xpathevaluator.

var evaluator = new Xpathevaluator (); 
Get the first div 
var result = Evaluator.evaluate ("//div", document.documentelement, NULL, 
         Xpathresult.first_ Ordered_node_type, null); 
Alert ("The" "The" the "" "+ result.singleNodeValue.id); 

In Firefox, Safari, Chrome, and Opera, all of the document instances implement the Xpathevaluator interface, so if the query executed in the HTML page, we can use Document.evaluate (), If an XML document is obtained through XMLHttpRequest or other mechanisms, the evaluate () method can also be used, for example:

Get-i-div 
var result = Document.evaluate ("//div", document.documentelement, NULL, 
         Xpathresult.first_ Ordered_node_type, null); 
Alert ("The" "The" the "" "+ result.singleNodeValue.id); 

Here are two ways to return to multiple nodes, or look at an example first:

Get all divs-iterator style 
var = document.evaluate ("//div", document.documentelement, NULL, 
         Xpathresult.ordered_node_iterator_type, null); 
if (result) { 
  var node = Result.iteratenext (); 
  while (node) { 
    alert (node.id); 
    node = Node.iteratenext (); 
  } 
} 
Get all divs-snapshot style 
var = document.evaluate ("//div", document.documentelement, NULL, 
         Xpathresult.ordered_node_snapshot_type, null); 
if (result) { 
  for (Var i=0, len=result.snapshotlength i < Len; i++) { 
    alert (Result.snapshotitem (i). ID); c16/>} 
} 


name Space
If you just use XPath in a simple query in an HTML document, the namespace parser parameter in evaluate () is generally null, if you prefer to use XPath to query in an XML document that contains namespaces, Then you should learn how to create and use a namespace parser.
Each namespace URI is mapped to a specified prefix, except for the default namespace. Each namespace parser maps between the namespace prefix and the namespace URI for the XPath engine. There are two ways to generate a namespace parser, the first of which is to create a method that accepts a namespace prefix as a parameter, and then returns the corresponding URL, as follows:

function resolver (prefix) { 
  switch (prefix) {case 
    ' Wrox ': return ' http://www.wrox.com/'; 
    Case "Ncz": Return "http://www.nczonline.net/"; 
    Default:return "http://www.yahoo.com/"; 
  } 
 

The second type uses a node that contains namespace information to generate a namespace parser.

<books xmlns:wrox= "http://www.wrox.com/" xmlns= "http://www.amazon.com/" > 
  <wrox:book>professional Javascript</book> 

<books> element contains all the namespace information, you can pass the reference of this node to the Creatensresovler () method of the Xpathevaluator object, and then you can automatically get a namespace parser.
Such as:

var evaluator = new Xpathevaluator (); 
var resolver = evaluator.creatensresolver (xmldoc.documentelement); 

Using any of the above methods makes it easy to query in a namespace-containing XML document.

var evaluator = new Xpathevaluator (); 
var resolver = evaluator.creatensresolver (xmldoc.documentelement); 
var result = Evaluator.evaluate ("Wrox:book", Xmldoc.documentelement, 
         Resolver, Xpathresult.first_ordered_node_ TYPE, null); 
if (result) { 
  alert (result.singleNodeValue.firstChild.nodeValue); 
} 

Note: If you execute a query in an XML document that contains namespaces and do not provide a namespace parser, an error occurs.

Support for XPath in IE browsers
IE8 has not yet implemented the interface defined in DOM Level 3 XPath, but it also has some support for XPath, which is primarily available for XML documents and is unavailable for document objects.
How to generate XML documents in IE:

function CreateDocument () { 
  if (typeof arguments.callee.activeXString!= "string") { 
    var versions = ["MSXML2. domdocument.6.0 ", 
            " MSXML2. domdocument.3.0 ", 
            " MSXML2. DOMDocument "]; 
    for (Var i=0,len=versions.length i < Len; i++) { 
      try { 
        var xmldom = new ActiveXObject (versions[i)); 
        arguments.callee.activeXString = Versions[i]; 
        return xmldom; 
      } catch (ex) {//skip}}} return to 
  new ActiveXObject (arguments.callee.activeXString); 
} 

After you build the Document object, you can use the Loadxml () method to load the content:

var xmldoc = CreateDocument (); 
Xmldoc.loadxml (""); 

The second method generates an XML object by requesting the Xmlhttrequest object.

var xhr = new XMLHttpRequest (), 
  xmldoc; 
Xhr.open ("Get", "Data.xml", true); 
Xhr.onreadystatechange = function () { 
  if (xhr.readystate = 4) { 
    if (xhr.status >= && xhr.status ; () { 
      xmldoc = xhr.responsexml; 
    } 
}; 


The third approach is to use the <xml> tag, which Microsoft calls this method an XML data island, as follows:

<xml id= "myXML" src= "Data.xml" ></xml>

And then:

var xmldoc = document.getElementById ("myXML"). XmlDocument;

XPath support:
XML document objects in IE have two built-in methods for supporting XPath:
selectSingleNode () and selectnodes (), each of which accepts an XPath expression as an argument, and then puts the first matching node back and all the matching nodes respectively.
Namespace support:
For

<books xmlns:wrox= "http://www.wrox.com/" xmlns= "http://www.amazon.com/" >
  <wrox:book>professional Javascript</book>

</books> This XML document, we should use the following method to query, that is, first use SetProperty (), to set the XML document namespace.

Xmldoc.setproperty ("SelectionNamespaces",
  "xmlns:wrox= ' http://www.wrox.com/' xmlns= ' http://www.amazon.com/') ");
var book = Xmldoc.documentElement.selectSingleNode ("Wrox:book");

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.