From 4b2eea202ceae63ac028df7dd712efeb4b58eb26 Mon Sep 17 00:00:00 2001 From: Davis King Date: Sat, 6 May 2017 12:46:19 -0400 Subject: [PATCH] Made the attribute_list of the xml parser a little more friendly by allowing you to ask for attributes that don't exist and get a defined behavior (an exception being thrown) rather than it being a contract violation. --- dlib/xml_parser/xml_parser_kernel_1.h | 7 ++++-- .../xml_parser/xml_parser_kernel_interfaces.h | 23 +++++++++++++++---- 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/dlib/xml_parser/xml_parser_kernel_1.h b/dlib/xml_parser/xml_parser_kernel_1.h index f2a5b02b7..751cd742f 100644 --- a/dlib/xml_parser/xml_parser_kernel_1.h +++ b/dlib/xml_parser/xml_parser_kernel_1.h @@ -49,7 +49,7 @@ namespace dlib public: - // These typedefs are here for backwards compatibily with previous versions of + // These typedefs are here for backwards compatibly with previous versions of // dlib. typedef xml_parser kernel_1a; typedef xml_parser kernel_1a_c; @@ -103,7 +103,10 @@ namespace dlib const std::string& key ) const { - return list[key]; + if (is_in_list(key)) + return list[key]; + else + throw xml_attribute_list_error("No XML attribute named " + key + " is present in tag."); } bool at_start ( diff --git a/dlib/xml_parser/xml_parser_kernel_interfaces.h b/dlib/xml_parser/xml_parser_kernel_interfaces.h index a49d53394..a0edf3317 100644 --- a/dlib/xml_parser/xml_parser_kernel_interfaces.h +++ b/dlib/xml_parser/xml_parser_kernel_interfaces.h @@ -6,10 +6,24 @@ #include #include "../interfaces/enumerable.h" #include "../interfaces/map_pair.h" +#include "../error.h" namespace dlib { +// ---------------------------------------------------------------------------------------- + + class xml_attribute_list_error : public dlib::error + { + /*! + WHAT THIS OBJECT REPRESENTS + This is an exception object thrown by attribute_list objects if you try to + access a non-existent attribute. + !*/ + public: + xml_attribute_list_error(const std::string& msg) : dlib::error(msg){} + }; + // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- @@ -43,11 +57,12 @@ namespace dlib const std::string& key ) const =0; /*! - requires - - is_in_list(key) == true ensures - - returns a const reference to the value associated with the - attribute named key. + if (is_in_list(key) == true) then + - returns a const reference to the value associated with the attribute + named key. + - else + - throws xml_attribute_list_error !*/ protected: