开发者

Dynamic XML code generation in C++

开发者 https://www.devze.com 2023-02-22 02:58 出处:网络
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 simpl

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开发者_如何学JAVA);

    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 is also pretty easy to use and can create dynamic xml for you.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号