A simple understanding of some basic methods for operating XPath in JavaScript, and how to operate xpath in javascript

Source: Internet
Author: User

A simple understanding of some basic methods for operating XPath in JavaScript, and how to operate xpath in javascript

Xpath is rarely used now, because JSON is very popular now. However, when XML was used as the data exchange format, Xpath played a very important role when we randomly accessed the large xml document structure. You may not notice that the interface specified by DOM Level 3 XPath has been implemented by Firefox, Safari, Chrome, and Opera. Their core interface is XPathEvaluator, which contains some methods that can work using xpath expressions. The main method is evaluate (), which can accept five parameters 1. xpath query string 2. specify the node from which the xpath query string should start. 3. namespace Parser (described later) 4. returned result type 5. the returned results should be added to that object (rarely used, because the results are mainly returned through evaluate ).

There are mainly 10 different return types. Each type represents a constant of the XPathResult object.

  • XPathResult. ANY_TYPE is applicable to the Data Type of the xpath expression.
  • XPathResult. ANY_UNORDERED_NODE_TYPE returns a set of matched nodes. The order may be different from that in the document.
  • XPathResult. BOOLEAN_TYPE returns the boolean type.
  • XPathResult. FIRST_ORDERED_NODE_TYPE returns the first node of the matching node in the document.
  • XPathResult. NUMBER_TYPE returns the num type
  • XPathResult. ORDERED_NODE_ITERATOR_TYPE returns the set of matched nodes. The order is the same as that in the document.
  • XPathResult. ORDERED_NODE_SNAPSHOT_TYPE returns a node set segment, which captures nodes outside the document. In this way, any modifications to the document will not affect the node set. The order in the node set must be the same as that in the document.
  • XPathResult. STRING_TYPE returns a string type.
  • XPathResult. UNORDERED_NODE_ITERATOR_TYPE returns a set of matched nodes. The order may be different from that in the document.
  • XPathResult. UNORDERED_NODE_SNAPSHOT_TYPE returns a node set segment that captures nodes outside the document. In this way, any modifications to the document will not affect the node set. The order in the node set does not need to be the same as that in the document.

With so many introductions, how can we use these APIs for operations?
The information returned by the evaluate () function is completely dependent on the request result type.
To execute the xpath query, you need to use the XPathEvaluator object. You can generate a new object or use a built-in object. If you generate a new object, you need to initialize XPathEvaluator.

Var evaluator = new XPathEvaluator (); // obtain the first div var result = evaluator. evaluate ("// div", document.doc umentElement, null, XPathResult. FIRST_ORDERED_NODE_TYPE, null); alert ("First div ID is" + result. singleNodeValue. id );

In Firefox, Safari, Chrome, and Opera, all document instances implement the XPathEvaluator interface. In this way, you can use document to perform queries on the HTML page. evaluate (). If you use XMLHttpRequest or another mechanism to obtain an XML document, the evaluate () method can also be used, for example:

//get first div var result = document.evaluate("//div", document.documentElement, null,          XPathResult.FIRST_ORDERED_NODE_TYPE, null); alert("First div ID is " + result.singleNodeValue.id); 

The following describes two methods to return multiple nodes. Let's take a look at the instance first:

//get all divs - iterator style var result = 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 result = 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);   } } 


Namespace
If you only use xpath for simple query in the html document, the namespace parser parameter in evaluate () is generally null, if you prefer to use xpath to query in xml documents containing namespaces, you should learn how to create and use the namespace parser.
In addition to the default namespace, each namespace URI is mapped to a specified prefix. Each namespace parser maps the namespace prefix and namespace uri of the xpath engine. There are two methods to generate the namespace parser. The first method is as follows: Create a method that accepts the namespace prefix as a parameter, and then return the corresponding url, as shown below:

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 method 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> 

<Books> the element contains all the namespace information. You can pass the reference of this node to the createNSResovler () method of the XPathEvaluator object, and then automatically obtain a namespace parser.
For example:

var evaluator = new XPathEvaluator(); var resolver = evaluator.createNSResolver(xmldoc.documentElement); 

Using any of the above methods, you can easily query the xml document containing the namespace.

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 file containing a namespace and do not provide a namespace parser, an error will occur.

Support for xpath in IE
IE8 does not implement the interface defined in DOM Level 3 XPath, but it also supports xpath. The xpath function in IE is mainly available for xml documents and unavailable for document objects.
How to generate an xml document 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 new ActiveXObject(arguments.callee.activeXString); } 

After a Document Object is generated, you can use the loadXML () method to load the content:

var xmldoc = createDocument(); xmldoc.loadXML(""); 

The second method uses the XMLHttRequest object to generate an xml object.

var xhr = new XMLHttpRequest(),   xmldoc; xhr.open("get", "data.xml", true); xhr.onreadystatechange = function(){   if (xhr.readyState == 4){     if (xhr.status >= 200 && xhr.status < 300){       xmldoc = xhr.responseXML;     } }; xhr.send(null); 

 
The third method is to use the <xml> tag. Microsoft calls this method xml data island as follows:

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

Then:

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

XPath support:
Xml document objects in ie support xpath in two built-in methods:
SelectSingleNode () and selectNodes (), each method accepts the xpath expression as a parameter, and then puts the first matching node and all matching nodes back.
Namespace support:
For

<books xmlns:wrox="http://www.wrox.com/" xmlns="http://www.amazon.com/">  <wrox:book>Professional JavaScript</book>

</Books> In this xml document, we should use the following method to query, that is, first use setProperty () to set the namespace of the xml document.

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

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.