感谢:l270378034的帮助
源xml文件:
<kdevelop>
<general>
<author>zeki</author>
<email>caizhiming@tom.com</email>
</general>
</kdevelop>
源程序:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
changeSave();
}
MainWindow::~MainWindow()
{
delete ui;
}
bool MainWindow::openXmlFile(QString FilePath)
{
QFile file( FilePath );
if( !file.open( QFile::ReadOnly | QFile::Text ) )
{
qDebug() << QObject::tr("error::ParserXML->OpenXmlFile->file.open->%s\n") << FilePath;
return false;
}
if( !m_doc.setContent( &file ) )
{
qDebug() << QObject::tr("error::ParserXML->OpenXmlFile->doc.setContent\n") << FilePath;
file.close();
return false;
}
file.close();
return true;
}
bool MainWindow::changeSave()
{
if(!openXmlFile("/home/qust/qt/XML/2.xml"))
{
return false;
}
//修改保存xml
QDomElement root = m_doc.documentElement();
if(root.tagName()!= "kdevelop")
return false;
QDomNode n = root.firstChild();
while ( !n.isNull() )
{
QDomElement e = n.toElement();
if( !e.isNull())
{
if( e.nodeName() == "general" )
{
QDomNodeList list = e.childNodes(); //获得元素e的所有子节点的列表
for(int a=0; a<list.count(); a++) //遍历该列表
{
QDomNode node = list.at(a);
if(node.isElement())
{
if( node.nodeName() == "author" )
{ QDomNode oldnode = node.firstChild(); //标签之间的内容作为节点的子节点出现,得到原来的子节点
node.firstChild().setNodeValue("csdn"); //用提供的value值来设置子节点的内容
QDomNode newnode = node.firstChild(); //值修改过后
node.replaceChild(newnode,oldnode); //调用节点的replaceChild方法实现修改功能
}
if( node.nodeName() == "email" )
{
QDomNode oldnode = node.firstChild();
node.firstChild().setNodeValue("test@tom.com");
QDomNode newnode = node.firstChild();
node.replaceChild(newnode,oldnode);
}
}
}
}
}
n = n.nextSibling();
}
QFile filexml("/home/qust/qt/XML/2.xml");
if( !filexml.open( QFile::WriteOnly | QFile::Truncate) ){
qWarning("error::ParserXML->writeOperateXml->file.open\n");
return false;
}
QTextStream ts(&filexml);
ts.reset();
ts.setCodec("utf-8");
m_doc.save(ts, 4, QDomNode::EncodingFromTextStream);
filexml.close();
return true;
}
运行后:
<kdevelop>
<general>
<author>csdn</author>
<email>test@tom.com</email>
</general>
</kdevelop>
QDomNode QDomNode::nextSibling () const
Returns the next sibling in the document tree. Changing the returned node will also change the node in the document tree.
If you have XML like this:
<h1>Heading</h1>
<p>The text...</p>
<h2>Next heading</h2>
and this QDomNode represents the <p> tag, nextSibling() will return the node representing the <h2> tag.
sibling 1.同层级 2.同辈 3.兄弟或姊妹。 4.同胞 Sibling 1.同胞兄妹