Add XML headers using Boost's property trees [duplicate]

雨燕双飞 提交于 2019-12-11 09:37:15

问题


I've been working on a XML reader/writer, and I used Boost's property trees to do so.

Everything is working, only one thing is missing in the output file: I'd like to add two header tags at the top of the file. Right now, the only header is this one, automatically written by Boost's write_xml() function:

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>

However, I'd like to add these two below the one already there:

<!-- Custom stylesheet -->
<?xml-stylesheet type="text/xsl" href="browser_view.xslt"?>
<!-- Authentic View -->
<?xmlspysps authentic_view.sps?>

Does anyone know how I could do that without editing the file after generating it with Boost?


回答1:


The word is "processing instruction". And I'm pretty sure you can't (why would they implement that? There is no Boost Xml library after all).

After double checking the xml_writer_settings there is indeed nothing that controls the printing of the processing instructions (otherwise you could ave suppressed them and instead printed the whole preamble yourself).

Here's my take on it with PugiXML:

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <iostream>

#include <pugixml.hpp>

int main() {

    std::stringstream ss;

    {
        boost::property_tree::ptree pt;
        pt.add("demo", "bla");
        boost::property_tree::xml_parser::write_xml(ss, pt);
    }

    {
        pugi::xml_document doc;
        doc.load(ss);

        auto pi = doc.prepend_child(pugi::xml_node_type::node_pi);
        pi.set_name("xmlspysps");
        pi.set_value("authentic_view.sps");

        pi = doc.prepend_child(pugi::xml_node_type::node_pi);
        pi.set_name("xml-stylesheet");
        pi.set_value("type=\"text/xsl\" href=\"browser_view.xslt\"");

        doc.save_file("test.xml");
    }
}

Saves:

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="browser_view.xslt"?>
<?xmlspysps authentic_view.sps?>
<demo>bla</demo>

Of course that's horribly inefficient if you really want to just serialize a ptree - but apparently you're not just serializing. You're marking up, for which you need a markup-library, preferrably an XML capable one.



来源:https://stackoverflow.com/questions/27485344/add-xml-headers-using-boosts-property-trees

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!