Can I find all XML nodes with a given attribute in a QDomDocument?
c++, qt, xml
Solution
You will need to recursively scan the document tree to find the elements yourself. For example, to find all elements with a given attribute name:
void findElementsWithAttribute(const QDomElement& elem, const QString& attr, QList<QDomElement> foundElements)
{
if( elem.attributes().contains(attr) )
foundElements.append(elem);
QDomElement child = elem.firstChildElement();
while( !child.isNull() ) {
findElementsWithAttribute(child, attr, foundElements);
child = child.nextSiblingElement();
}
}
QList<QDomElement> foundElements;
QDomDocument doc;
// Load document
findElementsWithAttribute(doc.documentElement(), "myattribute", foundElements);
Problem
I'm using Qt 4.7.4. In my program, each QDomNode in a QDomDocument will have a unique identifier attribute. Is there a simple way to locate all nodes (in this case, only a single node) with a given attribute? Nothing that I have found suggests that this is possible, but I thought that I might as well ask. I suppose that I could place the identifier in a child node of the original node, search for the identifier node, and then take its parent, but I would prefer to keep it in an attribute.