uniquenamehere
uniquenamehere

Reputation: 1949

How to get xml attributes with this syntax using Qt DOM

I am using Qt DOM XML parser and have run in to a problem with attributes defines like this:

<special-prop key="A">1</special-prop>

The two data I want from the above line is A and 1. I am able to get the 1, but not the key/value attribute pair.

My code and debug output below:

#include <QByteArray>
#include <QDebug>
#include <QDomDocument>
#include <QString>

int main(int argc, char *argv[])
{
    QString input("<special-prop key=\"A\">1</special-prop><special-prop key=\"B\">2</special-prop><special-prop key=\"C\">3</special-prop>");
    QByteArray bytes = input.toUtf8();

    QDomDocument doc;
    doc.setContent(bytes);

    QDomNodeList start = doc.elementsByTagName("special-prop");

    QDomNode node = start.item(0);
    qDebug() << "Element text: " << node.toElement().text();
    qDebug() << "Attributes found: " << node.hasAttributes();

    QDomNamedNodeMap map = node.attributes();
    qDebug() << "Attributes found: " << map.length();

    QDomAttr attr = node.toAttr();
    qDebug() << "Name: " << attr.name();
    qDebug() << "Value: " << attr.value();

    getchar();

    return 0;
}

The output looks like this:

Element text:  "1"
Attributes found:  true
Attributes found:  1
Name:  ""
Value:  ""

SOLUTION:

#include <QByteArray>
#include <QDebug>
#include <QDomDocument>
#include <QString>

int main(int argc, char *argv[])
{
    QString input("<special-prop key=\"A\">1</special-prop><special-prop key=\"B\">2</special-prop><special-prop key=\"C\">3</special-prop>");
    QByteArray bytes = input.toUtf8();

    QDomDocument doc;
    doc.setContent(bytes);

    QDomNodeList start = doc.elementsByTagName("special-prop");
    int length = start.length();
    int lengthInner;
    for (int i = 0; i < length; i++)
    {
        auto node = start.at(i);
        auto map = node.attributes();

        lengthInner = map.length();
        for (int j = 0; j < lengthInner; j++)
        {
            auto mapItem = map.item(j);
            auto attribute = mapItem.toAttr();
            qDebug() << "Name: " << attribute.name();
            qDebug() << "Value: " << attribute.value();
        }

        qDebug() << "Element text: " << node.toElement().text();
        qDebug() << "Attributes found: " << node.hasAttributes();
    }

    getchar();

    return 0;
}

Output:

Name:  "key"
Value:  "A"
Element text:  "1"
Attributes found:  true

Upvotes: 2

Views: 2987

Answers (1)

You need to iterate over the attribute map:

for (int i = 0; i < map.length(); ++i) {
   auto inode = map.item(i);
   auto attr = inode.toAttr();
   qDebug() << "Name: " << attr.name();
   qDebug() << "Value: " << attr.value();
}

The output is then as follows:

Element text:  "1"
Attributes found:  true
Attributes found:  1
Name:  "key"
Value:  "A"

Upvotes: 2

Related Questions