Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 683
Pythonizer Avatar asked Aug 13 '26 03:08

Pythonizer


1 Answers

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)
like image 66
PYPL Avatar answered Aug 14 '26 17:08

PYPL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!