Skip to content

Commit 953919b

Browse files
author
Steve Canny
committed
oxml: add CT_Body.clear_content()
1 parent c293458 commit 953919b

2 files changed

Lines changed: 27 additions & 0 deletions

File tree

docx/oxml/parts.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,16 @@ def add_p(self):
3838
self.append(p)
3939
return p
4040

41+
def clear_content(self):
42+
"""
43+
Remove all content child elements from this <w:body> element. Leave
44+
the <w:sectPr> element if it is present.
45+
"""
46+
children = self.getchildren()
47+
content_elms = children[:-1] if self._has_sectPr else children
48+
for content_elm in content_elms:
49+
self.remove(content_elm)
50+
4151
@property
4252
def _has_sectPr(self):
4353
"""

tests/oxml/test_parts.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,23 @@ def it_can_add_a_p_to_itself(self):
3434
assert body.xml == after_body_bldr.xml
3535
assert isinstance(p, CT_P)
3636

37+
def it_can_clear_all_the_content_it_holds(self):
38+
"""
39+
Remove all content child elements from this <w:body> element.
40+
"""
41+
cases = (
42+
(a_body(), a_body()),
43+
(a_body().with_p(), a_body()),
44+
(a_body().with_sectPr(), a_body().with_sectPr()),
45+
(a_body().with_p().with_sectPr(), a_body().with_sectPr()),
46+
)
47+
for before_body_bldr, after_body_bldr in cases:
48+
body = before_body_bldr.element
49+
# exercise -----------------
50+
body.clear_content()
51+
# verify -------------------
52+
assert body.xml == after_body_bldr.xml
53+
3754

3855
class DescribeCT_Document(object):
3956

0 commit comments

Comments
 (0)