Source Edit

This module implements a simple high performance XML / HTML parser. The only encoding that is supported is UTF-8. The parser has been designed to be somewhat error correcting, so that even most “wild HTML” found on the web can be parsed with it. Note: This parser does not check that each <tag> has a corresponding </tag>! These checks have do be implemented by the client code for various reasons:

  • Old HTML contains tags that have no end tag: <br> for example.
  • HTML tags are case insensitive, XML tags are case sensitive. Since this library can parse both, only the client knows which comparison is to be used.
  • Thus the checks would have been very difficult to implement properly with little benefit, especially since they are simple to implement in the client. The client should use the errorMsgExpected proc to generate a nice error message that fits the other error messages this library creates.

Example 1: Retrieve HTML title

The file examples/htmltitle.nim demonstrates how to use the XML parser to accomplish a simple task: To determine the title of an HTML document.

  1. # Example program to show the parsexml module
  2. # This program reads an HTML file and writes its title to stdout.
  3. # Errors and whitespace are ignored.
  4. import os, streams, parsexml, strutils
  5. if paramCount() < 1:
  6. quit("Usage: htmltitle filename[.html]")
  7. var filename = addFileExt(paramStr(1), "html")
  8. var s = newFileStream(filename, fmRead)
  9. if s == nil: quit("cannot open the file " & filename)
  10. var x: XmlParser
  11. open(x, s, filename)
  12. while true:
  13. x.next()
  14. case x.kind
  15. of xmlElementStart:
  16. if cmpIgnoreCase(x.elementName, "title") == 0:
  17. var title = ""
  18. x.next() # skip "<title>"
  19. while x.kind == xmlCharData:
  20. title.add(x.charData)
  21. x.next()
  22. if x.kind == xmlElementEnd and cmpIgnoreCase(x.elementName, "title") == 0:
  23. echo("Title: " & title)
  24. quit(0) # Success!
  25. else:
  26. echo(x.errorMsgExpected("/title"))
  27. of xmlEof: break # end of file reached
  28. else: discard # ignore other events
  29. x.close()
  30. quit("Could not determine title!")

Example 2: Retrieve all HTML links

The file examples/htmlrefs.nim demonstrates how to use the XML parser to accomplish another simple task: To determine all the links an HTML document contains.

  1. # Example program to show the new parsexml module
  2. # This program reads an HTML file and writes all its used links to stdout.
  3. # Errors and whitespace are ignored.
  4. import os, streams, parsexml, strutils
  5. proc `=?=` (a, b: string): bool =
  6. # little trick: define our own comparator that ignores case
  7. return cmpIgnoreCase(a, b) == 0
  8. if paramCount() < 1:
  9. quit("Usage: htmlrefs filename[.html]")
  10. var links = 0 # count the number of links
  11. var filename = addFileExt(paramStr(1), "html")
  12. var s = newFileStream(filename, fmRead)
  13. if s == nil: quit("cannot open the file " & filename)
  14. var x: XmlParser
  15. open(x, s, filename)
  16. next(x) # get first event
  17. block mainLoop:
  18. while true:
  19. case x.kind
  20. of xmlElementOpen:
  21. # the <a href = "xyz"> tag we are interested in always has an attribute,
  22. # thus we search for ``xmlElementOpen`` and not for ``xmlElementStart``
  23. if x.elementName =?= "a":
  24. x.next()
  25. if x.kind == xmlAttribute:
  26. if x.attrKey =?= "href":
  27. var link = x.attrValue
  28. inc(links)
  29. # skip until we have an ``xmlElementClose`` event
  30. while true:
  31. x.next()
  32. case x.kind
  33. of xmlEof: break mainLoop
  34. of xmlElementClose: break
  35. else: discard
  36. x.next() # skip ``xmlElementClose``
  37. # now we have the description for the ``a`` element
  38. var desc = ""
  39. while x.kind == xmlCharData:
  40. desc.add(x.charData)
  41. x.next()
  42. echo(desc & ": " & link)
  43. else:
  44. x.next()
  45. of xmlEof: break # end of file reached
  46. of xmlError:
  47. echo(errorMsg(x))
  48. x.next()
  49. else: x.next() # skip other events
  50. echo($links & " link(s) found!")
  51. x.close()

Imports

strutils, lexbase, streams, unicode, os

Types

  1. XmlErrorKind = enum
  2. errNone, ## no error
  3. errEndOfCDataExpected, ## ``]]>`` expected
  4. errNameExpected, ## name expected
  5. errSemicolonExpected, ## ``;`` expected
  6. errQmGtExpected, ## ``?>`` expected
  7. errGtExpected, ## ``>`` expected
  8. errEqExpected, ## ``=`` expected
  9. errQuoteExpected, ## ``"`` or ``'`` expected
  10. errEndOfCommentExpected, ## ``-->`` expected
  11. errAttributeValueExpected ## non-empty attribute value expected

