I’m trying to add a processing instruction node to an existing XML document to have a XSL transformation applied to the document when displayed in a browser. I looked up how to do it using libxml++ classes but couldn’t find it out, so I tried using libxml2. This is what I came up with:
xmlpp::Document* Doc = Parser->get_document();
// Set processing instruction for stylesheet
const xmlNodePtr PINode = xmlNewDocPI(
Doc->cobj(),
reinterpret_cast<xmlChar*>("xml-stylesheet"),
reinterpret_cast<xmlChar*>("href=\"../stylesheet.xslt\" type=\"text/xsl\"")
);
if (PINode == NULL) {
// Never get here
}
Doc->write_to_file_formatted("mydoc.xml", "utf-8");
The processing instruction node is not written into the document. So what am I missing here?
It turns out that just calling
xmlNewDocPIis not enough. It creates the processing instruction node and somehow associates it to the document but it doesn’t actually attach it to the document.For that purpose some of the
xmlAdd*functions must be called and, since I need the PI to be included right below the XML declaration and not nested within the documents root node, I had to use the following:It looks kind of hackish but works. So the full snippet for the working code gets like this: