1
我想將自己的類的一些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