此文档main.cpp文件分为两部分:
1】上面是读取txt文档的代码
2】下面是读取和修改xml文档的内容,并且保存xml修改的代码
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QDomDocument>
#include <QFile>
#include <QDomNode>
#include <QDebug>
#include <QTextStream>
#include <QDomNodeList>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
//读取txt文件
// QFile file("new.txt");
// if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
// qDebug()<<"open file false";
// while(!file.atEnd()){
// QByteArray line=file.readLine();
// qDebug()<<"line:"<<line;
// }
//读取xml文件
QDomDocument doc;
QFile file1("am.xml");
if (!file1.open(QIODevice::ReadOnly))
{
qDebug()<<"open file false";
}
QString errorStr;
int errorLine, errorCol;
if (!doc.setContent(&file1,&errorStr,&errorLine,&errorCol))
{
file1.close();
qDebug()<<"setting file content false";
}
file1.close();
QDomElement docElem = doc.documentElement();
QDomNode n = docElem.firstChild();//
while (!n.isNull())
{
QDomElement e = n.toElement(); // try to convert the node to an element.
if(!e.isNull()){
if(e.nodeName()=="item")
{
QDomNodeList list=e.childNodes();
for(int a=0;a<list.size();a++){
QDomNode node=list.at(a);
if(node.isElement()){
if(node.nodeName()=="num"){
QDomNode oldnode=node.firstChild();
node.firstChild().setNodeValue("csdn");
QDomNode newnode=node.firstChild();
node.replaceChild(newnode ,oldnode);
qDebug()<<"执行到num里面,修改num值";
qDebug()<<"num:"<<node.firstChild().nodeValue();
}
if(node.nodeName()=="hei")
{
QDomNode oldnode=node.firstChild();
node.firstChild().setNodeValue("56");
QDomNode newnode=node.firstChild();
node.replaceChild(newnode,oldnode);
qDebug()<<"执行到hei里面,修改hei值";
qDebug()<<node.firstChild().nodeValue();
}
}
}
}
}
if (!e.isNull())
{
qDebug() << qPrintable(e.tagName()) << endl; // the node really is an element.
}
n = n.nextSibling();
}
//保存修改后的xml文件
QFile filexml("am.xml");
if(!filexml.open(QFile::WriteOnly | QFile::Truncate))
{
qWarning("error:ParserXml ->writeXmlOPerator->file.open\n");
return false;
}
QTextStream ts(&filexml);
ts.reset();
ts.setCodec("utf-8");
doc.save(ts,2,QDomNode::EncodingFromTextStream);
filexml.close();
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}