具有前缀映射和不带前缀映射的 Pugiparse 命名空间

Pugiparse namespace with prefix mapping and without prefix mappig

本文关键字:映射 前缀 Pugiparse 命名空间      更新时间:2023-10-16

我有一个客户端应用程序,用于解析从 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>

如果观察两个服务器之间的差异,则服务器 A 不会发送命名空间和前缀之间的映射,但服务器 B 会发送(查看本地修改时间标记)。如何编写通用客户端解析逻辑,以通用地处理这两种情况。任何示例代码都会有很大帮助。

谢谢-桑迪普

我认为最好的选择是忽略命名空间并按本地名称查找节点。你可以像这样用 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();
}