Fix #338: re.sub() flag argument at wrong position.
[docutils.git] / sandbox / docbook / scripts / xsl_process.py
blob8c9ecc90e27eb51a1028aa0359aefd465574ca5c
1 from lxml import etree
2 import lxml
3 import os, sys, logging
5 def report_xsl_error(transform_error_obj):
6 for error_obj in transform_error_obj:
7 sys.stderr.write(error_obj.message)
8 sys.stderr.write('\n')
9 if error_obj.line != 0 and error_obj.column != 0:
10 sys.stderr.write(str(error_obj.line))
11 sys.stderr.write(str(error_obj.column))
13 def transform_lxml(xslt_file, xml_file, param_dict = {}):
14 # have to put quotes around string params
15 temp = {}
16 the_keys = param_dict.keys()
17 for the_key in the_keys:
18 if len(the_key) > 0:
19 if the_key[0] == '"' and the_key[-1] == '"':
20 temp[the_key] = param_dict[the_key]
21 elif the_key[0] == "'" and the_key[-1] == "'":
22 temp[the_key] = param_dict[the_key]
23 else:
24 temp[the_key] = "'{0}'".format(param_dict[the_key])
25 param_dict = {}
26 param_dict.update(temp)
28 try:
29 xslt_doc = etree.parse(xslt_file)
30 except lxml.etree.XMLSyntaxError as error:
31 sys.stderr.write(str(error))
32 return 1, None
33 try:
34 transform = etree.XSLT(xslt_doc)
35 except lxml.etree.XSLTParseError as error:
36 sys.stderr.write(str(error) + '\n')
37 return 1, None
39 if not isinstance(xml_file, lxml.etree._XSLTResultTree):
40 try:
41 indoc = etree.parse(xml_file)
42 except lxml.etree.XMLSyntaxError as msg:
43 sys.stderr.write('Invalid XML\n')
44 sys.stderr.write(str(msg))
45 sys.stderr.write('\n')
46 return 1, None
47 else:
48 indoc = xml_file
49 try:
50 outdoc = transform(indoc, **param_dict)
51 except lxml.etree.XSLTApplyError as error:
52 msg = 'error converting %s to %s with %s:\n' % (xml_file, out_file, xslt_file)
53 msg += str(error)
54 msg += '\n'
55 report_xsl_error(transform.error_log)
56 return 1, None, None
57 report_xsl_error(transform.error_log)
58 return 0, outdoc
59 if __name__ == '__main__':
60 error, doc_obj = transform_lxml(xslt_file = sys.argv[1], xml_file= sys.argv[2])
61 if not error:
62 doc_obj.write('foo', encoding='utf8')