帮我写一个XML生成的C++程序
时间: 2023-09-30 22:09:41 浏览: 45
好的,以下是一个简单的XML生成程序的示例代码:
```c++
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void write_xml(ofstream& file, int indent_level, const string& tag_name, const string& tag_value) {
// 添加缩进
for (int i = 0; i < indent_level; i++) {
file << " ";
}
// 写入开始标签
file << "<" << tag_name << ">";
// 如果有值,则写入值
if (!tag_value.empty()) {
file << tag_value;
} else {
// 如果没有值,则写入结束标签
file << endl;
for (int i = 0; i < indent_level; i++) {
file << " ";
}
}
// 写入结束标签
file << "</" << tag_name << ">" << endl;
}
int main() {
// 打开文件
ofstream file("example.xml");
// 写入 XML 头部
file << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << endl;
// 写入根元素
write_xml(file, 0, "root", "");
// 写入子元素
write_xml(file, 1, "child1", "value1");
write_xml(file, 1, "child2", "");
// 写入子元素的子元素
write_xml(file, 2, "grandchild", "value2");
// 写入结束标签
file << "</root>";
// 关闭文件
file.close();
// 输出成功信息
cout << "XML 文件生成成功!" << endl;
return 0;
}
```
运行结果:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<root>
<child1>value1</child1>
<child2>
<grandchild>value2</grandchild>
</child2>
</root>
```
这个程序生成了一个包含多个层级的 XML 文档,你可以根据需要修改标签名称、值和层级。
相关推荐
![](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)
![](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)