XPATHS and Default Namespaces

后端 未结 5 2073
囚心锁ツ
囚心锁ツ 2020-11-28 12:34

What is the story behind XPath and support for namespaces? Did XPath as a specification precede namespaces? If I have a document where elements have been given a default na

5条回答
  •  隐瞒了意图╮
    2020-11-28 13:20

    Using libxml it seems this works:

    http://xmlsoft.org/examples/xpath1.c

     int 
    register_namespaces(xmlXPathContextPtr xpathCtx, const xmlChar* nsList) {
        xmlChar* nsListDup;
        xmlChar* prefix;
        xmlChar* href;
        xmlChar* next;
    
        assert(xpathCtx);
        assert(nsList);
    
        nsListDup = xmlStrdup(nsList);
        if(nsListDup == NULL) {
        fprintf(stderr, "Error: unable to strdup namespaces list\n");
        return(-1); 
        }
    
        next = nsListDup; 
        while(next != NULL) {
        /* skip spaces */
        while((*next) == ' ') next++;
        if((*next) == '\0') break;
    
        /* find prefix */
        prefix = next;
        next = (xmlChar*)xmlStrchr(next, '=');
        if(next == NULL) {
            fprintf(stderr,"Error: invalid namespaces list format\n");
            xmlFree(nsListDup);
            return(-1); 
        }
        *(next++) = '\0';   
    
        /* find href */
        href = next;
        next = (xmlChar*)xmlStrchr(next, ' ');
        if(next != NULL) {
            *(next++) = '\0';   
        }
    
        /* do register namespace */
        if(xmlXPathRegisterNs(xpathCtx, prefix, href) != 0) {
            fprintf(stderr,"Error: unable to register NS with prefix=\"%s\" and href=\"%s\"\n", prefix, href);
            xmlFree(nsListDup);
            return(-1); 
        }
        }
    
        xmlFree(nsListDup);
        return(0);
    }
    

提交回复
热议问题