Fixed bug chopping off newline when outputing to a file.
[docutils/kirr.git] / sandbox / xml2rst / rst / rst_xslt.py
blob26ff199e057697a495bcfa62ae8adb7a0b17ec8f
1 ###############################################################################
2 ###############################################################################
3 # Import
5 import os.path
6 import sys
8 try:
9 from lxml import etree
10 except ImportError:
11 raise Exception("""
12 Python package 'lxml' is not available.
13 You may try to use 'xml2rst.xsl' with a standalone XSLT processor like 'xalan' or 'xsltproc'""")
15 ###############################################################################
16 ###############################################################################
17 # Constants
19 """
20 @var MainXsltNm: Name of the main XSLT source file
21 @type MainXsltNm: str
22 """
23 MainXsltNm = "xml2rst.xsl"
25 ###############################################################################
26 ###############################################################################
27 # Specialized functions
29 def convert(inNm, outNm, settings):
30 """
31 Do the conversion.
33 @param inNm: Filename of input file.
34 @type inNm: str
36 @param outNm: Filename of output file or None.
37 @type outNm: str | None
38 """
39 try:
40 inF = open(inNm)
41 except IOError, e:
42 raise Exception("Can't open input file %r: %s" % ( inNm, e, ))
44 modP = os.path.dirname(__file__)
45 mainXsltNm = os.path.join(modP, MainXsltNm)
46 try:
47 mainXsltF = open(mainXsltNm)
48 except IOError, e:
49 raise Exception("Can't open main XSLT file %r: %s" % ( mainXsltNm, e, ))
51 xsltParser = etree.XMLParser()
52 mainXsltDoc = etree.parse(mainXsltF, xsltParser)
53 mainXsltF.close()
54 mainXslt = etree.XSLT(mainXsltDoc)
56 inParser = etree.XMLParser()
57 try:
58 inDoc = etree.parse(inF, inParser)
59 except Exception, e:
60 raise Exception("Error parsing input file %r: %s" % ( inNm, e, ))
61 inF.close()
63 xsltParams = { }
64 if settings.fold is not None:
65 xsltParams['fold'] = str(settings.fold)
66 if settings.adornment is not None:
67 xsltParams['adornment'] = "'" + settings.adornment + "'"
68 try:
69 result = mainXslt(inDoc, **xsltParams)
70 except Exception, e:
71 raise Exception("Error transforming input file %r: %s" % ( inNm, e, ))
72 outS = str(result)
73 if outNm:
74 try:
75 outF = open(outNm, "w")
76 except IOError, e:
77 raise Exception("Can't open output file %r: %s" % ( outNm, e, ))
78 outF.write(outS)
79 outF.close()
80 else:
81 sys.stdout.write(outS)