to_xml, 转换C++ struct到 xml格式

C++开发 cgi, 经常需要输出xml格式的数据。借鉴个to_json.hpp的库,  实现了个to_xml库, 可以方便输出xml数据。

使用范例:

#include "to_xml.hpp"

#include <stdio.h> 

 

struct A 

    int a; 

     struct B {  

        int i; 

        std::string name; 

        std::vector<std::string> other; 

        DEF_TO_XML_MEM3(B, i, name, other) 

    };   

 

   std::vector<int> b; 

   B c; 

   std::string d; 

}; 

 

DEF_TO_XML3(A, XML_ATTR2(a, d), b, c) 

 

int main(int argc, const char *argv[]) 

    A a; 

    a.a = 1; 

    a.d = "abc"; 

    a.b.push_back(2); 

    a.b.push_back(3); 

    a.b.push_back(4); 

    a.c.i=4; 

    a.c.name="piboye&"; 

    a.c.other.push_back("piboye1<>"); 

    a.c.other.push_back("piboye2'\""); 

 

    std::string out = to_xml(a); 

    printf("%s\n", out.c_str()); 

 

return 0; 

输出:

  1. <A a="1", d="abc"><b>2</b><b>3</b><b>4</b><c><i>4</i><name>piboye&amp;</name><other>piboye1&lt;&gt;</other><other>piboye2&apos;&quot;</other></c></A>  

DEF_TO_XML3 定义个全局的 to_xml函数, 可以格式化类型 A,  3 表示有3个输出参数。

XML_ATTR2表示 有两个成员被当成 xml的属性来输出,其它的参数当成子元素输出。

DEF_TO_XML_MEM3 表示定义类的成员方法 to_xml

to_xml.hpp.pump 是借鉴了 gtest使用的 pump.py工具来减少重复代码, 并借鉴了 repeat macro的技巧。

对字符中串中的, < > & ' " 进行了转义。

你可能感兴趣的:(struct)