From 689b1a86d0c4cf4937492f4680457a133df368c6 Mon Sep 17 00:00:00 2001 From: Carl Hetherington Date: Tue, 8 Jul 2014 22:40:36 +0100 Subject: [PATCH 1/1] Add the ability to find the root node name of some XML. --- src/cxml.cc | 9 ++++++++- src/cxml.h | 9 +++++++-- test/tests.cc | 13 ++++++++----- 3 files changed, 23 insertions(+), 8 deletions(-) diff --git a/src/cxml.cc b/src/cxml.cc index b251ae7..99055ee 100644 --- a/src/cxml.cc +++ b/src/cxml.cc @@ -239,6 +239,11 @@ cxml::Document::Document (string root_name, boost::filesystem::path file) read_file (file); } +cxml::Document::Document () +{ + _parser = new xmlpp::DomParser (); +} + cxml::Document::~Document () { delete _parser; @@ -270,8 +275,10 @@ cxml::Document::take_root_node () } _node = _parser->get_document()->get_root_node (); - if (_node->get_name() != _root_name) { + if (!_root_name.empty() && _node->get_name() != _root_name) { throw cxml::Error ("unrecognised root node"); + } else if (_root_name.empty ()) { + _root_name = _node->get_name (); } } diff --git a/src/cxml.h b/src/cxml.h index 0f57b92..a8da82a 100644 --- a/src/cxml.h +++ b/src/cxml.h @@ -213,14 +213,19 @@ typedef boost::shared_ptr ConstNodePtr; class Document : public Node { public: + Document (); Document (std::string root_name); Document (std::string root_name, boost::filesystem::path); + virtual ~Document (); + void read_file (boost::filesystem::path); void read_stream (std::istream &); - virtual ~Document (); - + std::string root_name () const { + return _root_name; + } + private: void take_root_node (); diff --git a/test/tests.cc b/test/tests.cc index 77f13c6..9d07e7c 100644 --- a/test/tests.cc +++ b/test/tests.cc @@ -69,10 +69,13 @@ BOOST_AUTO_TEST_CASE (test) BOOST_CHECK (!document.optional_bool_child("G")); - BOOST_CHECK_EQUAL (document.node_children("H/I").size(), 2); - BOOST_CHECK_EQUAL (document.node_children("H/I").front()->content(), "testing"); - BOOST_CHECK_EQUAL (document.node_children("H/I").back()->content(), "more testing"); + list > h = document.node_children ("H"); + BOOST_CHECK_EQUAL (h.size(), 1); + BOOST_CHECK_EQUAL (h.front()->node_children("I").size(), 2); + BOOST_CHECK_EQUAL (h.front()->node_children("I").front()->content(), "testing"); + BOOST_CHECK_EQUAL (h.front()->node_children("I").back()->content(), "more testing"); - BOOST_CHECK_EQUAL (document.string_child("J/K"), "jim"); - BOOST_CHECK (!document.optional_bool_child("G")); + BOOST_CHECK_EQUAL (document.node_children("J").size(), 1); + BOOST_CHECK_EQUAL (document.node_children("J").front()->node_children("K").size(), 1); + BOOST_CHECK_EQUAL (document.node_children("J").front()->node_children("K").front()->content(), "jim"); } -- 2.30.2