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
)
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
16 the_keys
= param_dict
.keys()
17 for the_key
in the_keys
:
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
]
24 temp
[the_key
] = "'{0}'".format(param_dict
[the_key
])
26 param_dict
.update(temp
)
29 xslt_doc
= etree
.parse(xslt_file
)
30 except lxml
.etree
.XMLSyntaxError
as error
:
31 sys
.stderr
.write(str(error
))
34 transform
= etree
.XSLT(xslt_doc
)
35 except lxml
.etree
.XSLTParseError
as error
:
36 sys
.stderr
.write(str(error
) + '\n')
39 if not isinstance(xml_file
, lxml
.etree
._XSLTResultTree
):
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')
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
)
55 report_xsl_error(transform
.error_log
)
57 report_xsl_error(transform
.error_log
)
59 if __name__
== '__main__':
60 error
, doc_obj
= transform_lxml(xslt_file
= sys
.argv
[1], xml_file
= sys
.argv
[2])
62 doc_obj
.write('foo', encoding
='utf8')