Pugixml - 使用前缀映射解析名称空间而不使用前缀映射

时间:2014-01-16 12:45:37

标签: c++ xml xml-parsing xml-deserialization pugixml

我有一个客户端应用程序,用于解析从2个不同服务器发送的xml响应。我把它们称为服务器A和服务器B.

服务器A通过以下响应响应其中一个请求:

<?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>

服务器B使用以下响应响应其中一个请求:

<?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>

如果观察两个服务器之间的差异,serverA不会在命名空间和前缀之间发送映射,但serverB会发送(查看local-modification-time标记)。如何编写通用客户端解析逻辑,以便一般性地处理这两种情况。任何示例代码都会有很大的帮助。

谢谢, -Sandeep

1 个答案:

答案 0 :(得分:3)

我认为最好的办法是忽略名称空间并按本地名称查找节点。 您可以使用XPath这样做:

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

或者您可以像这样使用C ++:

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();
}