2017-07-27 203 views
0

我認爲,xpath //@ns1:*必須返回與前綴ns1相關聯的命名空間中的所有屬性。但是,libxml2會返回具有更多屬性的節點集,然後我期待。libxml2:在xpath中忽略名稱空間

這是我的測試代碼。我在win32上嘗試了libxml2版本2.7.8,在Linux上嘗試了2.9.1版本。

#include <libxml/tree.h> 
#include <libxml/parser.h> 
#include <libxml/xpath.h> 
#include <libxml/xpathInternals.h> 
#include <stdio.h> 
#include <string.h> 

const char* sample_doc = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" 
    "<root xmlns:na=\"urn:test1\">" 
    "<el>First</el><!-- comment -->" 
    "<el at=\"some attr\" na:a=\"stuff\">Second</el>" 
    "</root>"; 

void die(const char* err) 
{ 
    fprintf(stderr, "ERROR: %s\n", err); 
    exit(1); 
} 

int test() 
{ 
    xmlXPathContextPtr xpathCtx; 
    xmlXPathObjectPtr xpathObj; 
    xmlDoc *doc = xmlReadMemory(sample_doc, strlen(sample_doc), "noname.xml", NULL, 0); 
    xpathCtx = xmlXPathNewContext(doc); 
    if(! xpathCtx) 
    die("xmlXPathNewContext"); 
    if(xmlXPathRegisterNs(xpathCtx, BAD_CAST "ns1", BAD_CAST "urn:test1") != 0) 
    die("xmlXPathRegisterNs1"); 
    xpathObj = xmlXPathEvalExpression(BAD_CAST "//@ns1:*", xpathCtx); 
    if(! xpathObj) 
    die("xmlXPathEvalExpression"); 
    printf("Found %d nodes:\n", xpathObj->nodesetval->nodeNr); 
    for(int i = 0; i < xpathObj->nodesetval->nodeNr; ++i) 
    { 
    xmlNodePtr n = xpathObj->nodesetval->nodeTab[i]; 
    xmlChar* t = xmlNodeGetContent(n); 
    printf(" type: %d, name: %s, content: %s\n", n->type, n->name, t); 
    xmlFree(t); 
    } 
    xmlXPathFreeObject(xpathObj); 
    xmlXPathFreeContext(xpathCtx); 
    xmlFreeDoc(doc); 
    return 0; 
} 

int main() 
{ 
    int rc; 
    xmlInitParser(); 
    LIBXML_TEST_VERSION 
    rc = test(); 
    xmlCleanupParser(); 
    return rc; 
} 

功能xmlXPathEvalExpression回報NODESET有2個節點,而我希望只有一個。

結果:

$ ./test 
Found 2 nodes: 
type: 2, name: at, content: some attr 
type: 2, name: a, content: stuff 

是,在libxml的錯誤,還是一個我的XPath是錯了嗎?

回答