2016-11-25 59 views
-1

我正在爲基於pugixml的XML解析器編寫一些便利函數,現在我遇到了問題,我只想檢索具有特定屬性名稱的XML節點和價值!比較std :: pugi :: xml_object_range屬性的對向量

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表達式)

+0

這是有效的XML嗎? :○ – erip

回答

-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 ""; 
    } 
}