C++ XML Objects Use: Reading the XML file

Previous Next Usage Home Installation Docs


We can now read the objects out of the XML file.


The following code reads the objects out of the xml file called "test1.xml" and returns an object of "root" type:

xmlobj_jscript_navigate n(&output, false);
context c(&n);
root *r = xmlobj_read_file<root>(infile, &c, &std::cerr, false, PARSEOBJ_NO_DEBUG);

The first line defines the type of syntax that will be used to define relationships between the objects in the XML file. At the moment I have written a navigator which emulates the simple "JavaScript" DOM syntax (like root().parent() etc). This isn't used in our file at the moment, but later on when we use "fragments", you'll see it come alive. Somebody could write one that handled an XPath syntax for example.

The next line declares a "context" object which allows your code to define all of the objects that may appear in the XML file. You derived from the context like this:

class context : public ph::xmlobj::xmlobj_context
	context(ph::reflect::object_navigator_factory *navfactory) :

	// ph::xmlobj::xmlobj_context overrides.
	virtual bool register_objects();

bool context::register_objects()
	register_object(new root("@xmlobj", "root"));
	register_object(new foo("@xmlobj", "foo"));
	register_object(new bar("foo", "bar"));
	return true;

It might not be immediately clear why we need a "type" and a "name" as a string, but a later feature will explain this a lot better. For each registered object, the "type" of the object is it's superclass type, and it's name is actually the type name that will appear in the file.

When an object is derived from ph::xmlobj::xmlobj, it uses "@xmlobj" as it's type. The reason for that "@" is simply so that it is impossible to use abstract objects in your XML files. You can't register abstract objects (since you can't create them, and wouldn't want to).

Finally, the object is read from the std::istream "infile", sending any errors (like syntax errors etc) to std::cerr. The last two arguments let you read and fail silently (doesn't output any errors), and define a level for debugging (some of those files can get complex :-).

Now we have our objects read from the file, we can play around with them.

Previous Next Usage Home Installation Docs

Generated: Wed Apr 5 23:00:19 EST 2006

Copyright (c) 2005; Paul Hamilton; pHamtec P/L.

Use, modification, and distribution is provided free of any limitations.