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