下面的代码利用Qt的QDomDocument等类来读取xml文件exm.xml,并写入另一个文件exm2.xml

代码:


#include <QDomNode>
#include <QDomElement>
#include <QDomDocument>
#include <QFile>
#include <QDebug>
#include <QDomProcessingInstruction>


int main(int argc, char *argv[])
{
    QDomDocument domDoc, domNew("");
	//header
    QDomProcessingInstruction domInstrct = domNew.createProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\"");
    QDomElement dom;
    QFile fp("exm.xml");
    if (fp.open(QFile::ReadWrite))
    {
        domNew.appendChild(domInstrct);
        domDoc.setContent(&fp, true);//读取exm.xml的内容
        auto domEle = domDoc.documentElement();//将exm.xml的内容转换为节点格式。由于xml采用一个根节点下面展开若干节点的格式,所以domEle是根节点
        qDebug() << domEle.tagName();
        qDebug() << domDoc.toString();
        auto domChild = domEle.firstChildElement();//获取根节点的第一个子节点
        auto dom = domNew.createElement(domEle.tagName());//创建一个与根节点同名的根节点
        domNew.appendChild(dom);
        while (!domChild.isNull()) {//遍历根节点
            auto n1 = domNew.createElement(domChild.tagName());//根据当前读取到的节点名字,在domNew里面再创建一个同名节点
            n1.setAttribute("value", domChild.attribute("value"));//给这个同名节点的value属性赋值
            dom.appendChild(n1);
            domChild = domChild.nextSibling().toElement();//走向下一个子节点
        }
        fp.close();
    }

	//创建新文件exm2.xml,并把domNew的内容写入
    QFile fp2("exm2.xml");
    if (fp2.open(QFile::WriteOnly | QFile::Truncate | QFile::Text)) {
        fp2.write(domNew.toString().toLatin1());
        //qDebug() << domNew.toString();
        fp2.close();
    }
}

主要语句的功能已经在代码中注释了。

完整项目见我的资源使用qt读取xml文件并写入另一个文件-C++文档类资源-CSDN下载

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