XPath Tutorial



XPath Cheat Sheet


XPath expression is used to select XML nodes or more.



Selecting Nodes

/item

: Select 'item' nodes from the root node.


//item

: Select all 'item' nodes.


item/price

: Select all 'price' elements that are children of 'item' elements.


item/*

: Select children node of 'item'.


/item[2]

: Select the second 'item' element from the root node.


/item/@id

: Select 'id' attribute of 'item' element.


/item/[@id="123"]

: Select 'item' elements with attribute 'id' of value 123.


/item/[@price > 100]

: Select 'item' elements with attribute 'price' greater than 100.


/processing-instruction('xml-stylesheet')

: Select a processing instruction with the target 'xml-stylesheet'.


/item/glove | /item/shoes

: Select 'glove' and 'shoes' elements that are children of 'item' elements.


10 + 5

: Calculate 10 + 5


//Coffee[starts-with(@name, 'Ethiopia')]

: Select all 'Coffee' elements with an attribute called 'name' that its value starts with 'Ethiopia'.


//Item[contains(@name, 'shield')]

: Select all 'Item' elements with an attribute called 'name' that its value contains 'shield'.


//Item[last()]

: Select all the last 'Item' elements among the 'Item' children elements for each parent.


//Item[text()='New item']

: Select all 'Item' elements that have the text 'New item'.


//Item[contains(text(),'New')]

: Select all 'Item' elements that have the text containing 'New' as a substring.


//Item[*]

: Select all 'Item' elements that have its child.


//Item[Magic]

: Select all 'Item' elements that have a child element 'Magic'.


//Item/text()

: Select all the texts of 'Item' elements.