So, yesterday I talked about SimpleXML and the basic way to access the XML data. Today I’ll be covering simple XPath queries and modification.
XML Path Language
This language is based off of the simple XML standard of element nodes (<node></node>) and attribute nodes (attribute="value"). Nodes can have a parent (previous node), children (nodes below), and siblings (nodes at the same level).
Here is the basic query syntax:
- nodename: all of children of that named node
- /: selects from the root node
- //: selects nodes in the document from the current node, that match the selection no matter where they are
- .: current node
- ..: parent node
- @: attributes
- [query]: which named node do you want
- last(): last child number
- position(): position of the child in the list
Here is some example XML (courtesy of w3schools.com):
-
-
<bookstore>
-
-
<book>
-
<title lang="eng">Harry Potter</title>
-
<price>29.99</price>
-
</book>
-
-
<book>
-
<title lang="eng">Learning XML</title>
-
<price>39.95</price>
-
</book>
-
-
</bookstore>
Example selections:
- //book Selects all book elements
- /bookstore Selects the element bookstore
- /boookstore/book[1] First book child element of bookstore
- /bookstore/book[last()] Last book child element of bookstore
- bookstore All the children of bookstore
- //@lang All attributes with lang
- //title[@lang='eng'] All title elements that have an attribute of lang with value ‘eng’
You can see that there are MANY possibilities for queries here. You can even use wildcards (*) and multiple paths (|). I’m not going to go into the detail here, but there are loads of functions and advanced syntax that allow you to craft detailed queries to retrieve the data you want.
XML Modification
In SimpleXML, you may want to add/change a node. It’s easy if you use the addChild($name) method. For example:
-
$book->addAttribute('color", "white");
-
$book->addChild('name', 'Fluffy');
-
It’s pretty obvious that you can either provide the data for the element, or return the object and add additional data individually.
To remove a node, the best way is to just set it to NULL. That will remove most of it. Sadly, to finish the job, you have to export it to DOM (why, I don’t know).
Finally, you can display your modified XML by using the asXML() class method. If you provide an optional string, it will save it to that path.

