C++ 实现以xml的格式写入文件

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值