libxml2 获取 XML 节点文本的偏移量

libxml2 get offset into XML text of node

我需要知道在使用 xmlReadMemory 获取 dom 后,可以在 dom 某处的特定任意节点找到 xml 字符串的哪个偏移量.问题是我不知道从哪里获取 xmlParserCtxtPtr 作为第一个参数传递给 xmlParserFindNodeInfo 因为我的整个解析过程没有产生这样的上下文;只有 xmlDoc.

以下代码对我有用(libxml2 文档几乎没有什么可取之处,必须下载源代码并在 lib 中挖掘,直到我理解到足以破解它为止)。关键是:

xmlSetFeature(ctxt, "gather line info", (void *)&v);

这里有一些代码来说明:

const char *xml = ...
xmlParserCtxt *ctxt = NULL;
xmlDoc *doc = NULL;
if (!(ctxt = xmlCreateDocParserCtxt((const unsigned char *)xml)))
    return -1;
int v = 1;
xmlSetFeature(ctxt, "gather line info", (void *)&v);
if (xmlParseDocument(ctxt) == -1)
{
    xmlFreeParserCtxt(ctxt);
    return -1;
}
else
{
    if ((ctxt->wellFormed) || ctxt->recovery)
        doc = ctxt->myDoc;
    else
    {
        xmlFreeParserCtxt(ctxt);
        return -1;
    }
}

// use doc to get a node and then xmlParserFindNodeInfo(ctxt, node)
…

xmlFreeParserCtxt(ctxt);