将对向量进行比较与pugi :: xml_object_range属性
Compare std::vector of pairs with pugi::xml_object_range attributes
我正在基于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 "";
}
}
相关文章:
- Cppcheck生成xml转储文件
- 如何在pugixml中获取节点的内部XML
- 如何使用tinyxml2从XML加载父实体和子实体
- boost xml parsingl将xml的路径作为变量发送
- C++RapidXml-使用first_node()遍历以修改XML文件中节点的值
- 使用 Tinyxml 在 xml 中添加一个子子项
- 增强基于 XML class_id的反序列化
- 当覆盖存在时调用基本虚拟"binded to object"函数
- 在 c++ 中使用 vtd-xml 时,如何摆脱 EOFException?
- 防止在C++中选择错误文件时提升 xml 解析器崩溃
- c++ 读取 xml 文件的内容
- 删除 XML 文件中的子节点C++
- "Unable to start debugging. No process is associated with this object." - 在Visual Studio Code中使用GDB
- 使用 RapidXML 更新C++中的 XML 节点和属性值
- 在Cmake构建CmakeList.txt中读取/解析XML文件
- 从 XML 中读取未指定结构的每个数据成员
- XML to XML XSLT transformation. MSXML in VBScript
- 将 QGraphicsView 或 Scene 转换为 XML/JSON
- Qt 写入 xml: QIODevice::write (QFile, "D:/logs.xml" ): 设备未打开
- 使用 libxml2 解析 XML 文件时缺少元素值