XPath Attributes and Element Queries
Write XPath attribute and element queries with practical examples for navigating XML document structures.
07.11.2015 · 1 min read
We continue with XPath queries.
Usage:
- element: Selects all elements with the given name.
- /: Starts from the root element and follows the full path to the target element.
- //: Searches through all matching elements below the selected element.
- .: Refers to the selected element.
- ..: Refers to the parent of the selected element.
- @: Used to query an element's attribute.
Let's continue with an example. The previous article already covered the basics above, so here we will query an attribute.
<?php
$xml = simplexml_load_file("library.xml");
$results = $xml->xpath('book[@isbn="9759954949"]'); // We get the book element whose isbn attribute is 9759954949.
foreach ($results as $key => $value) {
echo $value->title;
}
?>
// Screen Output
Yunus Emre Divani
As you can see, we can query attributes with [@attribute="value"]. By combining this syntax with the other XPath features above, we can write more flexible XML queries.