我以一种非常糟糕的方式从rapidXML获取了配置文件的值。
xml_document<> doc;
doc.parse<parse_full>(buffer);
int a = atoi(doc.first_node("master")->first_node("profile")->first_node("width")->value());如果节点不存在,"first_node“将返回0,因此"->value()”将崩溃。返回一个新的xml_node将修复崩溃,但是内存泄漏怎么办?
这是带有新旧返回值的rapidXML的函数:
xml_node<Ch> *first_node(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const
{
if (name)
{
if (name_size == 0)
name_size = internal::measure(name);
for (xml_node<Ch> *child = m_first_node; child; child = child->next_sibling())
if (internal::compare(child->name(), child->name_size(), name, name_size, case_sensitive))
return child;
return new xml_node<Ch>(node_document);
//return 0;
}
else
return m_first_node;
}发布于 2012-11-06 23:13:20
您应该使用异常,例如:
int a;
try
{
xml_document<> doc;
doc.parse<parse_full>(buffer);
a = atoi(doc.first_node("master")->first_node("profile")->first_node("width")->value());
}
catch(NodeNotExists &ex)
{
// process error condition
}另外,如果不想更改rapidxml代码,可以使用如下包装器函数:
template<typename T>
T* notnull(T* arg)
{
if (arg == 0)
throw NodeNotExists();
return arg;
}发布于 2013-10-24 23:48:42
扩展hate-engine的答案,我创建了一个静态助手函数类,通过包装节点值访问来处理这种情况。请在here上查看我的答案。您可以在此基础上进行扩展,或者追求更多类似于xpath风格的节点访问(我不相信这是目前内置于RapidXML中的,但others do是内置的)。
编辑:您可以使用创建一个包装器函数,该函数采用一个简单的类似xpath的路径,并将其与我的一个包装器相结合,以获得类似于...
int a = GetNodeInt(GetFirstNodePath(doc, "master/profile/width"), 0);其中GetNodeInt和GetFirstNodePath的定义类似于...
int GetNodeInt(rapidxml::xml_base<>* node, int DefaultValue)
{
int temp;
try
{
if (node == 0) return DefaultValue;
if (sscanf(node->value(), "%d", &temp) != 1) return DefaultValue;
return temp;
}
catch (...) { return DefaultValue; }
}
// Find node with simple path from current node such as "first/second/third"
rapidxml::xml_node<>* GetFirstNodePath(rapidxml::xml_node<>* root, const char *path)
{
xml_node<>* node = root;
char* last = (char*)path; // only using this pointer to read
char* cur = last;
if (cur == 0 || root == 0) return 0;
while (node)
{
if (*cur == '/' || *cur == 0)
{
if (cur != last) node = node->first_node(last,cur-last);
if (*cur == 0) break;
last = cur + 1;
}
++cur;
}
return node;
}现在,这段代码还没有经过彻底的测试,但是给了您一个大概的概念。
https://stackoverflow.com/questions/12255643
复制相似问题