C++中的动态XML代码生成
问题描述:
我想将自己的类的一些C++对象转换为XML代码。我想有几个库提供C++到XML映射,但我想保持图书馆开销简单,并制作我自己的东西。C++中的动态XML代码生成
什么是生成XML构建的适当方法?在Java中有注释可用于动态生成XML。也许模板机制?
到目前为止我使用的是TinyXML。我非常喜欢使用它。
下面是一个例子,这是我想生成:
std::string XMLBuilder::buildThreadInformation(vector<threadinfo> threadinfos) {
TiXmlDocument document;
TiXmlDeclaration *declaration = new TiXmlDeclaration("1.0", "", "");
TiXmlElement *messageWrapElement = new TiXmlElement("message");
TiXmlElement *threadsElement = new TiXmlElement("threads");
messageWrapElement->LinkEndChild(threadsElement);
std::string numberString;
for (vector<threadinfo>::const_iterator it = threadinfos.begin(); it
!= threadinfos.end(); ++it) {
TiXmlElement *threadElement = new TiXmlElement("thread");
threadsElement->LinkEndChild(threadElement);
TiXmlElement *threadNumberElement = new TiXmlElement("number");
threadElement->LinkEndChild(threadNumberElement);
numberString = boost::lexical_cast<std::string>((*it).thread_number);
TiXmlText *threadNumber = new TiXmlText(numberString.c_str());
threadNumberElement->LinkEndChild(threadNumber);
TiXmlElement *threadNameElement = new TiXmlElement("name");
threadElement->LinkEndChild(threadNameElement);
TiXmlText *threadName = new TiXmlText((*it).name.c_str());
threadNameElement->LinkEndChild(threadName);
}
document.LinkEndChild(declaration);
document.LinkEndChild(messageWrapElement);
TiXmlPrinter printer;
document.Accept(&printer);
std::string result = printer.CStr();
return result;
}
类的ThreadInfo将包括INT数目和std ::字符串名称。
您是否会进一步解释您的问题并提供一个您想要做什么的小例子?从你的问题来看,我不清楚你是否尝试将对象序列化为xml,编写自己的声明式XML语言(如XAML)或完全是其他语言。 – Nathanael 2011-04-04 20:30:00
@Nathanael:你说得对。我添加了一个例子,我希望它足够小。 – 2011-04-05 20:45:25