简体   繁体   中英

Dynamic XML code generation in C++

I would like to transform some C++ objects of classes of my own into XML code. I guess there are several libraries which provide C++ to XML-mapping, but I would like to keep the library overhead simple and craft something of my own.

What would be an appropriate approach to generate XML building? In Java there are annotations which could be use to dynamaically generate the XML. Maybe the template mechanism?

I am using TinyXML so far. I really enjoy using it.

Here is an example, which I would like to be generated:

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;

}

The class threadinfo would consist of int number and std::string name.

RapidXML也非常易于使用,可以为您创建动态xml。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM