1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
|
// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt
/*
This is an example illustrating the use of the xml_parser component in
the dlib C++ Library.
This example simply reads in an xml file and prints the parsing events
to the screen.
*/
#include <dlib/xml_parser.h>
#include <iostream>
#include <fstream>
using namespace std;
using namespace dlib;
// ----------------------------------------------------------------------------------------
class doc_handler : public document_handler
{
/*
As the parser runs it generates events when it encounters tags and
data in an XML file. To be able to receive these events all you have to
do is make a class that inherits from dlib::document_handler and
implements its virtual methods. Then you simply associate an
instance of your class with the xml_parser.
So this class is a simple example document handler that just prints
all the events to the screen.
*/
public:
virtual void start_document (
)
{
cout << "parsing begins" << endl;
}
virtual void end_document (
)
{
cout << "Parsing done" << endl;
}
virtual void start_element (
const unsigned long line_number,
const std::string& name,
const dlib::attribute_list& atts
)
{
cout << "on line " << line_number << " we hit the <" << name << "> tag" << endl;
// print all the tag's attributes
atts.reset();
while (atts.move_next())
{
cout << "\tattribute: " << atts.element().key() << " = " << atts.element().value() << endl;
}
}
virtual void end_element (
const unsigned long line_number,
const std::string& name
)
{
cout << "on line " << line_number << " we hit the closing tag </" << name << ">" << endl;
}
virtual void characters (
const std::string& data
)
{
cout << "Got some data between tags and it is:\n" << data << endl;
}
virtual void processing_instruction (
const unsigned long line_number,
const std::string& target,
const std::string& data
)
{
cout << "on line " << line_number << " we hit a processing instruction with a target of '"
<< target << "' and data '" << data << "'" << endl;
}
};
// ----------------------------------------------------------------------------------------
int main(int argc, char** argv)
{
try
{
// Check if the user entered an argument to this application.
if (argc != 2)
{
cout << "Please enter an xml file to parse on the command line" << endl;
return 1;
}
doc_handler dh;
// Now run the parser and tell it to call our doc_handler for each of the parsing
// events.
parse_xml(argv[1], dh);
}
catch (std::exception& e)
{
cout << e.what() << endl;
}
}
|