c++ - C++ 中的动态 XML 代码生成

标签 c++ xml code-generation

我想将我自己的类的一些 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/

相关文章:

c# - XSD 工具在生成 C# 代码时将 "Specified"附加到某些属性/字段

c++ - 为什么我需要另一个迭代器作为 std::copy() 中的参数?

c++ - 在不同的类上调用不同的成员函数

android - 从另一个开发人员导入的代码 : <No resource identifier found for attribute 'ProgressColor' in package. ..> 我的一个 .xml 文件中出现错误

java - 如何使用 javax.lang.model 读取文件?

code-generation - JavaME 的解析器生成器

C++ uniform_int_distribution 总是在第一次调用时返回 min()

c++ - Unresolved external symbol 错误 (LNK2019),包含 header 后

html - 在 xslt 文件中获取 "prefix ' soap' is not defined"

c# - 向后兼容的 XML 反序列化