Qt以QXmlStreamReader 遍历.ts文件的C++代码,查找所有source为abc的字段,修改其translation字段为123,并写入保存文件
时间: 2024-02-27 12:57:55 浏览: 82
xml.zip_qt xml_the code_xml QT
下面是代码示例:
```cpp
#include <QtCore/QCoreApplication>
#include <QtCore/QFile>
#include <QtCore/QXmlStreamReader>
#include <QtCore/QXmlStreamWriter>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString fileName = "example.ts";
QFile file(fileName);
if (!file.open(QFile::ReadOnly | QFile::Text)) {
qDebug() << "Failed to open file.";
return -1;
}
QXmlStreamReader xmlReader(&file);
xmlReader.setNamespaceProcessing(false);
QFile outputFile("modified.ts");
if (!outputFile.open(QFile::WriteOnly | QFile::Text)) {
qDebug() << "Failed to open output file.";
return -1;
}
QXmlStreamWriter xmlWriter(&outputFile);
xmlWriter.setAutoFormatting(true);
xmlWriter.writeStartDocument();
xmlWriter.writeStartElement("TS");
while (!xmlReader.atEnd()) {
xmlReader.readNext();
if (xmlReader.isStartElement() && xmlReader.name() == "context") {
xmlReader.readNext();
while (!(xmlReader.isEndElement() && xmlReader.name() == "context")) {
if (xmlReader.isStartElement() && xmlReader.name() == "message") {
QString source;
QString translation;
bool found = false;
xmlReader.readNext();
while (!(xmlReader.isEndElement() && xmlReader.name() == "message")) {
if (xmlReader.isStartElement() && xmlReader.name() == "source") {
source = xmlReader.readElementText();
} else if (xmlReader.isStartElement() && xmlReader.name() == "translation") {
translation = xmlReader.readElementText();
}
if (source == "abc" && !translation.isEmpty()) {
found = true;
translation = "123";
}
xmlReader.readNext();
}
if (found) {
xmlWriter.writeStartElement("message");
xmlWriter.writeStartElement("source");
xmlWriter.writeCharacters(source);
xmlWriter.writeEndElement();
xmlWriter.writeStartElement("translation");
xmlWriter.writeCharacters(translation);
xmlWriter.writeEndElement();
xmlWriter.writeEndElement();
}
}
xmlReader.readNext();
}
}
}
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
return a.exec();
}
```
这段代码使用 `QXmlStreamReader` 解析 `.ts` 文件,并且使用 `QXmlStreamWriter` 写入修改后的 `.ts` 文件。对于每个 `context`,它会遍历所有的 `message`,并且查找 `source` 为 `abc` 的字段,如果找到了,就将其 `translation` 字段修改为 `123` 并且写入 `.ts` 文件。注意,这个代码没有处理错误情况,实际使用时可能需要加入相关的错误处理代码。
阅读全文