Pugixml - parse namespace with prefix mapping and without prefix mappig

社会主义新天地 提交于 2019-12-04 04:52:24

问题


I have a client application that parses xml responses that are sent from 2 different servers. I call them server A and server B.

Server A responds to one of the request with a response as below:

<?xml version="1.0" encoding="UTF-8"?>
    <D:multistatus xmlns:D="DAV:">
    <D:response>
    <D:href>/T12.txt</D:href>
    <D:propstat>
    <D:prop>
    <local-modification-time xmlns="urn:abc.com:webdrive">1389692809</local-modification-time>
    </D:prop>

    <D:status>HTTP/1.1 200 OK</D:status>

    </D:propstat>
</D:response>
</D:multistatus>

Server B responds to one of the request with a response as below:

<?xml version="1.0" encoding="UTF-8"?>
    <D:multistatus xmlns:D="DAV:">
    <D:response>
    <D:href>/T12.txt</D:href>
    <D:propstat>
    <D:prop>
    <O:local-modification-time xmlns:O="urn:abc.com:webdrive">1389692809</O:local-modification-time>
    </D:prop>

    <D:status>HTTP/1.1 200 OK</D:status>

    </D:propstat>
</D:response>
</D:multistatus>

If you observer the difference between the two servers, serverA does not send a mapping between namespace and prefix, but serverB does (look at local-modification-time tag). How can I write a generic client parsing logic, to handle both these scenarios generically. Any sample code would be of great help.

Thanks, -Sandeep


回答1:


I think your best bet is to just ignore namespaces and find the node by local name. You can do it with XPath like this:

node.select_single_node(".[local-name()='local-modification-time']")

Or you can just use C++ like this:

pugi::xml_node child_by_local_name(pugi::xml_node node, const char* name)
{
    for (pugi::xml_node child = node.first_child(); child; child = child.next_sibling())
    {
        if (strcmp(child.name(), name) == 0)
            return child;

        const char* colon = strchr(child.name(), ':');

        if (colon && strcmp(colon + 1, name) == 0)
            return child;
    }

    return pugi::xml_node();
}


来源:https://stackoverflow.com/questions/21162186/pugixml-parse-namespace-with-prefix-mapping-and-without-prefix-mappig

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!