我想将我自己的类的一些 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::string 名称组成。
最佳答案
RapidXML也非常易于使用,可以为您创建动态 xml。
关于c++ - C++ 中的动态 XML 代码生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5539978/