- Introduction to the XPathAPI Object
- Example
- Search Examples
- Conclusion
Search Examples
There are many ways to search for elements with the methods that are provided by the XPathAPI class. There are also many ways to combine search strings to do more advanced searches in your XML files. The most common way to search for elements is with an absolute path. Following are examples of each method using an absolute path:
XPathAPI.getEvalString(this.firstChild, "/root/node"); XPathAPI.selectNodeList(this.firstChild, "/root/node"); XPathAPI.selectSingleNode(this.firstChild, "/root/node"); XPathAPI.setNodeValue(this.firstChild, "/root/node", "new value");
As a shortcut to retrieve the value of an item using the selectSingleNode method, you could append code to the end, like so:
XPathAPI.selectSingleNode(this.firstChild, "/root/node").firstChild.nodeValue;
To retrieve an attribute’s value, you could use the following:
XPathAPI.selectSingleNode(this.firstChild, "/root/node").attributes.att;
To use a relative path, you have to start at the parent node of the element that you’re searching for. The following two examples could accomplish this functionality:
XPathAPI.selectSingleNode(this.firstChild.childNodes[0], "node"); XPathAPI.setNodeValue(this.firstChild.childNodes[0], "node", "new value");
A great way to find all the matching node names without worrying about the path or the parent node is by adding a wildcard. This can be achieved by using the following code:
XPathAPI.getEvalString(this.firstChild, "/*/node"); XPathAPI.selectNodeList(this.firstChild, "/*/node"); XPathAPI.selectSingleNode(this.firstChild, "/*/node"); XPathAPI.setNodeValue(this.firstChild, "/*/node", "new value");
The wildcard is useful if you want to change the values of all the nodes with the name that you’re searching. In the example, we would change all of the node elements’ values to "new value". Another use for the wildcard is in the selectNodeList method: You can retrieve all of the elements by name without knowing the path or parent.
For advanced searches, you can combine different search methods. For example, wildcards can be combined with an attribute search:
XPathAPI.selectSingleNode(this._xml.firstChild, "/*/node[@att=’a1’").firstChild.nodeValue;