原先存在的xml文件
<?xml version="1.0" encoding="UTF-8"?>
<root>
<first>4</first>
<second>1</second>
<add>1</add>
</root>
QString fileName = tmp_dir + "/xxx.xml";
QDomDocument doc("myDocument");
QFile inputFile(fileName);
if (!inputFile.open(QFile::ReadOnly | QFile::Text))
{
inputFile.close();
return;
}
if (!doc.setContent(&inputFile))
{
qDebug() << "doc.setContent() error!\n";
inputFile.close();
return;
}
inputFile.close();
QDomElement docElem = doc.documentElement();
if (docElem.tagName() == "root")
{
QDomNode level_1_child_node = docElem.firstChild();
while (!level_1_child_node.toElement().isNull())
{
if (level_1_child_node.toElement().tagName() == "second")
{
QDomElement menuOnlyElement = doc.createElement("add");
QDomText text = doc.createTextNode("1");
menuOnlyElement.appendChild(text);
docElem.appendChild(menuOnlyElement);
}
level_1_child_node = level_1_child_node.nextSibling();
}
}
if (!inputFile.open(QFile::WriteOnly | QFile::Truncate))
{
inputFile.close();
return;
}
QTextStream ts(&inputFile);
ts.reset();
ts.setCodec("utf-8");
doc.save(ts,4,QDomNode::EncodingFromTextStream);
inputFile.close();
相信大家都看得懂,下面就几个点说一下
1.
QDomElement menuOnlyElement = doc.createElement("add");
QDomText text = doc.createTextNode("1");
menuOnlyElement.appendChild(text);
docElem.appendChild(menuOnlyElement);
QFile::Truncate