在c++中动态生成XML代码

Dynamic XML code generation in C++

本文关键字:XML 代码 动态 c++      更新时间:2023-10-16

我想把我自己的类的一些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 number和std::string name组成。

RapidXML也很容易使用,可以为您创建动态xml