I am spoiled (rotten, to be sure) by C# and its XML manipulation classes in the System.Xml namespace. I can load an XML file into an XmlDocument. I can search the whole document for nodes that match an XPath expression, using XmlNode.SelectNodes( "an xpath expression" ). The result is an XmlNodeList that contains XmlNode objects that I can iterate over.
Now I am using C++ Qt (versions 4.7.1 and 4.8, but the particular version may not be important). I can load an XML file into a QDomDocument. But, I am frustrated that I cannot search the document using an XPath expression in a similar way that I did in C#.
I have had limited success using QXmlQuery to find stuff in the XML file. If I write the query in just the right way, I can obtain a QStringList of results, iterate that QStringList, and then store the data somewhere for use later.
But, I still want to be able to obtain a collection of QDomNode objects that are in the document, directly via an XPath expression. One specific use case is to find one element whose "name" attribute has a certain value, and then replace that element with a new element. That is why I want the QDomNode object itself, not just some string-based or other representation of the XML content that QXmlQuery can provide. For the specific use case just mentioned, I am getting by using QDomElement.elementsByTagName() and iterating those elements, but it is not as flexible nor as cool as XPath.
Is it just wishful thinking? Would it be worth the effort to develop some new class that implements the QAbstractXmlReceiver interface? Or, would I just end up with a new collection of data that has no direct relationship to the QDomNode objects in the QDomDocument?
The following is the utility function I use to search for nodes in a
QDomDocumentusing an XPath expression. It uses theQDomNodeModelclass suggested by @Alejandro, downloadable from https://adared.ch/qdomnodemodel-qxmlquery. It is based on the usage example from https://www.qtcentre.org/threads/37645-QAbstractXmlNodeModel-implementation-QDomNodeModel-QXmlQuery. Thanks to Stanislaw Adaszewski, who provided both theQDomNodeModelclass and the usage example.There are a few methods in
QDomNodeModelthat are commented as not implemented. However, for the simple XML content that I needed to search,QDomNodeModelis sufficient as-is.In my application, I load an XML file, and use the above utility function to search it.
The example XML content to search.