Using the xmlsax class
The xmlsax class provides a callback-based framework for parsing XML documents. The xmlsax class provides methods for parsing strings of XML or XML files. When it encounters a tag, attribute or other XML component, it calls one of it's callback methods. These methods may be overridden by a child class to perform specific tasks. The xmlsax class is especially useful if you can't afford to load the entire document into memory and use the xmldom class, or if you just need to extract specific data from an XML file.
The following example creates a child class of xmlsax that overrides the tagStart(), attributeName(), attributeValue(), text(), tagEnd(), and comment() callback methods to print information about each XML component encountered during parsing.
#include <rudiments/xmlsax.h>
#include <rudiments/stdio.h>
// create an xml sax handler by inheriting from xmlsax
class myxmlhandler : public xmlsax {
protected:
bool tagStart(const char *ns, const char *name) {
stdoutput.printf("start tag: %s\n",name);
return true;
}
bool attributeName(const char *name) {
stdoutput.printf(" attribute: %s",name);
return true;
}
bool attributeValue(const char *value) {
stdoutput.printf(" = \"%s\"\n",value);
return true;
}
bool text(const char *string) {
stdoutput.printf(" text: %s\n",string);
return true;
}
bool tagEnd(const char *ns, const char *name) {
stdoutput.printf("end tag: %s\n",name);
return true;
}
bool comment(const char *string) {
stdoutput.printf("comment: %s\n",string);
return true;
}
};
int main(int argc, const char **argv) {
myxmlhandler handler;
// parse an xml string
stdoutput.write("parsing xml:\n\n");
handler.parseString(
"<!-- a list of cities -->"
"<cities>"
" <city country=\"US\">New York</city>"
" <city country=\"UK\">London</city>"
" <city country=\"JP\">Tokyo</city>"
"</cities>");
}