LibXML没有返回xpath结果

时间:2017-05-02 08:06:01

标签: c++ xpath libxml2

我从相机下载了一个XML到内存,并想用libxml和xpath解析它,但是当我试图查询一个节点的值时,我得到一个空白的结果(或者更确切地说,是“Leerer Knoten”路径) 。发生什么事?

std::string wrapper::utility::XMLHelper::getPayload(std::string identifier, std::string document)
{
    xmlDocPtr doc = xmlParseDoc((const unsigned char*)document.c_str());
    xmlXPathContextPtr xpathCtx;
    xmlXPathObjectPtr result;

    xpathCtx = xmlXPathNewContext(doc);
    if (xpathCtx == NULL)
        return "Invalid Context";

    result = xmlXPathEvalExpression((xmlChar*)identifier.c_str(), xpathCtx);
    char buffer[16];
    snprintf(buffer, sizeof(buffer), "%d", result->nodesetval->nodeNr);

    if (xmlXPathNodeSetIsEmpty(result->nodesetval))
    {
        xmlXPathFreeContext(xpathCtx);
        xmlXPathFreeObject(result);
        xmlFreeDoc(doc);
        return "Leerer Knoten";
    }

    std::string returnValue((char*)xmlNodeGetContent(result->nodesetval->nodeTab[0]));
    xmlXPathFreeContext(xpathCtx);
    xmlFreeDoc(doc);
    xmlCleanupParser();

    return returnValue;
}

std::string identifier = "/NetworkInterface/IPAddress/ipAddress";
std::string request =
    "<?xml version=\"1.0\" encoding=\"UTF-8\" ?> \n"
    "<NetworkInterface version=\"2.0\" xmlns=\"http://www.std-cgi.com/ver20/XMLSchema\">\n"
    "    <id>1</id> \n"
    "    <IPAddress version=\"2.0\" xmlns=\"http://www.std-cgi.com/ver20/XMLSchema\">\n"
    "       <ipVersion>dual</ipVersion> \n"
    "       <addressingType>static</addressingType> \n"
    "       <ipAddress>172.19.50.232</ipAddress> \n"
    "       <subnetMask>255.255.0.0</subnetMask> \n"
    "       <ipv6Address>::</ipv6Address> \n"
    "       <bitMask>0</bitMask> \n"
    "       <DefaultGateway>\n"
    "           <ipAddress>172.19.50.1</ipAddress> \n"
    "           <ipv6Address>::</ipv6Address> \n"
    "       </DefaultGateway>\n"
    "       <PrimaryDNS>\n"
    "           <ipAddress>8.8.8.8</ipAddress> \n"
    "       </PrimaryDNS>\n"
    "       <SecondaryDNS>\n"
    "           <ipAddress>0.0.0.0</ipAddress> \n"
    "       </SecondaryDNS>\n"
    "    </IPAddress>\n"
    "    <Discovery version=\"2.0\" xmlns=\"http://www.std-cgi.com/ver20/XMLSchema\">\n"
    "        <UPnP>\n"
    "            <enabled>true</enabled> \n"
    "        </UPnP>\n"
    "        <Zeroconf>\n"
    "            <enabled>true</enabled> \n"
    "        </Zeroconf>\n"
    "    </Discovery>\n"
    "    <Link version=\"2.0\" xmlns=\"http://www.std-cgi.com/ver20/XMLSchema\">\n"
    "        <MACAddress>c4:2f:90:4c:85:68</MACAddress> \n"
    "        <autoNegotiation>true</autoNegotiation> \n"
    "        <speed>10</speed> \n"
    "        <duplex>half</duplex> \n"
    "        <MTU>1500</MTU> \n"
    "    </Link>\n"
    "</NetworkInterface>";

std::string res = wrapper::utility::XMLHelper::getPayload(identifier, request);

1 个答案:

答案 0 :(得分:1)

/NetworkInterface/IPAddress/ipAddress搜索空XML命名空间中的元素。您的文档似乎包含命名空间,因此请注册它并使用命名空间前缀。