Sunday, 10 August 2014

Python: Unzip the file, apply modifications on the containing files and zip the file again



I have to write a filter for files in a zipped file. So I have the zip file as an input, it contains some xml kind of files. I filter the xml with xslt. So the files will be overwritten and finally zip the file again. My code looks like the following:


Problem: Terminates without exceptions but It does not work.



from lxml import etree
from io import StringIO
import zipfile

def axlFilter(inputfile):

with zipfile.ZipFile(inputfile) as zip_file:
for file in zip_file.namelist():
try:

xslt_root = etree.XML('''\
<xsl:stylesheet version="1.0"
xmlns:xsl="http://ift.tt/tCZ8VR">

<xsl:template match="node() | @*">
<xsl:copy>
<xsl:apply-templates select="node() | @*"/>
</xsl:copy>
</xsl:template>


<xsl:template match="TimeStamp"/>
<xsl:template match="@timeStamp"/>
<xsl:template match="TimeStamps"/>
<xsl:template match="Signature"/>

</xsl:stylesheet>
''')

transform = etree.XSLT(xslt_root)

doc = etree.parse(file)
result_tree = transform(doc)

resultfile = StringIO(unicode(str(result_tree)))
zipwrite.write_file(file, resultfile)


finally:
zip_file.close()

No comments:

Post a Comment