QXmlQuery xmlQuery; xmlQuery.setQuery("doc('my.xml')/root/group/item[@key=\"ccc\"]"); QString sl; if(!xmlQuery.evaluateTo(&sl)) qDebug() << "parse error\n"; qDebug() <<sl;
xmlQuery.setQuery("doc('my.xml')/root/group/item[@key=\"ccc\"]/@value");
#include <QtCore>#include <QtXmlPatterns>class MessageHandler : public QAbstractMessageHandler { public: MessageHandler() : QAbstractMessageHandler(0) { } QString statusMessage() const { return m_description; } int line() const { return m_sourceLocation.line(); } int column() const { return m_sourceLocation.column(); } protected: virtual void handleMessage(QtMsgType type, const QString &description, const QUrl &identifier, const QSourceLocation &sourceLocation) { Q_UNUSED(type); Q_UNUSED(identifier); m_messageType = type; m_description = description; m_sourceLocation = sourceLocation; } private: QtMsgType m_messageType; QString m_description; QSourceLocation m_sourceLocation;};int main(int argc, char **argv) { QCoreApplication app(argc, argv); QXmlQuery xmlQuery; MessageHandler messageHandler; xmlQuery.setMessageHandler(&messageHandler); xmlQuery.setQuery("doc('my.xml')/root/group/item[@key=\"ccc\"]/@value"); QString sl; if(!xmlQuery.evaluateTo(&sl)) { qDebug() << "error at line " << messageHandler.line() << ":" << messageHandler.column() << endl << messageHandler.statusMessage() << endl; } else { qDebug() <<sl; } return 0;}
DESTDIR = ./CONFIG += console releaseQT += xmlpatternsQT -= guiSOURCES = main.cpp
QDomDocument domDoc;QFile file(m_file);//имя xml-файлаQString attrVal;if(file.open(QIODevice::ReadOnly)){ if(domDoc.setContent(&file)){ QDomElement root = domDoc.documentElement();//возвращает корневой элемент документа QDomElement el = root.firstChildElement(m_tagName); while(!el.isNull()) { if(el.attribute("key") == "ccc"){ attrVal = el.attribute("value"); break; } el = el.nextSiblingElement(m_tagName); } } file.close();}
QString attrValue = getAttr(fileName, tagName, attrName);
C++ (Qt)// var 1xmlQuery.setQuery("string(doc('my.xml')/root/group/item[@key=\"ccc\"]/@value)"); // var 2xmlQuery.setQuery("doc('my.xml')/root/group/item[@key=\"ccc\"]/@value cast as xs:string"); // var 3xmlQuery.setQuery("doc('my.xml')/root/group/item[@key=\"ccc\"]/@value/string()");
C++ (Qt)xmlQuery.setQuery("doc('my.xml')/root/group/item[@key=\"ccc\"]/@value/name()");