如何使用Qt DOM使用此语法获取xml属性

时间:2015-08-18 20:39:47

标签: c++ xml qt dom xml-parsing

我正在使用Qt DOM XML解析器并且遇到了属性定义问题,如下所示:

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

我想从上面一行得到的两个数据是A和1.我能够获得1,但不能获得键/值属性对。

我的代码和调试输出如下:

#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;
}

输出如下:

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;
}

输出:

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

1 个答案:

答案 0 :(得分:2)

您需要遍历属性映射:

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();
}

输出如下:

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