xslt.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #!/usr/bin/python -u
  2. # $Id: xslt.py 8353 2009-03-17 16:57:50Z mzjn $
  3. import sys
  4. import libxml2
  5. import libxslt
  6. from docbook import adjustColumnWidths
  7. # Check the arguments
  8. usage = "Usage: %s xmlfile.xml xslfile.xsl [outputfile] [param1=val [param2=val]...]" % sys.argv[0]
  9. xmlfile = None
  10. xslfile = None
  11. outfile = "-"
  12. params = {}
  13. try:
  14. xmlfile = sys.argv[1]
  15. xslfile = sys.argv[2]
  16. except IndexError:
  17. print usage
  18. sys.exit(1)
  19. def quote(astring):
  20. if astring.find("'") < 0:
  21. return "'" + astring + "'"
  22. else:
  23. return '"' + astring + '"'
  24. try:
  25. outfile = sys.argv[3]
  26. if outfile.find("=") > 0:
  27. name, value = outfile.split("=", 2)
  28. params[name] = quote(value)
  29. outfile = None
  30. count = 4
  31. while (sys.argv[count]):
  32. try:
  33. name, value = sys.argv[count].split("=", 2)
  34. if params.has_key(name):
  35. print "Warning: '%s' re-specified; replacing value" % name
  36. params[name] = quote(value)
  37. except ValueError:
  38. print "Invalid parameter specification: '" + sys.argv[count] + "'"
  39. print usage
  40. sys.exit(1)
  41. count = count+1
  42. except IndexError:
  43. pass
  44. # ======================================================================
  45. # Memory debug specific
  46. # libxml2.debugMemory(1)
  47. # Setup environment
  48. libxml2.lineNumbersDefault(1)
  49. libxml2.substituteEntitiesDefault(1)
  50. libxslt.registerExtModuleFunction("adjustColumnWidths",
  51. "http://nwalsh.com/xslt/ext/xsltproc/python/Table",
  52. adjustColumnWidths)
  53. # Initialize and run
  54. styledoc = libxml2.parseFile(xslfile)
  55. style = libxslt.parseStylesheetDoc(styledoc)
  56. doc = libxml2.parseFile(xmlfile)
  57. result = style.applyStylesheet(doc, params)
  58. # Save the result
  59. if outfile:
  60. style.saveResultToFilename(outfile, result, 0)
  61. else:
  62. print result
  63. # Free things up
  64. style.freeStylesheet()
  65. doc.freeDoc()
  66. result.freeDoc()
  67. # Memory debug specific
  68. #libxslt.cleanup()
  69. #if libxml2.debugMemory(1) != 0:
  70. # print "Memory leak %d bytes" % (libxml2.debugMemory(1))
  71. # libxml2.dumpMemory()