3.2 Library interface

Using the library interface of xml.hwp gives your script the most flexibility and allows you to access all features of XML documents. The library interface is based on the SAX parsing model which means that you specify a number of callbacks which the XML parser will call while it is parsing your document. One of those callbacks is the StartElement() callback. It will be called whenever the parser encounters a new XML tag in the document. As described in its manual page, StartElement() receives three arguments: The parser handle, the element name and a table containing the XML attributes specified in the tag. Thus, a StartElement() callback could look like this:

 
Function p_StartElement(p, name$, attrs)
   DebugPrint("New tag found:", name$)
   For k,v In Pairs(attrs) Do DebugPrint(k .. "=" .. v)
EndFunction

The code above will print the name of the XML tag the parser has just handled as well as all the attributes specified in the XML tag declaration. After having defined the callback, we now have to create a XML parser. This is done using the xml.CreateParser() function. You have to pass all callbacks you want to use to it. For our little example, we only want to use the StartElement() callback so we create the parser like this:

 
p = xml.CreateParser({StartElement = p_StartElement})

As a next thing, we can feed XML data to the parser. This is done by calling the parser:Parse() method:

 
p:Parse([[<plugin name="XML" author="A. Falkenhahn" version="1.0"/>]])

Running this code will print the plugin's name as well as the attributes name, author and version. You can call parser:Parse() as often as you want. When you're finished, don't forget to call parser:Free() to free the parser handle. So here's the full example code of our minimal XML parser from above, ready to be copy and pasted into the Hollywood IDE:

 
@REQUIRE "xml"

Function p_StartElement(p, name$, attrs)
   DebugPrint("New tag found:", name$)
   For k,v In Pairs(attrs) Do DebugPrint(k .. "=" .. v)
EndFunction

p = xml.CreateParser({StartElement = p_StartElement})
p:Parse([[<plugin name="XML" author="A. Falkenhahn" version="1.0"/>]])
p:Free()

Of course, there are many other callback types besides StartElement(). See xmlCreateParser for details.

Alternatively, you can also use the plugin's serialization interface. This is easier because it only requires a single function call to convert Hollywood tables to XML documents and vice versa but you won't have fine-tuned control over everything as you have when using the library interface.

See the next chapter for more details on the plugin's serialization interface.


Show TOC