C++ XML类
该类主要将xml中的标签分为两类,无内容标签统一称为父标签,有内容的就以键值对的方式直接输出。
后面可能会优化通过函数参数的方式管控层级关系,现在是通过类里自动记录层级深度来表示的。
#include <fstream>
#include <string>
#include <iostream>
#include <map>
class XmlWriter {
private:
std::ofstream m_file;
public:
XmlWriter(const std::string& filename) {
m_file.open(filename.c_str());
if (!m_file) {
std::cout << "" << std::endl;
}
m_file << "<?xml version=\"1.0\" encoding = \"UTF-8\"?> \n";
depth = 0;
}
~XmlWriter() {
if (m_file) {
m_file.close();
}
}
void addParentElement(const std::string& parentLable = "") {
if (!parentLable.empty()) {
if (depth) {
for (int i = 0; i < depth; i++)
m_file << " ";
}
m_file << "<" << parentLable << ">\n";
depth++;
m_LableMap[depth]= parentLable;
}
}
void addLableKey(const std::string& key, const std::string& value = "") {
if (!key.empty() && !value.empty()) {
if (depth)
{
for (int i = 0; i < depth; i++)
m_file << " ";
}
m_file << "<" << key << ">" << value << "</" << key << ">\n";
}
}
void closeParentElement() {
if (depth)
{
for (int i = 0; i < depth - 1 ; i++)
m_file << " ";
}
m_file << "</" << m_LableMap[depth] << ">\n";
m_LableMap.erase(depth);
depth--;
}
private:
int depth;
std::map<int, std::string> m_LableMap;
};
int main(int argc, char * argv[])
{
XmlWriter writer("mateDate.xml");
writer.addParentElement("Person");
writer.addLableKey("Age", "27");
writer.addLableKey("name", "hzh");
writer.addParentElement("friend");
writer.addLableKey("name", "zjm");
writer.addLableKey("Age", "22");
writer.closeParentElement();
writer.addLableKey("pay", "30w");
writer.closeParentElement();
return 0;
}