xml - QXmlStreamWriter 查找标记值并替换为另一个特定值
问题描述
我有一个 xml 文件,其中包含英语和法语字符串作为消息。我正在尝试从 xml 文件中读取特定元素并用另一个特定值替换它们的值。
示例(在下面的 xml 文件中):将“Bonjour le monde”替换为“bonjour le monde à nouveau”。
知道如何使用 QXmlStreamReader 和 QXmlStreamWriter 来实现这一点吗?我的示例程序无法正常工作。我正在使用 qt 5.14.0
//xml文件:myfile.xml
<?xml version='1.0' encoding='utf-8'?>
<TS language="fr_FR" version="2.1">
<context>
<name>TRStringFactory</name>
<message>
<location filename="test.cpp" line="28" />
<source>none</source>
<translation type="unfinished">aucun</translation>
</message>
<message>
<location filename="test.cpp" line="29" />
<source>hello world</source>
<translation type="unfinished">Bonjour le monde</translation>
</message>
</context>
</TS>
解决方案
答案:-->
void updateXMLFile(QString fileName)
{
if (fileName != "")
{
QDomDocument document;
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly))
return;
if (!document.setContent(&file))
{
file.close();
return;
}
file.close();
QString in = "aucun";
QString out = "ravi gupta";
QDomElement root = document.documentElement();
QString name = root.tagName();
qDebug()<<"tag name"<<name;
QDomNode fChild = root.firstChild();
while(!fChild.isNull())
{
QDomElement fElement = fChild.toElement();
if(!fElement.isNull())
{
qDebug()<<"fElement.tagName() : " <<fElement.tagName();
if(fElement.tagName() == "context" )//Some Dummy tagname)
{
QDomNode enabledChecks = fChild.firstChild();
while(!enabledChecks.isNull())
{
QDomElement checkName = enabledChecks.toElement();
//Some Code
QDomNode sChild = enabledChecks.firstChild();
while (!sChild.isNull())
{
QDomElement x = sChild.toElement();
qDebug()<<"second child : " <<x.tagName()<<x.text();
if(x.text() == in)
{
// create a new node with a QDomText child
QDomElement newNodeTag = document.createElement(QString("translation"));
QDomText newNodeText = document.createTextNode(out);
newNodeTag.appendChild(newNodeText);
checkName.replaceChild(newNodeTag,x);
//sChild.removeChild(x);
qDebug()<<"matched";
// Save content back to the file
if (!file.open(QIODevice::Truncate | QIODevice::WriteOnly)) {
qDebug("Basically, now we lost content of a file");
return;
}
file.resize(0);
QTextStream stream;
stream.setDevice(&file);
document.save(stream, 4);
file.close();
}
sChild = sChild.nextSibling();
}
enabledChecks = enabledChecks.nextSibling();
}
}
}
fChild = fChild.nextSibling();
}
}
}
推荐阅读
- postgresql - PostgreSQL => ALTER TABLE without timezone -> with timezone, using select for TZ
- java - 应用程序关闭后,Android 服务不存在
- c# - 在侦听用户输入时在不同的线程上运行方法
- c - Mini-GMP Arduino 打印
- c - 在 C 中为动态数字输入读取字符串时出现问题
- xamarin - 如何将通知的小图标设置为应用程序的图标?
- java - Java 语言练习与数组
- java - 为什么 Kotlin 没有显式类型?
- javascript - Angular 动态加载的模块需要使用根注入器服务
- python - urllib.request- HTTPError:HTTP 错误 403:禁止