XPath introduction and references

Posted by Albert Gareev on Nov 23, 2009 | Categories: XML Data

Parent page: Service Functions – XML (QTP, VBScript) 

Note. Although there could be no “reusable function” that would construct XPath for you, I store current post under “XML Service Functions” category, as it’s closely related to it. XPath is fairly simple to learn and very powerful in use. 
You can use free XPath Designer Tool to validate queries you constructed.

What is XPath? The each element in XML tree has its own unique address.
The XPath expressions provide the ability to navigate around the tree, selecting elements (groups of nodes, single nodes, attributes, text values, etc.) by a variety of conditions.

What does it mean? You can address any XML tree element without looping through the tree, i.e. as you use array[index] notation to get an element of the array, for XML you would use XML[XPath].

How basic XPath syntax looks like? You will see that it is very similar to a disk folder/file addressing, as it’s a tree structure too.
For example, filepath “c:\documents\personal\pictures\1.jpg”  in XML-XPath notation would look like “./documents/personal/pictures/picture[1]”.

What are the differences?
If we can address only one file with a single pathstring, in XML we can address a collection of elements with a single pathstring. If in any folder there could be no duplicated filenames, in XML it’s allowed: elements will be referred by index. 
If we can address an element of an array only by index value, in XML we can address elements by index value or by element value. If with arrays all indexing is absolute, in XML it could be relative.

Get a collection of book items in a library XML structure. Xpath = “./library/book”.
Get first book in the collection. Xpath = “./library/book[1]”.
Get a collection of book items written by James Bach. Xpath = “descendant::book[author/@firstname=’James’ and author/@lastname=’Bach’]“.

Documentation and references.

W3C XML Path Language

W3Schools XPath Introduction

Using XML Queries and Transformations

  • Leave a Reply

    * Required
    ** Your Email is never shared

Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported
This work by Albert Gareev is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported.