【问题标题】:Compare std::vector of pairs with pugi::xml_object_range attributes将 std::vector 对与 pugi::xml_object_range 属性进行比较
【发布时间】:2017-04-09 22:54:51
【问题描述】:

我正在为基于 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 表达式)

【问题讨论】:

  • 那是有效的 XML 吗? :o

标签: c++ c++11 pugixml


【解决方案1】:

为了解决这个问题,我们必须使用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 ""; 
    }
}

【讨论】:

    猜你喜欢
    • 2016-09-18
    • 2016-10-25
    • 1970-01-01
    • 1970-01-01
    • 2015-08-26
    • 2022-07-12
    • 1970-01-01
    • 1970-01-01
    • 2021-10-13
    相关资源
    最近更新 更多