Parse a xml file using c++ & Qt

送分小仙女□ 提交于 2019-12-04 12:14:06

问题


I try to parse a XML-file with the following structure:

<I>
  <C c="test1">
     <H><Pd pd="123"/>
        <f p="789" r="456"/>
     </H>
     <M m="test2">
       <H><Pd pd="3456"/><R r="678"/>
       </H>
     </M>
  </C>
  <T t="0">
     <T2>123</T2>
     <T3>2345</T3>
  </T>
  <T t="1">
     <T1>23456</T1>
     <T2>23</T2>
     <T3>123</T3>
     <T4>456</T4>
  </T>
</I>

I have a List of numbers e.g. 0 and 1 and a search pattern e.g. '23' Now i want to search the XML-file for all T-nodes with t="a number from my list" where one of the child nodes(T1, T2,T3) contain the search pattern.

Can anybody help me getting started with this problem? I want to use the Qt functions but do not really know how to begin.

I'm happy about every hint!


回答1:


Untested, but this is a way I already used Qt to scan in a very simply XML file. Maybe this can give you a hint how to use it here:

QDomElement docElem;
QDomDocument xmldoc;

xmldoc.setContent(YOUR_XML_DATA);
docElem=xmldoc.documentElement();

if (docElem.nodeName().compare("T")==0)
{
    QDomNode node=docElem.firstChild();
    while (!node.isNull())
    {
        quint32 number = node.toElement().attribute("t").toUInt(); //or whatever you want to find here..
        //do something
        node = node.nextSibling();
    }
}



回答2:


For XML things, it was suggested to use QXmlStreamReader and QXmlStreamWriter from QtCore module, just because the QDom and QSax things have been not actively maintained for a while.

http://doc.qt.digia.com/4.7/qxmlstreamreader.html

http://doc.qt.digia.com/4.7/qxmlstreamwriter.html

I will not copy&paste the example code from qt docs to here. Hope you could understand them well. And you also could check examples/xml directory in qt 4.x.




回答3:


you could use QXmlQuery. It act like XQuery (i guess the syntax is the same). And you could parse your xml file with the big advantage of XQuery's flexibility. You can start with a code like this:

QByteArray myDocument;
QBuffer buffer(&myDocument); // This is a QIODevice.
buffer.open(QIODevice::ReadOnly);
QXmlQuery query;
query.bindVariable("myDocument", &buffer);
query.setQuery("doc($myDocument)");

setQuery method allow you to define your search pattern. It can be based on element id, attribute, and so on...as with XQuery. This is QXmlQuery doc page: link



来源:https://stackoverflow.com/questions/12913881/parse-a-xml-file-using-c-qt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!