diff --git a/include/Swiften/Parser/StringTreeParser.cpp b/include/Swiften/Parser/StringTreeParser.cpp new file mode 100644 index 00000000..92412d14 --- /dev/null +++ b/include/Swiften/Parser/StringTreeParser.cpp @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2011 Jan Kaluza + * Licensed under the Simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +#include +#include +#include +#include + +namespace Swift { + +class DefaultStringTreeParser : public StringTreeParser { + public: + void handleTree(ParserElement::ref root) { + root_ = root; + } + + ParserElement::ref getRoot() { + return root_; + } + + private: + ParserElement::ref root_; +}; + +ParserElement::ref StringTreeParser::parse(const std::string &xml) { + PlatformXMLParserFactory factory; + DefaultStringTreeParser client; + XMLParser *parser = factory.createXMLParser(&client); + + parser->parse(xml); + ParserElement::ref root = client.getRoot(); + delete parser; + return root; +} + +} diff --git a/include/Swiften/Parser/StringTreeParser.h b/include/Swiften/Parser/StringTreeParser.h new file mode 100644 index 00000000..06089a7d --- /dev/null +++ b/include/Swiften/Parser/StringTreeParser.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2011 Jan Kaluza + * Licensed under the Simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +#pragma once + +#include + +#include +#include + +#include +#include + +namespace Swift { + /** + * Generics parser offering something a bit like a DOM to work with. + */ + class StringTreeParser : public XMLParserClient { + public: + StringTreeParser() : XMLParserClient() {} + + virtual void handleStartElement(const std::string& element, const std::string& xmlns, const AttributeMap& attributes) { + if (!root_) { + root_ = boost::make_shared(element, xmlns, attributes); + elementStack_.push_back(root_); + } + else { + ParserElement::ref current = *elementStack_.rbegin(); + elementStack_.push_back(current->addChild(element, xmlns, attributes)); + } + } + + virtual void handleEndElement(const std::string& /*element*/, const std::string&) { + elementStack_.pop_back(); + if (elementStack_.empty()) { + handleTree(root_); + } + } + + virtual void handleCharacterData(const std::string& data) { + ParserElement::ref current = *elementStack_.rbegin(); + current->appendCharacterData(data); + } + + virtual void handleTree(ParserElement::ref root) = 0; + + static ParserElement::ref parse(const std::string &xml); + + private: + std::deque elementStack_; + ParserElement::ref root_; + }; +}