将C结构映射到XML元素
假设我有一个C或C ++结构,例如:
struct ConfigurableElement { int ID; char* strName; long prop1; long prop2; ... };
我想将其加载/保存到以下XML元素:
这种映射可以简单地用Java / C#或任何其他语言完成,并且具有运行时reflection。 是否可以使用宏/模板技巧在C ++中以任何非繁琐的方式完成?
处理嵌套结构/联合的加分点。
您想要的技术称为序列化。 您可能想阅读这些文章:
http://www.codeproject.com/KB/cpp/xmlserialization.aspx
http://www.codesynthesis.com/products/xsd/ <===非常接近你想要的!
http://www.artima.com/cppsource/xml_data_binding.html
http://www.ibm.com/developerworks/xml/library/x-serial.html
http://www.firstobject.com/xml-serialization-in-c++.htm
编辑:
还有另一种选择:Ultimatepp提供的Xmlize:
http://www.ultimatepp.org/reference$Xmlize.html
http://www.ultimatepp.org/reference$Xmlize$en-us.html
http://www.ultimatepp.org/reference$XmlizeCustomValue$en-us.html
提示和技巧始终存在。 看看Metaresc库https://github.com/alexanderchuranov/Metaresc
它为类型声明提供了接口,该接口也将为该类型生成元数据。 基于元数据,您可以轻松地序列化/反序列化任何复杂的对象。 开箱即用,您可以序列化/反序列化XML,JSON,XDR,类似Lisp的表示法,C-init表示法。
这是一个简单的例子:
#include #include #include "metaresc.h" TYPEDEF_STRUCT (host_t, (char *, host), int port, ); TYPEDEF_STRUCT (config_t, (host_t, local), (host_t, remote), (char *, name), ); int main (int argc, char * argv[]) { config_t config = { .local = { .host = "localhost", .port = 8080, }, .remote = { .host = "google.com", .port = 80, }, .name = "service", }; char * str = MR_SAVE_XML (config_t, &config); if (str) { printf ("%s\n", str); free (str); } return (EXIT_SUCCESS); }
该程序将输出
$ ./config localhost 8080 google.com 80 service
图书馆适用于最新的gcc和clang。