Qt修改完XML文件<?xml version="1.0" encoding="UTF-8"?>双引号变成乐单引号
时间: 2023-07-06 18:35:11 浏览: 200
你可以使用Qt中的QXmlStreamWriter类来修改XML文件,并通过设置setAutoFormatting和setAutoFormattingIndent参数来控制输出格式。为了将双引号替换为单引号,你可以在写入XML节点时使用replace函数来替换字符串中的双引号为单引号。以下是一个示例代码:
```c++
#include <QCoreApplication>
#include <QFile>
#include <QXmlStreamReader>
#include <QXmlStreamWriter>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// 打开XML文件进行读取
QFile file("input.xml");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
qDebug() << "Failed to open file";
return -1;
}
// 创建XML读取器
QXmlStreamReader reader(&file);
// 打开输出文件进行写入
QFile outFile("output.xml");
if (!outFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
qDebug() << "Failed to open output file";
return -1;
}
// 创建XML写入器
QXmlStreamWriter writer(&outFile);
writer.setAutoFormatting(true);
writer.setAutoFormattingIndent(2);
// 开始读取XML文件
while (!reader.atEnd() && !reader.hasError()) {
QXmlStreamReader::TokenType token = reader.readNext();
if (token == QXmlStreamReader::StartElement) {
// 写入XML节点
writer.writeStartElement(reader.name().toString());
// 写入XML节点属性
foreach (const QXmlStreamAttribute& attr, reader.attributes()) {
writer.writeAttribute(attr.name().toString(),
attr.value().toString().replace('"', '\''));
}
} else if (token == QXmlStreamReader::EndElement) {
// 关闭XML节点
writer.writeEndElement();
} else if (token == QXmlStreamReader::Characters) {
// 写入XML节点文本内容
writer.writeCharacters(reader.text().toString());
}
}
// 关闭读取器和写入器
reader.clear();
outFile.close();
return 0;
}
```
这个示例程序会将input.xml文件中的双引号替换为单引号,并将结果写入到output.xml文件中。当然,你需要根据自己的实际需求来修改代码。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)