gpt4 book ai didi

c++ - RapidXML 节点异常处理

转载 作者:太空宇宙 更新时间:2023-11-04 11:31:11 25 4
gpt4 key购买 nike

我正在使用 RapidXML 解析一个 xml 文件,其中包含一些我想在我的 C++ 程序中使用的变量。我能够读取有效节点,但我想添加一些错误处理,例如,如果节点名称拼写错误。

这是我的文件的一个工作示例。

.cpp

try
{
rapidxml::file<> xmlFile("file.xml");
rapidxml::xml_document<> doc;
doc.parse<parse_declaration_node | parse_no_data_nodes>(xmlFile.data());

xml_node<>* prop_node = doc.first_node("PropertyList");
}
catch (const runtime_error& e)
{
// Do something
}
catch (const rapidxml::parse_error& e)
{
// Do something
}
catch (const exception& e)
{
// Do something
}
catch(...)
{
// Do something
}

.xml

<?xml version="1.0" encoding="utf-8"?>

<PropertyList>
...
</PropertyList>

但是,如果我将 .cpp 文件中的 first_node() 调用更改为不存在的节点,如下所示:

xml_node<>* prop_node = doc.first_node("Property");

程序在运行时崩溃,提示内存访问错误而不是抛出异常。

这是 RapidXML 应该的工作方式还是我做错了什么?

谢谢!

最佳答案

我对 RapidXML 不是很熟悉,但是我从它的引用页面上找到了以下关于 first_node 的内容。 http://rapidxml.sourceforge.net/manual.html#namespacerapidxml_1what_is_rapidxml

function xml_node::first_node

Synopsis

xml_node* first_node(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const; Description

Gets first child node, optionally matching node name. Parameters

name Name of child to find, or 0 to return first child regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero name_size Size of name, in characters, or 0 to have size calculated automatically from string case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters Returns

Pointer to found child, or 0 if not found.

因此您可以调用 first_node 而无需指定其名称。(尽管这可能不是您问题的直接答案。)

或者检查doc.first_node("Property")的返回值是否为0,如果返回值不为0才赋值给prop_node。

关于c++ - RapidXML 节点异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24699572/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com