我正在尝试将处理指令节点添加到现有 XML 文档,以便在浏览器中显示时将 XSL 转换应用于该文档。我查找了如何使用 libxml++
类来执行此操作,但找不到它,所以我尝试使用 libxml2
。这就是我想到的:
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");
处理指令节点未写入文档。那么我在这里缺少什么?
最佳答案
事实证明,仅调用 xmlNewDocPI
是不够的。它创建处理指令节点并以某种方式将其关联到文档,但它实际上并未将其附加到文档。
为此,必须调用一些 xmlAdd*
函数,并且由于我需要将 PI 包含在 XML 声明的正下方,而不是嵌套在文档根节点中,因此我必须使用以下内容:
xmlAddPrevSibling(Doc->get_root_node()->cobj(), PINode);
它看起来有点黑客但有效。因此,工作代码的完整片段如下所示:
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) {
xmlAddPrevSibling(Doc->get_root_node()->cobj(), PINode);
}
Doc->write_to_file_formatted("mydoc.xml", "utf-8");
关于c++ - 使用 libxml++ 将处理指令添加到现有 XML 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8908323/