Pythonizer
Pythonizer

Reputation: 1194

Modifie the xml data in python

I'm trying to edit an attribute of an pptx xml file to add a slide between slides, I know there is a module called python-pptx but it's not able to do that.

So everything starts from a file "[Content_Types].xml" and the first thing i have to do is to put a string <Override ContentType="application/vnd.openxmlformats-officedocument.presentationml.slide+xml" PartName="/ppt/slides/slide4.xml"/> between the after /ppt/slides/slide3.xml and then increment the number of other slides by 1

full xml looks like this

<?xml version="1.0" encoding="UTF-8" standalone="true"?>
-<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
<Override ContentType="application/vnd.openxmlformats-officedocument.presentationml.slide+xml" PartName="/ppt/slides/slide1.xml"/>
<Override ContentType="application/vnd.openxmlformats-officedocument.presentationml.slide+xml" PartName="/ppt/slides/slide2.xml"/>
<Override ContentType="application/vnd.openxmlformats-officedocument.presentationml.slide+xml" PartName="/ppt/slides/slide3.xml"/>
<Override ContentType="application/vnd.openxmlformats-officedocument.presentationml.slide+xml" PartName="/ppt/slides/slide4.xml"/>
<Override ContentType="application/vnd.openxmlformats-officedocument.presentationml.slide+xml" PartName="/ppt/slides/slide5.xml"/>
<Override ContentType="application/vnd.openxmlformats-officedocument.presentationml.slide+xml" PartName="/ppt/slides/slide6.xml"/>
</Types>

Any suggestions about how to do that?

Upvotes: 3

Views: 566

Answers (1)

PYPL
PYPL

Reputation: 1849

You dont need to use an xml parser for that, just read out the data from a file and insert your line in which position you want, for your case it will be OK to add the data in the end of the file without inserting it in the middle and shifting by 1, because your xml doesn't have subtrees, anyway, the resault will be the same

with open('[Content_Type].xml', 'r') as fl:
    readout = fl.read()
spl = readout.split('><')
spl.insert(len(spl)-1, """Override ContentType="application/vnd.openxmlformats-officedocument.presentationml.slide+xml" PartName="/ppt/slides/slide%d.xml"/""" %(slides+1))
final = '><'.join(spl)
with open('[Content_Type].xml', 'w') as fl:
    fl.write(final)

Upvotes: 1

Related Questions