QT中基于流的XML解析

    技术2022-05-20  52

       今天通过QXmlStreamReader类实现了对XML文件的解析。

       实现代码:                                                                                                  

       QString ExeStr[2] = {NULL}; typedef struct _SrcDestPath { QString Content; QString SrcPath; QString DestPath; }SrcDestPath; SrcDestPath Path[100] = {NULL}; int index = -1; int ExeIndex = -1; QXmlStreamReader streamxml; QFile file("E://QT//copy//copy.xml"); file.open(QFile::ReadOnly|QFile::Text); streamxml.setDevice(&file); while(!streamxml.atEnd()) { streamxml.readNext(); if(streamxml.isStartElement()) { if(streamxml.name() == "beforecopy") { ExeIndex = 0; } if(streamxml.name() == "aftercopy") { ExeIndex = 1; } if(streamxml.name() == "copy") { index++; } if(streamxml.name() == "run") { ExeStr[ExeIndex] = streamxml.readElementText(); } if(streamxml.name() == "content") { Path[index].Content = streamxml.readElementText(); } if(streamxml.name() == "source") { Path[index].SrcPath = streamxml.readElementText(); } if(streamxml.name() == "dest") { Path[index].DestPath = streamxml.readElementText(); } } }

       对应的XML文件:

       <copying> <beforecopy> <run>hello.exe</run> </beforecopy> <copy> <content>content1</content> <source>D:/test/testVFP</source> <dest>D:/test/copy1</dest> </copy> <copy> <content>content2</content> <source>D:/test/WinAPI1/WinAPI1.ncb</source> <dest>D:/test/copy2</dest> </copy> <aftercopy> <run>nihao.exe</run> </aftercopy> </copying>

     

      在实现的过程中也遇到了一些问题:

      1、setDevice(&file)中的参数应为IODevice*型,一般用QFile*赋值,而且这样对应到指定的XML文件很方便。一开始我一直不成功,readNext()返回值为1,invalid,errorStr()的结果是:premature end of document。查了半天资料原来是file要open才行,郁闷啊!因为在QDomDocument类中并没有这样的操作,习惯性思维啊。

      2、QXmlStreamReader给我们带来了太大的方便了,readNext()函数就是使劲往下读节点,而name()函数可以获得节点名。知道了自己想要节点的text内容就很方便了,先找到节点,再一个readElementText()就OK了。QXmlStreamReader真的是很方便啊,一个while循环再加if判断就搞定。而我们的QDomDocument就自愧不如了,要一层一层往里面找,写得时候要随时关注自己要处理的XML文件,按照固定套路操作,头都绕晕了,麻烦啊。不知道是我的方法没对还是什么,嘿嘿!

      

       在处理的过程中接触了一个新的有关QString的类QStringRef,没有具体研究,有空研究了在分享。

      

      

     

       

     


    最新回复(0)