htmltitle.nim 1002 B

12345678910111213141516171819202122232425262728293031323334353637
  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!")