C++ 如何使用Qt DOM使用此语法获取xml属性
我正在使用Qt DOM XML解析器,遇到了如下属性定义的问题:C++ 如何使用Qt DOM使用此语法获取xml属性,c++,xml,qt,dom,xml-parsing,C++,Xml,Qt,Dom,Xml Parsing,我正在使用Qt DOM XML解析器,遇到了如下属性定义的问题: <special-prop key="A">1</special-prop> Element text: "1" Attributes found: true Attributes found: 1 Name: "" Value: "" 解决方案: #include <QByteArray> #include <QDebug> #include <QDomDocu
<special-prop key="A">1</special-prop>
Element text: "1"
Attributes found: true
Attributes found: 1
Name: ""
Value: ""
解决方案:
#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;
}
您需要迭代属性映射:
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();
}
…这里,女士们,先生们,请大家考虑一下,这是一个如何明确地提出好问题的例子。荣誉
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"