【问题标题】:libxml2 predicates in xpath expression are not always recognizedxpath 表达式中的 libxml2 谓词并不总是被识别
【发布时间】:2013-06-20 15:12:45
【问题描述】:

我之所以向您求助,是因为我在使用 libxml2 库时遇到了问题,该库未考虑我的 xpath 表达式中的某些参数。

这是我试图解析的 xml 文件的示例:

<?xml version="1.0" encoding="ISO-8859-1"?>

<bookstore>

    <book title="Harry Potter" lang="eng" version="1">
       <price>29.99</price>
    </book>

    <book title="Learning XML" lang="eng" version="2">
        <price>38.95</price>
    </book>

    <book title="Learning C" lang="eng" version="2">  
       <price>39.95</price>
    </book>

</bookstore>

假设我要提取所有母语为英语且版本为第一版的书籍。

如果我没记错的话,我会使用下面的 XPath 表达式:

//book[@lang='eng' and @version='1']

以及我的代码中的以下说明:

xmlChar * xpath_expression = "//book[@lang='eng' and @version='1']";
xmlXPathObjectPtr xpathRes = xmlXPathEvalExpression(xpath_expression, ctxt);

问题是我得到的结果是书籍列表,好像我只是执行以下请求:

//book

我想知道我的版本是否有问题,因为我有最新的 debian 挤压 (2.7.8.dfsg-2 +挤压7)...

【问题讨论】:

    标签: xpath libxml2 predicates


    【解决方案1】:

    这肯定不是 libxml2 中的错误。您可能在其他地方犯了错误。以下代码只打印“哈利波特”:

    #include <stdio.h>
    #include <libxml/xpath.h>
    
    int main()
    {
        static const char xml[] =
            "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
            "<bookstore>\n"
            "    <book title=\"Harry Potter\" lang=\"eng\" version=\"1\">\n"
            "       <price>29.99</price>\n"
            "    </book>\n"
            "    <book title=\"Learning XML\" lang=\"eng\" version=\"2\">\n"
            "        <price>38.95</price>\n"
            "    </book>\n"
            "    <book title=\"Learning C\" lang=\"eng\" version=\"2\">  \n"
            "       <price>39.95</price>\n"
            "    </book>\n"
            "</bookstore>\n";
    
        xmlDocPtr doc = xmlParseMemory(xml, sizeof(xml));
        xmlXPathContextPtr ctxt = xmlXPathNewContext(doc);
        xmlChar *expression = BAD_CAST "//book[@lang='eng' and @version='1']";
        xmlXPathObjectPtr res = xmlXPathEvalExpression(expression, ctxt);
        xmlNodeSetPtr nodeset = res->nodesetval;
    
        for (int i = 0; i < nodeset->nodeNr; i++) {
            xmlNodePtr node = nodeset->nodeTab[i];
            xmlChar *title = xmlGetProp(node, BAD_CAST "title");
            printf("%s\n", title);
        }   
    
        xmlXPathFreeObject(res);
        xmlXPathFreeContext(ctxt);
        xmlFreeDoc(doc);
    
        return 0;
    }
    

    【讨论】:

    • 我意识到返回的响应是模棱两可的,因为虽然我得到了一个元素,但我仍然可以通过解析返回的节点来访问其他元素。
    • libxml2 就是这样工作的。您可以在 xmlXPathObject 中获得 XPath 查询的结果,在这种情况下,它包含一个节点集。此节点集中的节点指向原始 XML 文档中的节点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-06
    • 1970-01-01
    • 2012-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    相关资源
    最近更新 更多