<chapter xmlns="http://www.gobosoft.com/eiffel/gobo/documentation" id="using_xml_parser">
<chapterinfo>
	<copyright>
		<year>2005</year>
		<holder>Eric Bezault</holder>
	</copyright>
	<author>
		<firstname>Eric</firstname><surname>Bezault</surname>
	</author>
	<email>ericb@gobosoft.com</email>
	<date>7 July 2005</date>
</chapterinfo>

<title>Using the XML parser</title>

<section id="first_xml_example">
<title>A first example: counting tags</title>

<para>
Let's start with a simple example of an XML parser that counts the number of tags in an input file. This example has two classes, the main class that opens the file and creates the parser, and a descendant of the callbacks class that receives events from the parser. The main class will connect this event consumer with the parser. 
</para>

<para>
The base class for events is <classname>XM_CALLBACKS</classname> which has all features deferred. For this example, only a couple of events are needed, so <classname>XM_CALLBACKS_NULL</classname> which provides empty bodies for all events is used for convenience. The events we redefine are routines called when the parser is started, and whenever it encounters a start (opening) XML tag.
</para>

<programlisting>
class TAGCOUNT_CALLBACKS

inherit

	XM_CALLBACKS_NULL
		redefine
			on_start,
			on_start_tag
		end

creation

	make

feature -- Events
	
	on_start is
			-- Reset tag count.
		do
			count := 0
		end
		
	on_start_tag (a_namespace: STRING; a_prefix: STRING; a_local_part: STRING) is
			-- Count start tags.
		do
			count := count + 1
		end
	
feature -- Access
	
	count: INTEGER
			-- Number of tags seen.
			
end
</programlisting>

<para>
The main class creates the parser, the routines that read the command line and open the 
file are standard and omitted here, which leaves the main routine that sets up 
and starts the parser, and prints the result:
</para>

<programlisting>
	parse_stream (a_stream: KI_CHARACTER_INPUT_STREAM) is
			-- Parse open stream.
		require
			a_stream_not_void: a_stream /= Void
			a_stream_open: a_stream.is_open_read
		local
			a_parser: XM_PARSER
			a_consumer: TAGCOUNT_CALLBACKS
		do
			-- Create the parser. 
			-- It is left in the default state, which means: 
			-- ascii only, no external entities or DTDs, 
			-- no namespace resolving.
			create {XM_EIFFEL_PARSER} a_parser.make
			
			-- Create the event consumer that counts start tags. 
			create {TAGCOUNT_CALLBACKS} a_consumer.make	
			a_parser.set_callbacks (a_consumer)
			
			-- Parse and display result
			a_parser.parse_from_stream (a_stream)
			if not a_parser.is_correct then
				error_handler.report_error_message (a_parser.last_error_extended_description)
			else
				error_handler.report_info_message ("Number of tags found: " + a_consumer.count.out)
			end
		end
</programlisting>

<para>
The full example is available at <filename class="directory">example/xml/event/tagcount</filename>.
</para>

</section>


<section id="xml_event_interfaces">
<title>Event interfaces</title>

<para>
Event interfaces are the lowest level of communication with an XML parser. An event interface is a deferred class containing callback calls. Sources of events, like a parser, have routines to attach a descendant of the event interface.
</para>

<para>
For each event interface, there is a purely deferred class with the callbacks, of which clients inherit, and a 'source' class, which events sources, like the parser, inherit. For the main XML content events, the event interface is <classname>XM_CALLBACKS</classname>, and the source is <classname>XM_CALLBACKS_SOURCE</classname>. It provides a <featurename>set_callbacks</featurename> feature, and the parser inherits from it.
</para>

<para>
DTD events are covered separately, for parsers that support them, using <classname>XM_DTD_CALLBACKS</classname> and <classname>XM_DTD_CALLBACKS_SOURCE</classname> (with <featurename>set_dtd_callbacks</featurename>).
</para>
</section>

<section id="xml_parsers">
<title>The XML parser interface</title>

<para>
The public interface of XML parsers is represented in the deferred class <classname>XM_PARSER</classname>. Parsers are event sources, inheriting from the event sources classes to provide <featurename>set_callbacks</featurename> and <featurename>set_dtd_callbacks</featurename>. An input document is parsed using <featurename>parse_from_stream</featurename> and similar features, which accept strings or IO streams from the Gobo Kernel library. Incremental parsing routines are available to parse a document a chunk at a time, if the parser supports it, which can be checked with <featurename>is_incremental</featurename>. 
</para>

<para>
Errors can be collected but are also forwarded to the event interface. Because an event filter stream as described below can produce its own errors, not reflected in the event source that is the parser, it may be more sensible in most cases to collect errors downstream.
</para>

<para>
The parsers have a <emphasis>string mode</emphasis>. Because XML documents can contain unicode characters that do not fit in most Eiffel compilers' <classname>CHARACTER</classname> and <classname>STRING</classname> types, the Gobo Eiffel library provides a Unicode string class, that inherits from <classname>STRING</classname>. The base class of Gobo's unicode string classes is <classname>UC_STRING</classname>. There are some subtle issues with polymorphism, for instance:
</para>

<programlisting>
"hello".append_string (a_uc_string)
</programlisting>

<para>
will not work because the call target is of dynamic type <classname>STRING</classname> which does not know about <classname>UC_STRING</classname>. A library routine, <classname>KL_STRING_ROUTINES</classname>'s <featurename>appended_string</featurename>, that copes with polymorphism is provided to replace the original routine. Other polymorphic routines are treated similarly. The Gobo Unicode facilities are described in more detail elsewhere along with the rationale for this design. <!-- FIXME: reference to Gobo Unicode doc! -->
</para>

<para>
As this potential polymorphism puts a burden of care on the client, and could lead to hard to detect problems for unprepared clients, the XML parsers default to a safe mode, where only instances of <classname>STRING</classname> are produced, and a parsing error occurs if the XML input contains some characters that do not fit in <classname>STRING</classname>. If the application input is only ASCII files, nothing else needs to be done. Otherwise, it may be necessary to set the string mode to some other mode, such as producing exclusively <classname>UC_STRING</classname> descendants, or producing them only when needed. These string mode settings are contained in the class <classname>XM_STRING_MODE</classname>, a parent of the parser classes.
</para>

<para>
Another setting a parser user may want to change from the default relates to external references, described below.
</para>

</section>

<section id="concrete_xml_parsers">
<title>Concrete parsers</title>

<para>
Several concrete parsers are available, which are descendants of this interface. The pure Eiffel parser is <classname>XM_EIFFEL_PARSER</classname>. The parser making use of and depending on the Expat C library is <classname>XM_EXPAT_PARSER</classname>. These classes can be created directly.
</para>

<para>
Because Expat introduces external dependencies in the library, a factory class is available to allow the same client code to work independently of whether or not the Expat parser is compiled in: <classname>XM_EXPAT_PARSER_FACTORY</classname>. The value of <featurename>is_expat_available</featurename> depends on whether Expat is available, and code may portably act accordingly, for instance falling back to the Eiffel parser.
</para>

</section>

<section id="xml_event_filters">
<title>Event filters and streams</title>

<para>
On top of the event interface, the XML library provides a set of filters and a framework for using filters. The filters are arranged in a stream, in a manner similar to the Unix command shell.
</para>

<para>
Each component of a filter pipe is a descendant of a filter base class, <classname>XM_CALLBACKS_FILTER</classname> for content events, which has a <featurename>next</featurename> attribute. The default implementation of each event is simply to forward the event to the next filter. A filter that uses only a few events can redefine only the required routines. Redefinition of routines are expected to do their processing and then forward the event to the next filter, for instance using <featurename>Precursor</featurename>. The class provides two routines that can be used as creation procedures: <featurename>make_null</featurename> sets <featurename>next</featurename> to a filter that does nothing on each event. This null filter, <classname>XM_CALLBACKS_NULL</classname> for content events, allows each component of a pipe to be used at any position in the pipe, including at the end, and the next filter to be set when convenient, while maintaining an invariant that <featurename>next</featurename> is not Void. The feature <featurename>set_next</featurename> can also be used as a creation procedure.
</para>

<para>
From an Eiffel typing viewpoint, the whole stream has the same type: each filter can be at any position in the pipe. It maybe that some filters have extra dependencies (one must be before the other) that are not captured by the static type system. This seems acceptable given the flexibility of the system, and that many practical filters can indeed be placed anywhere on a pipe. A good point for encapsulation is that each filter is a small component with a clear interface, providing much better encapsulation than some other event filter patterns (like each stage inheriting from the previous one, with high coupling between each component).
</para>

</section>

<section>
<title>Content events</title>

<para>
The content events are the core of the XML parser interface. They cover elements and attributes, in addition to less fundamental feature like comments and processing instructions. There are also events called on startup and at the end of parsing.
</para>

<para>
All events of <classname>XM_CALLBACKS</classname> that take names of tags or attributes, follow the same convention. The signature includes the namespace (a string representing the namespace URI), name prefix and local part. The parser is not expected to provide to resolve namespaces, with a filter introduced below resolving the namespaces and replacing the non-resolved namespaces (Void) downstream of the filter pipe. Whether a namespace is set can be checked with <featurename>has_namespace</featurename>.
</para>

<para>
To make the interface consistently simple, it has only atomic events whose parameters are only strings and not data structures. Data structures are built downstream, or as intermediary internal structures of a specific filter. In particular, this means there is one event per attribute.
</para>

</section>

<section>
<title>Content event filters</title>

<para>
A set of standard content event filters is available in the library. There is a factory class <classname>XM_CALLBACKS_FILTER_FACTORY</classname> with creation routines and convenience routines to build pipes and bind the filters to each other. The filters can be created directly, the factory is only there for convenience.
</para>

<para>
The namespace resolving filter <classname>XM_NAMESPACE_RESOLVER</classname> will be in most standard pipes. It reads XML namespace declaration attributes (these events are not forwarded downstream) and adds a resolved namespace URI to all outgoing names.
</para>

<para>
For completely correct validation of unicode character classes in XML names, the filter <classname>XM_UNICODE_VALIDATION_FILTER</classname> should be used. It is transparent unless an error occurs when it issues an error event, so an error filter should be connected later in the pipe.
</para>

<para>
The atomicity of content events is not guaranteed by the parser, that is two or more <featurename>on_content</featurename> events may follow each other. The <classname>XM_CONTENT_CONCATENATOR</classname> filter turns succeeding content events into one. It will be usually be preceded by a <classname>XM_NO_COMMENT_FILTER</classname> filter which removes comment events, because otherwise events placed in the middle of content will also contribute  non-atomic content events separated by comment events.
</para>

<para>
Without <classname>XM_STOP_ON_ERROR_FILTER</classname> the event flow may continue after an error. This filter stops all event forwarding from the first error, which it remembers for later use (<featurename>has_error</featurename> and <featurename>last_error</featurename>). It is useful for most standard pipes, indeed an error condition is better collected here, including errors within the preceding filters, than in the parser itself.
</para>

<para>
<classname>XM_PRETTY_PRINT_FILTER</classname> is a filter that prints out the event stream as an XML document, to the standard output, or a string. It can be placed anywhere in the stream, which may be convenient for debugging.
</para>

<para>
To produce the output in a tree structure (descendants from <classname>XM_NODE</classname>), the filter <classname>XM_CALLBACKS_TO_TREE_FILTER</classname> is used. It expects resolved namespaces.
</para>

<para>
<classname>XM_SHARED_STRINGS_FILTER</classname> saves memory and possibly comparison time by making all equal strings point to a single instance. The downstream events must then consider strings immutable. This sharing is across event categories: for example, if a content happens to be the same as an element name, it will be the same string.
</para>

<para>
To finish this section, here is an example of a filter pipe, using the factory class convenience routines <featurename>callbacks_pipe</featurename> that simply binds the next pipe of each filter in an array and returns the first element:
</para>

<programlisting>
...
inherit
	XM_CALLBACKS_FILTER_FACTORY
...

a_parser: XM_PARSER
...

a_parser.set_callbacks (callbacks_pipe (
		&lt;&lt; new_namespace_resolver,
			new_stop_on_error,
			new_tree_builder >>))
...
</programlisting>

<para>
In a real program, references may be kept to individual filters, to recover the result or check their state after processing. <classname>XM_TREE_CALLBACKS_PIPE</classname> provides a standard pipe for tree creation with attributes for the interesting component filters.
</para>

</section>
<!-- section DTD events -->

<!-- summary! -->

</chapter>
