XPath Attributes and Tag Querying
Attributes used to write XPath queries, with examples.
07.11.2015 · 1 min read
We continue with XPath queries.
Usage:
- element: If you query like this, it will bring all elements named "element".
- /: If you start with this, you need to write from the root element to the element you want to reach.
- //: Queries in all elements after the selected element.
- .: The selected element
- ..: The element above the selected element
- @: Used to query in the element's attribute.
Let's continue with examples. There are already examples related to the features above in the previous topic. Now let's query an attribute.
<?php
$xml = simplexml_load_file("library.xml");
$results = $xml->xpath('book[@isbn="9759954949"]'); // We're getting 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 above, we can query for attributes with [@attribute="value"]. Using this with the other features above, we can perform our query operations on XML with the XPath language.