enumeration that lists all errors that can occur Source Edit

  1. XmlEventKind = enum
  2. xmlError, ## an error occurred during parsing
  3. xmlEof, ## end of file reached
  4. xmlCharData, ## character data
  5. xmlWhitespace, ## whitespace has been parsed
  6. xmlComment, ## a comment has been parsed
  7. xmlPI, ## processing instruction (``<?name something ?>``)
  8. xmlElementStart, ## ``<elem>``
  9. xmlElementEnd, ## ``</elem>``
  10. xmlElementOpen, ## ``<elem
  11. xmlAttribute, ## ``key = "value"`` pair
  12. xmlElementClose, ## ``>``
  13. xmlCData, ## ``<![CDATA[`` ... data ... ``]]>``
  14. xmlEntity, ## &entity;
  15. xmlSpecial ## ``<! ... data ... >``

enumeration of all events that may occur when parsing Source Edit

  1. XmlParseOption = enum
  2. reportWhitespace, ## report whitespace
  3. reportComments, ## report comments
  4. allowUnquotedAttribs, ## allow unquoted attribute values (for HTML)
  5. allowEmptyAttribs ## allow empty attributes (without explicit value)

options for the XML parser Source Edit

  1. XmlParser = object of BaseLexer

the parser object. Source Edit

Procs

  1. proc close(my: var XmlParser) {.inline, ...raises: [IOError, OSError],
  2. tags: [WriteIOEffect], forbids: [].}

closes the parser my and its associated input stream. Source Edit

  1. proc errorMsg(my: XmlParser): string {....raises: [ValueError], tags: [],
  2. forbids: [].}

returns a helpful error message for the event xmlError Source Edit

  1. proc errorMsg(my: XmlParser; msg: string): string {....raises: [ValueError],
  2. tags: [], forbids: [].}

returns an error message with text msg in the same format as the other error messages Source Edit

  1. proc errorMsgExpected(my: XmlParser; tag: string): string {.
  2. ...raises: [ValueError], tags: [], forbids: [].}

returns an error message “<tag> expected” in the same format as the other error messages Source Edit

  1. proc getColumn(my: XmlParser): int {.inline, ...raises: [], tags: [], forbids: [].}

get the current column the parser has arrived at. Source Edit

  1. proc getFilename(my: XmlParser): string {.inline, ...raises: [], tags: [],
  2. forbids: [].}

get the filename of the file that the parser processes. Source Edit

  1. proc getLine(my: XmlParser): int {.inline, ...raises: [], tags: [], forbids: [].}

get the current line the parser has arrived at. Source Edit

  1. proc kind(my: XmlParser): XmlEventKind {.inline, ...raises: [], tags: [],
  2. forbids: [].}

returns the current event type for the XML parser Source Edit

  1. proc next(my: var XmlParser) {....raises: [IOError, OSError], tags: [ReadIOEffect],
  2. forbids: [].}

retrieves the first/next event. This controls the parser. Source Edit

  1. proc open(my: var XmlParser; input: Stream; filename: string;
  2. options: set[XmlParseOption] = {}) {....raises: [IOError, OSError],
  3. tags: [ReadIOEffect], forbids: [].}

initializes the parser with an input stream. Filename is only used for nice error messages. The parser’s behaviour can be controlled by the options parameter: If options contains reportWhitespace a whitespace token is reported as an xmlWhitespace event. If options contains reportComments a comment token is reported as an xmlComment event. Source Edit

  1. proc rawData(my: var XmlParser): lent string {.inline, ...raises: [], tags: [],
  2. forbids: [].}

returns the underlying ‘data’ string by reference. This is only used for speed hacks. Source Edit

  1. proc rawData2(my: var XmlParser): lent string {.inline, ...raises: [], tags: [],
  2. forbids: [].}

returns the underlying second ‘data’ string by reference. This is only used for speed hacks. Source Edit

Templates

  1. template attrKey(my: XmlParser): string

returns the attribute key for the event xmlAttribute Raises an assertion in debug mode if my.kind is not xmlAttribute. In release mode, this will not trigger an error but the value returned will not be valid. Source Edit

  1. template attrValue(my: XmlParser): string

returns the attribute value for the event xmlAttribute Raises an assertion in debug mode if my.kind is not xmlAttribute. In release mode, this will not trigger an error but the value returned will not be valid. Source Edit

  1. template charData(my: XmlParser): string

returns the character data for the events: xmlCharData, xmlWhitespace, xmlComment, xmlCData, xmlSpecial Raises an assertion in debug mode if my.kind is not one of those events. In release mode, this will not trigger an error but the value returned will not be valid. Source Edit

  1. template elementName(my: XmlParser): string

returns the element name for the events: xmlElementStart, xmlElementEnd, xmlElementOpen Raises an assertion in debug mode if my.kind is not one of those events. In release mode, this will not trigger an error but the value returned will not be valid. Source Edit

  1. template entityName(my: XmlParser): string

returns the entity name for the event: xmlEntity Raises an assertion in debug mode if my.kind is not xmlEntity. In release mode, this will not trigger an error but the value returned will not be valid. Source Edit

  1. template piName(my: XmlParser): string

returns the processing instruction name for the event xmlPI Raises an assertion in debug mode if my.kind is not xmlPI. In release mode, this will not trigger an error but the value returned will not be valid. Source Edit

  1. template piRest(my: XmlParser): string

returns the rest of the processing instruction for the event xmlPI Raises an assertion in debug mode if my.kind is not xmlPI. In release mode, this will not trigger an error but the value returned will not be valid. Source Edit