From 64d58b9a7e057e6d829107678b1570082be1093f Mon Sep 17 00:00:00 2001 From: Bjørn Lindeijer Date: Mon, 7 Apr 2008 08:37:23 +0000 Subject: Added XML::Document class which simplifies parsing an XML document and automatically cleans it up again. --- src/utils/xml.cpp | 36 ++++++++++++++++++++++++++++++++++++ src/utils/xml.h | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+) (limited to 'src/utils') diff --git a/src/utils/xml.cpp b/src/utils/xml.cpp index e30450f0..98b474cb 100644 --- a/src/utils/xml.cpp +++ b/src/utils/xml.cpp @@ -22,9 +22,45 @@ */ #include "xml.h" +#include "../log.h" +#include "../resources/resourcemanager.h" namespace XML { + Document::Document(const std::string &filename): + mDoc(NULL) + { + int size; + ResourceManager *resman = ResourceManager::getInstance(); + char *data = (char*) resman->loadFile(filename.c_str(), size); + + if (data) { + mDoc = xmlParseMemory(data, size); + free(data); + + if (!mDoc) + logger->log("Error parsing XML file %s", filename.c_str()); + } else { + logger->log("Error loading %s", filename.c_str()); + } + } + + Document::Document(const char *data, int size) + { + mDoc = xmlParseMemory(data, size); + } + + Document::~Document() + { + if (mDoc) + xmlFreeDoc(mDoc); + } + + xmlNodePtr Document::rootNode() + { + return mDoc ? xmlDocGetRootElement(mDoc) : 0; + } + int getProperty(xmlNodePtr node, const char* name, int def) { diff --git a/src/utils/xml.h b/src/utils/xml.h index ef3bad3d..5473b2ca 100644 --- a/src/utils/xml.h +++ b/src/utils/xml.h @@ -33,6 +33,43 @@ */ namespace XML { + /** + * A helper class for parsing an XML document, which also cleans it up + * again (RAII). + */ + class Document + { + public: + /** + * Constructor that attempts to load the given file through the + * resource manager. Logs errors. + */ + Document(const std::string &filename); + + /** + * Constructor that attempts to load an XML document from memory. + * Does not log errors. + * + * @param data the string to parse as XML + * @param size the length of the string in bytes + */ + Document(const char *data, int size); + + /** + * Destructor. Frees the loaded XML file. + */ + ~Document(); + + /** + * Returns the root node of the document (or NULL if there was a + * load error). + */ + xmlNodePtr rootNode(); + + private: + xmlDocPtr mDoc; + }; + /** * Gets an integer property from an xmlNodePtr. */ -- cgit v1.2.3-70-g09d2