![]() |
Libzeep comes with a XPath 1.0 implementation. You can use this to locate elements in a DOM tree easily. For a complete description of the XPath specification you should read the documentation at e.g. http://www.w3.org/TR/xpath/ or https://www.w3schools.com/xml/xpath_intro.asp.
The way it works in libzeep is that you can call find()
on an zeep::xml::element
object and it will return a zeep::xml::element_set
object which is actually a
std::list
of zeep::xml::element
pointers of the elements that conform to the specification in XPath passed
as parameter to find()
.
An alternative method find_first()
can be used to return only the first element.
An example where we look for the first person in our test file with the lastname Jones:
zeep::xml::element
* jones = doc.child()->find_first("//person[lastname='Jones']");
XPath constructs can reference variables. As an example, suppose you need to find nodes in a special XML Namespace but you do not want to find out what the prefix of this Namespace is, you could do something like this:
#include <iostream> #include <zeep/xml/document.hpp> #include <zeep/xml/xpath.hpp> int main() { using namespace zeep::xml::literals; auto doc = R"(<bar xmlns:z="https://www.hekkelman.com/libzeep"> <z:foo>foei</z:foo> </bar>)"_xml;zeep::xml::context ctx; ctx.set("ns", "https://www.hekkelman.com/libzeep");
auto xp = zeep::xml::xpath("//*[namespace-uri() = $ns]");
for (auto n: xp.evaluate<zeep::xml::element>(doc, ctx)) std::cout << n->str() << std::endl; return 0; }
Create an xpath context and store our variable |
|
Create an xpath object with the specified XPath using the variable |
|
Iterate over the result of the evaluation of this XPath, the result will consist of zeep::xml::element object pointers |
![]() |
Note |
---|---|
Please note that the evaluation of an XPath returns pointers to XML nodes. Of course these are only valid as long as you do not modify the the document in which they are contained. |