LibXML 不返回 xpath 结果

LibXML not returning the xpath result

我从相机下载了一个 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);

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