假设我有一个C或C ++结构,例如:
struct ConfigurableElement {
int ID;
char* strName;
long prop1;
long prop2;
...
};
我想将其加载/保存到以下XML元素中:
<ConfigurableElement ID="1" strName="namedElem" prop1="2" prop2="3" ... />
这样的映射可以简单地用Java / C#或任何其他语言完成,并且具有运行时反射。是否可以使用宏/模板技巧在C ++中以任何非繁琐的方式完成?
处理嵌套结构/联合的加分点。
答案 0 :(得分:3)
您想要的技术称为序列化。您可能想阅读这些文章:
http://www.codeproject.com/KB/cpp/xmlserialization.aspx
http://www.codesynthesis.com/products/xsd/&lt; ===非常接近你想要的东西!
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
答案 1 :(得分:2)
提示和技巧始终存在。看一下Metaresc库https://github.com/alexanderchuranov/Metaresc
它为类型声明提供了接口,该接口也将为该类型生成元数据。基于元数据,您可以轻松地序列化/反序列化任何复杂的对象。开箱即用,您可以序列化/反序列化XML,JSON,XDR,类似Lisp的表示法,C-init表示法。
这是一个简单的例子:
#include <stdio.h>
#include <stdlib.h>
#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
<?xml version="1.0"?>
<config>
<local>
<host>localhost</host>
<port>8080</port>
</local>
<remote>
<host>google.com</host>
<port>80</port>
</remote>
<name>service</name>
</config>
图书馆适用于最新的gcc和clang。