Add XML headers using Boost's property trees

832 Views Asked by At

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

There are 1 best solutions below

1
On BEST ANSWER

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.