what's the easiest way to generate xml in c++?

前端 未结 6 1160
遥遥无期
遥遥无期 2020-12-01 02:11

I\'ve used boost serialization but this doesn\'t appear to allow me to generate xml that conforms to a particular schema -- it seems it\'s purpose was to just to persist a c

6条回答
  •  青春惊慌失措
    2020-12-01 02:57

    Boost.PropertyTree is a nice and straightforward way of generating XML - especially if you are already using Boost.

    The following is a complete example program:

    #include 
    #include 
    
    using boost::property_tree::ptree;
    using boost::property_tree::write_xml;
    using boost::property_tree::xml_writer_settings;
    
    int wmain(int argc, wchar_t* argv[]) {
        char* titles[] = {"And Then There Were None", "Android Games", "The Lord of the Rings"};
    
        ptree tree;
        tree.add("library..version", "1.0");
        for (int i = 0; i < 3; i++) {
            ptree& book = tree.add("library.books.book", "");
            book.add("title", titles[i]);
            book.add(".id", i);
            book.add("pageCount", (i+1) * 234);
        }
    
        // Note that starting with Boost 1.56, the template argument must be std::string
        // instead of char
        write_xml("C:\\Users\\Daniel\\Desktop\\test.xml", tree,
            std::locale(),
            xml_writer_settings(' ', 4));
    
        return 0;
    }
    

    The resulting XML looks like this:

    
    
        
            
                And Then There Were None
                234
            
            
                Android Games
                468
            
            
                The Lord of the Rings
                702
            
        
    
    

    One thing that's particularly nice are the dot-separated paths that allow you to implicitly create all the nodes along the way. The documentation is rather meager, but together with ptree.hpp should give you an idea of how it works.

提交回复
热议问题