2016-11-25 10 views
-1

XMLパーサーの便利な関数をpugixmlに基づいて作成していますが、特定の属性名を持つXMLノードのみを取得したいという問題がありますそして価値!pugi :: xml_object_range属性を持つペアのstd :: vectorを比較する

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 
    // ... 
} 

誰かが私を助けたり、私にヒントを与えることができます! (おそらくラムダ式で)

+0

有効なXMLですか? :o – 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 ""; 
    } 
} 
関連する問題