jdum / odfdo

python library for OpenDocument format (ODF)
Apache License 2.0
58 stars 11 forks source link

Deleting content from one point to another in a odt document #49

Closed mlwesoly closed 2 months ago

mlwesoly commented 2 months ago

Hello, how is the best way to delete a part from the document. For example i want to delete all the text (paragraphs) from a chapter 5 until the end of the document (or maybe just one chapter). How would i do this? Sorry that I don't even have a beginning idea, but I'm really clueless in this one. Thank you already for your help!

i'm using already for something else: get_styled_elements("xyz") and the .delete() those. But this seems like a hassle for a whole chapter for example...

jdum commented 2 months ago

Hi, you can iterate over the elements of the document's body, but of course not delete some of them while iterating on their list.
So I would reconstruct the body from scratch, keeping wanted elements.

pseudo code:

keep_list = []
for elem in document.body.children:
    if element_to_keep:
        keep_list.append(elem)
document.body.clear()
document.body.extend(keep_list)
mlwesoly commented 2 months ago

Ohh thank you so much! That I can traverse with .childern all the underlying elements did the trick. That is amazing. And also I was searching for some method like remove, but didn't thought about clear & delete.