最近在研究 KML文件(也是一种XML格式),忽然发现很多工具都是在线的,使用起来并不顺手,因此编写一个本地的 XML 格式化工具。能够帮助将KML变成容易阅读的格式。
使用方法:
XMLLocalFormatter 输入文件名
之后会生成一个“输入文件名_for.XML”的新文件。
代码如下:
#include <iostream>
#include <fstream>
#include <string>
#include "tinyxml2.h"
using namespace std;
using namespace tinyxml2;
int main(int argc, char* argv[]) {
if (argc != 2) {
cerr << "Usage: xml_formatter input_file" << endl;
return EXIT_FAILURE;
}
string inputFile = argv[1];
// Load the XML file using TinyXML2.
XMLDocument doc;
XMLError error = doc.LoadFile(inputFile.c_str());
if (error != XML_SUCCESS) {
cerr << "Error loading file: " << inputFile << ". Error code: " << error << "." << endl;
return EXIT_FAILURE;
}
// 查找最后一个 '.' 的位置以分离扩展名
size_t dotPosition = inputFile.find_last_of('.');
if (dotPosition == std::string::npos || dotPosition == 0) {
std::cerr << "Invalid file name format.\n";
return 1;
}
// 构造新的文件名
std::string baseName = inputFile.substr(0, dotPosition);
std::string extension = inputFile.substr(dotPosition);
std::string newFileName = baseName + "_for" + extension;
const char* output = newFileName.c_str();
// Use PrettyPrint option for formatting.
doc.SaveFile(output,false);
cout << "Formatted XML saved successfully to: " << newFileName << endl;
return EXIT_SUCCESS;
}
运行:

左边是格式化之前的,右边是格式化之后的

有需要的朋友可以试试。
可执行程序(建议自行编译):
源代码工程: