如何在 RapidXML 中获取属性值
问题:
你有一个 rapidxml::xml_node 实例,你想访问特定属性,例如 my-attribute
解决方案
使用 first_attribute 并将 name 参数设置为字符串:
rapidxml-attr-example.cpp
rapidxml::xml_attribute<>* attr = node->first_attribute("my-attribute");记住如果不存在此类属性,first_attribute() 返回 nullptr,所以一定要检查以避免段错误!
完整示例:
XML:
test.xml
<?xml version="1.0" encoding="UTF-8"?>
<root-element>
<child my-attr="foo"></child>
</root-element>C++:
rapidxml-example.cpp
#include <rapidxml/rapidxml_utils.hpp>
#include <string>
#include <iostream>
using namespace rapidxml;
using namespace std;
int main() {
rapidxml::file<> xmlFile("test.xml");
// 创建并解析文档
rapidxml::xml_document<> doc;
doc.parse<0>(xmlFile.data());
// 获取根节点
rapidxml::xml_node<> *root = doc.first_node("root-element");
rapidxml::xml_node<> *child = root->first_node("child");
// 获取并打印属性
rapidxml::xml_attribute<>* attr = child->first_attribute("my-attr");
if(attr == nullptr) {
cout << "没有此属性!" << endl;
} else {
cout << attr->value() << endl;
}
}或者你可以使用此代码片段函数获取属性值或默认值:
rapidxml-helpers.cpp
#include <rapidxml/rapidxml_utils.hpp>
#include <string>
#include <iostream>
using namespace rapidxml;
using namespace std;
/**
* 返回 attr 的 ->value() 或 default_value(如果 attr == nullptr)
*/
inline string attr_value_or_default(rapidxml::xml_attribute<>* attr, string default_value="") {
if(attr == nullptr) {
return default_value;
} else {
return attr->value();
}
}
int main() {
rapidxml::file<> xmlFile("test.xml");
// 创建并解析文档
rapidxml::xml_document<> doc;
doc.parse<0>(xmlFile.data());
// 获取根节点
rapidxml::xml_node<> *root = doc.first_node("root-element");
rapidxml::xml_node<> *child = root->first_node("child");
// 获取并打印属性+
rapidxml::xml_attribute<>* attr = child->first_attribute("my-attr");
cout << attr_value_or_default(attr, "No such attribute!") << endl;
}Check out similar posts by category:
C/C++
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow