; docformat = 'rst'
;+
; This class is an example of using a SAX parser to parse XML files.
;
; :Examples:
; Run the main-level program to see an example of using the class to parse
; an XML file available from the internet.
;
; :Author:
; Michael Galloy
;-
;+
; Returns the current indentation as a string.
;
; :Private:
;
; :Returns:
; string
;-
function mg_xmlsax_example::_getSpacing
compile_opt strictarr
return, self.indentation eq 0L $
? '' $
: (string(bytarr(4 * self.indentation) + 32B))
end
;+
; Called by parser when an XML tag is first encountered.
;
; :Params:
; uri : in, required, type=string
; namespace URI associated with element
; local : in, required, type=string
; tag name with any prefix removed
; name : in, required, type=string
; tag name
; attname : in, optional, type=starr
; attribute names, if present
; attvalue : in, optional, type=strarr
; attribute values, if present
;-
pro mg_xmlsax_example::startElement, uri, local, name, attname, attvalue
compile_opt strictarr
print, string(format='(%"%sStarting to parse tag named: \"%s\", URI: \"%s\", Local: \"%s\"")', $
self->_getSpacing(), name, uri, local)
; handle attributes, if present
if (n_elements(attname) gt 0L) then begin
print, transpose(self->_getSpacing() + ' :' + attname + '="' + attvalue + '"')
endif
++self.indentation
end
;+
; Called by the parser when an XML tag is finished.
;
; :Params:
; uri : in, required, type=string
; namespace URI associated with element
; local : in, required, type=string
; tag name with any prefix removed
; name : in, required, type=string
; tag name
;-
pro mg_xmlsax_example::endElement, uri, local, name
compile_opt strictarr
--self.indentation
end
;+
; Called for text content between tags.
;
; This method is called frequently because *any* character data between a
; begin and end tag counts (i.e. linefeeds, spaces, etc.).
;
; :Params:
; chars : in, required, type=string
; string between tags
;-
pro mg_xmlsax_example::characters, chars
compile_opt strictarr
if (~stregex(chars, '^[[:space:]]+$', /boolean)) then begin
print, self->_getSpacing() + '"' + chars + '"'
endif
end
;+
; Initialize the XML SAX parser.
;
; :Returns:
; 1 if successful, 0 if not
;
; :Keywords:
; _extra : in, optional, type=keywords
; keywords to IDLffXMLSAX::init
;-
function mg_xmlsax_example::init, _extra=e
compile_opt strictarr
if (~self->idlffxmlsax::init(_extra=e)) then return, 0
return, 1
end
;+
; Define instance variables for parser. Make sure to inherit from IDLffXMLSAX.
;-
pro mg_xmlsax_example__define
compile_opt strictarr
define = { mg_xmlsax_example, inherits IDLffXMLSAX, indentation: 0L }
end
; Main-level program example of using mg_xmlsav_example class
xml = obj_new('mg_xmlsax_example')
xml->parseFile, 'http://updates.idldev.com/site.xml', /url
print, transpose(strarr(2))
xml->parseFile, filepath('planets.xml', subdir=['examples', 'data'])
obj_destroy, xml
end