将对向量进行比较与pugi :: xml_object_range属性

Compare std::vector of pairs with pugi::xml_object_range attributes

本文关键字:xml object 属性 range pugi 向量 比较      更新时间:2023-10-16

我正在基于pugixml为我的XML解析器编写一些便利功能,现在我有一个问题,我只想检索具有特定属性名称和值的XML节点!

XML示例:

<Readers>
    <Reader measurement="..." type="Mighty">
        <IP reader="1">192.168.1.10</IP>
        <IP reader="2">192.168.1.25</IP>
        <IP reader="3">192.168.1.30</IP>
        <IP reader="4">192.168.1.50</IP>    
    </Reader>
    <Reader measurement="..." type="Standard">
        ...
    </Reader>
</Readers>

我的尝试:

std::string GetNodeValue(std::string node, std::vector<std::pair<std::string,std::string>> &attributes)
{
    pugi::xml_node xmlNode = m_xmlDoc.select_single_node(("//" + node).c_str()).node();
    // get all attributes
    pugi::xml_object_range<pugi::xml_attribute_iterator> nodeAttributes(xmlNode.attributes());
    // logic to compare given attribute name:value pairs with parsed ones
    // ...
}

有人可以帮我或给我一个提示吗?(也许带有lambda表达式)

要解决此问题,我们必须使用XPath。

/*!
    Create XPath from node name and attributes
    @param XML node name
    @param vector of attribute name:value pairs
    @return XPath string
*/
std::string XmlParser::CreateXPath(std::string node, std::vector<std::pair<std::string,std::string>> &attributes)
{
    try
    {       
        // create XPath
        std::string xpath = node + "[";
        for(auto it=attributes.begin(); it!=attributes.end(); it++)
            xpath += "@" + it->first + "='" + it->second + "' and ";
        xpath.replace(xpath.length()-5, 5, "]");        
        return xpath;
    }
    catch(std::exception exp)
    {       
        return "";
    }
}

CreateXPath从给定的节点名称和属性列表中构造有效的XML XPATH语句。

/*!
    Return requested XmlNode value
    @param name of the XmlNode
    @param filter by given attribute(s) -> name:value   
    @return value of XmlNode or empty string in case of error
*/
std::string XmlParser::GetNodeValue(std::string node, std::vector<std::pair<std::string,std::string>> &attributes /* = std::vector<std::pair<std::string,std::string>>() */)
{   
    try
    {
        std::string nodeValue = "";     
        if(attributes.size() != 0) nodeValue = m_xmlDoc.select_node(CreateXPath(node, attributes).c_str()).node().child_value();            
        else nodeValue = m_xmlDoc.select_node(("//" + node).c_str()).node().child_value();          
        return nodeValue;
    }
    catch(std::exception exp) 
    {           
        return ""; 
    }
}