本文件用QDomDocument读取XML文件
XML文件路径:D:Testqtxmltest.xml内容:
- <?xmlversion="1.0"encoding="GBK"?>
- <Root>
- <TestAttr="属性">金财税</Test>
- </Root>
1、新建一个Qt工程,命名为xml。
2、在xml.pro文件加入一句 Qt += xml
3、在界面上放一个PushButton和一个TextEdit
main.cpp
- #include<QtGui/QApplication>
- #include"mainwindow.h"
- #include<QTextCodec>
- intmain(intargc,char*argv[])
- {
- QApplicationa(argc,argv);
- QTextCodec::setCodecForCStrings(QTextCodec::codecForName("GBK"));
- QTextCodec::setCodecForLocale(QTextCodec::codecForName("GBK"));
- QTextCodec::setCodecForTr(QTextCodec::codecForName("GBK"));
- MainWindoww;
- w.show();
- returna.exec();
- }
在PushButton的clicked()槽中写读取xml的代码
mainwindow.cpp
- #include"mainwindow.h"
- #include"ui_mainwindow.h"
- #include<QDomDocument>
- #include<QDomElement>
- #include<QDomAttr>
- #include<QFile>
- MainWindow::MainWindow(QWidget*parent):
- QMainWindow(parent),
- ui(newUi::MainWindow)
- {
- ui->setupUi(this);
- }
- MainWindow::~MainWindow()
- {
- deleteui;
- }
- voidMainWindow::on_pushButton_clicked()
- {
- QFilefile("D:/Test/qt/xml/test.xml");
- if(!file.open(QFile::ReadOnly|QFile::Text))
- {
- ui->textEdit->append(tr("XML文件打开失败"));
- }
- QDomDocumentdoc;
- QStringerrStr;
- interrLine,errCol;
- if(!doc.setContent(&file,false,&errStr,&errLine,&errCol))
- {
- ui->textEdit->append(tr("指定XML内容失败原因:")+errStr);
- }
- file.close();
- QDomElementroot=doc.documentElement();
- ui->textEdit->append(root.nodeName());
- QDomElementchild=root.firstChildElement();
- ui->textEdit->append(child.nodeName());
- ui->textEdit->append(child.text());
- ui->textEdit->append(child.attributeNode("Attr").nodeName());
- ui->textEdit->append(child.attributeNode("Attr").nodeValue());
- }
运行结果:
在上一节的工程中加入一个按钮,在按钮的clicked()槽中加入以下代码:
- voidMainWindow::on_pushButton_2_clicked()
- {
- QFilefile("C:/new.xml");
- if(!file.open(QFile::WriteOnly|QFile::Text))
- {
- ui->textEdit->append(tr("文件打开失败"));
- }
- doc.appendChild(doc.createProcessingInstruction("xml","version="1.0"encoding="GBK""));
- QDomElementroot=doc.createElement("Root");
- doc.appendChild(root);
- QDomElementchild=doc.createElement("Test");
- QDomTexttext=doc.createTextNode(tr("金财税"));
- child.appendChild(text);
- child.setAttribute("Attr","属性");
- root.appendChild(child);
- QTextStreamout(&file);
- doc.save(out,4);
- file.close();
- }
还需要在源文件头部加入引用:
- #include<QTextStream>
如果执行成功,会在C盘里找到new.xml文件,文件内容如下:
- <?xmlversion="1.0"encoding="GBK"?>
- </Root>
本文出自 “自由自我” 博客,请务必保留此出处http://www.52php.cn/article/p-aqqehpit-ev.html (编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|