c++ - 使用 libxml++ 将处理指令添加到现有 XML 文档

标签 c++ xml libxml2

我正在尝试将处理指令节点添加到现有 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/

相关文章:

javascript - Magento:自定义文件中的 jQuery 不起作用

javascript - 如何获取 XML 标签内的内容来创建数组?

c++ - 系统范围的 libxml2 不工作,从源代码编译在配置中失败

c - 无法在 C 中使用 Libxml2 解析 XML

iphone - XPath如何在不加载整个xml的情况下选择第一个元素?

c++ - 为什么读写管道时需要关闭fds?

c++ - ROS 节点到节点持续时间

java - []int 和 int[] 有什么区别

c++ - 数据结构——指向自身的 C++ 指针

java - 使用 XPath 检索 XML 元素会抛出 NullPointerException