diff options
author | Bjørn Lindeijer <bjorn@lindeijer.nl> | 2008-04-07 08:37:23 +0000 |
---|---|---|
committer | Bjørn Lindeijer <bjorn@lindeijer.nl> | 2008-04-07 08:37:23 +0000 |
commit | 64d58b9a7e057e6d829107678b1570082be1093f (patch) | |
tree | f95a940521150e8f5bbab1bba520c956c8b2aed9 /src/utils | |
parent | 36a53a1d5e3b558dafe200a6929948e7730c94f0 (diff) | |
download | mana-64d58b9a7e057e6d829107678b1570082be1093f.tar.gz mana-64d58b9a7e057e6d829107678b1570082be1093f.tar.bz2 mana-64d58b9a7e057e6d829107678b1570082be1093f.tar.xz mana-64d58b9a7e057e6d829107678b1570082be1093f.zip |
Added XML::Document class which simplifies parsing an XML document and
automatically cleans it up again.
Diffstat (limited to 'src/utils')
-rw-r--r-- | src/utils/xml.cpp | 36 | ||||
-rw-r--r-- | src/utils/xml.h | 37 |
2 files changed, 73 insertions, 0 deletions
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 @@ -34,6 +34,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. */ int |