rendered paste body#include <iostream>#include <sstream>#include <string>using std::endl;#include "Handler.h"#include "Parser.h"class NumberHandler: public XMLHandler {public: NumberHandler(int* result): result(result), num(0) {} void character_data(const char* s, size_t len) { unsigned int i; for (i=0; i<len; ++i) { if ('0' <= s[i] && s[i] <= '9') { num *= 10; num += s[i] - '0'; } else { throw_error("Non-digit found in <data>"); } } *result = num; //XXX hack! should implement handler_popped } void handler_popped() { *result = num; } NumberHandler* clone() const { return new NumberHandler(*this); }private: int* result; int num;};struct SampleData { SampleData(): string(), num(0) {} std::string string; int num;};class TestHandler: public XMLHandler {public: TestHandler(SampleData* data): data(data), in_data(false), in_string(false), in_num(false) { //push_handler(this); } void start_element(const std::string& name, const XML_Char**) { if (name == "data") { in_data = true; } else if (name == "string" && in_data) { in_string = true; } else if (name == "num" && in_data) { in_num = true; push_handler(NumberHandler(&data->num)); } } void end_element(const std::string& name) { if (name == "data") { if (in_data) { in_data = false; } else { throw_error("end of data but we weren't in data"); } } else if (name == "string") { if (in_string) { in_string = false; } else { throw_error("end of string but we weren't in string"); } } else if (name == "num") { if (in_num) { in_num = false; } else { throw_error("end of num but we weren't in num"); } } } void character_data(const char *s, size_t len) { if (in_string) { data->string.append(s, len); } } TestHandler* clone() const { return new TestHandler(*this); }private: SampleData* data; bool in_data, in_string, in_num;};int main() { std::string xml("<data><string>foobarbaz</string><num>12345</num></data>"); SampleData data; { //dummy scope to control parser destruction XMLParser parser; parser.push_handler(TestHandler(&data)); if (!parser.parse(xml)) { std::cerr << "Parse error: " << parser.get_error().str() << endl; return 1; } } if (data.string != "foobarbaz") { std::cerr << "Parsed string doesn't match" << endl; return 1; } if (data.num != 12345) { std::cerr << "Parsed number doesn't match" << endl; return 1; } return 0;}/* vim: set ts=4 sw=4 et: */