Skip to content

Element

Element, base class of all ODF classes.

Classes:

Name Description
EText

Representation of an XML text node (internal).

Element

Base class for all ODF elements, providing an abstraction of the underlying XML structure.

PropDef

Named tuple for class properties (internal).

PropDefBool

Named tuple for boolean class properties (internal).

Functions:

Name Description
class_from_tag

Retrieves the Python class associated with a given ODF qualified tag

register_element_class

(internal function) Associate a qualified element name to a Python class

register_element_class_list

(internal function) Associate a qualified element name to a Python class

xpath_compile

Compile an XPath query string into an lxml.etree.XPath object.

xpath_return_elements

Execute a compiled XPath query and return a list of matching lxml elements.

xpath_return_strings

Execute a compiled XPath query and return a list of matching strings.

Attributes:

Name Type Description
FIRST_CHILD
LAST_CHILD
NAMESPACES_XML
NEXT_SIBLING
ODF_NAMESPACES
PREV_SIBLING
STOPMARKER

FIRST_CHILD module-attribute

FIRST_CHILD = 0

LAST_CHILD module-attribute

LAST_CHILD = 1

NAMESPACES_XML module-attribute

NAMESPACES_XML = (
    OFFICE_PREFIX + encode() + b"%s</office:document>"
)

NEXT_SIBLING module-attribute

NEXT_SIBLING = 2

ODF_NAMESPACES module-attribute

ODF_NAMESPACES = _generate_odf_namespaces()

PREV_SIBLING module-attribute

PREV_SIBLING = 3

STOPMARKER module-attribute

STOPMARKER = 5

_ODF_NAMESPACES_CORE module-attribute

_ODF_NAMESPACES_CORE = {
    "anim": "urn:oasis:names:tc:opendocument:xmlns:animation:1.0",
    "chart": "urn:oasis:names:tc:opendocument:xmlns:chart:1.0",
    "config": "urn:oasis:names:tc:opendocument:xmlns:config:1.0",
    "dc": "http://purl.org/dc/elements/1.1/",
    "dom": "http://www.w3.org/2001/xml-events",
    "dr3d": "urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0",
    "draw": "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0",
    "fo": "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0",
    "form": "urn:oasis:names:tc:opendocument:xmlns:form:1.0",
    "grddl": "http://www.w3.org/2003/g/data-view#",
    "manifest": "urn:oasis:names:tc:opendocument:xmlns:manifest:1.0",
    "math": "http://www.w3.org/1998/Math/MathML",
    "meta": "urn:oasis:names:tc:opendocument:xmlns:meta:1.0",
    "number": "urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0",
    "of": "urn:oasis:names:tc:opendocument:xmlns:of:1.2",
    "office": "urn:oasis:names:tc:opendocument:xmlns:office:1.0",
    "pkg": "http://docs.oasis-open.org/ns/office/1.2/meta/pkg#",
    "presentation": "urn:oasis:names:tc:opendocument:xmlns:presentation:1.0",
    "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
    "rdfa": "http://docs.oasis-open.org/opendocument/meta/rdfa#",
    "dsig": "urn:oasis:names:tc:opendocument:xmlns:digitalsignature:1.0",
    "script": "urn:oasis:names:tc:opendocument:xmlns:script:1.0",
    "smil": "urn:oasis:names:tc:opendocument:xmlns:smil-compatible:1.0",
    "style": "urn:oasis:names:tc:opendocument:xmlns:style:1.0",
    "svg": "urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0",
    "table": "urn:oasis:names:tc:opendocument:xmlns:table:1.0",
    "text": "urn:oasis:names:tc:opendocument:xmlns:text:1.0",
    "xforms": "http://www.w3.org/2002/xforms",
    "xhtml": "http://www.w3.org/1999/xhtml",
    "xlink": "http://www.w3.org/1999/xlink",
    "xml": "http://www.w3.org/XML/1998/namespace",
    "xsd": "http://www.w3.org/2001/XMLSchema",
    "xsi": "http://www.w3.org/2001/XMLSchema-instance",
}

_ODF_NAMESPACES_EXTENSIONS module-attribute

_ODF_NAMESPACES_EXTENSIONS = {
    "calcext": "urn:org:documentfoundation:names:experimental:calc:xmlns:calcext:1.0",
    "chartooo": "http://openoffice.org/2010/chart",
    "css3t": "http://www.w3.org/TR/css3-text/",
    "drawooo": "http://openoffice.org/2010/draw",
    "field": "urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0",
    "formooo": "http://openoffice.org/2011/form",
    "formx": "urn:openoffice:names:experimental:ooxml-odf-interop:xmlns:form:1.0",
    "loext": "urn:org:documentfoundation:names:experimental:office:xmlns:loext:1.0",
    "officeooo": "http://openoffice.org/2009/office",
    "ooo": "http://openoffice.org/2004/office",
    "oooc": "http://openoffice.org/2004/calc",
    "ooow": "http://openoffice.org/2004/writer",
    "presentationooo": "http://openoffice.org/2012/presentation",
    "rpt": "http://openoffice.org/2005/report",
    "tableooo": "http://openoffice.org/2009/table",
}

_class_registry module-attribute

_class_registry: dict[str, type[Element]] = {}

_re_anyspace module-attribute

_re_anyspace = compile(' +')

_tag_class_registry module-attribute

_tag_class_registry: dict[str, type[Element]] = {}

_xpath_text_descendant_no_annotation module-attribute

_xpath_text_descendant_no_annotation = xpath_compile(
    "descendant::text()[not (parent::office:annotation)]"
)

EText

Bases: str

Representation of an XML text node (internal).

Created to hide the specifics of lxml in searching text nodes using XPath.

Constructed like any str object but only accepts lxml text objects.

Methods:

Name Description
__init__

Initialize EText instance.

is_tail

Check if this text node represents the ‘tail’ part of its parent.

is_text

Check if this text node represents the ‘text’ part of its parent.

Attributes:

Name Type Description
parent Element | None

Return the parent element of this text node.

Source code in odfdo/element.py
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
class EText(str):
    """Representation of an XML text node (internal).

    Created to hide the specifics of lxml in searching text nodes using XPath.

    Constructed like any str object but only accepts lxml text objects.
    """

    # There's some black magic in inheriting from str
    def __init__(
        self,
        text_result: _Element,
    ) -> None:
        """Initialize EText instance.

        Args:
            text_result: The lxml element representing the text node.
        """
        self.__parent = text_result.getparent()
        self.__is_text: bool = bool(text_result.is_text)
        self.__is_tail: bool = bool(text_result.is_tail)

    @property
    def parent(self) -> Element | None:
        """Return the parent element of this text node.

        Returns:
            Element | None: The parent Element or None if it's a root text node.
        """
        parent = self.__parent
        # XXX happens just because of the unit test
        if parent is None:
            return None
        return Element.from_tag(tag_or_elem=parent)

    def is_text(self) -> bool:
        """Check if this text node represents the 'text' part of its parent.

        Returns:
            bool: True if it's the text part, False otherwise.
        """
        return self.__is_text

    def is_tail(self) -> bool:
        """Check if this text node represents the 'tail' part of its parent.

        Returns:
            bool: True if it's the tail part, False otherwise.
        """
        return self.__is_tail

__is_tail instance-attribute

__is_tail: bool = bool(is_tail)

__is_text instance-attribute

__is_text: bool = bool(is_text)

__parent instance-attribute

__parent = getparent()

parent property

parent: Element | None

Return the parent element of this text node.

Returns:

Type Description
Element | None

Element | None: The parent Element or None if it’s a root text node.

__init__

__init__(text_result: _Element) -> None

Initialize EText instance.

Parameters:

Name Type Description Default
text_result _Element

The lxml element representing the text node.

required
Source code in odfdo/element.py
438
439
440
441
442
443
444
445
446
447
448
449
def __init__(
    self,
    text_result: _Element,
) -> None:
    """Initialize EText instance.

    Args:
        text_result: The lxml element representing the text node.
    """
    self.__parent = text_result.getparent()
    self.__is_text: bool = bool(text_result.is_text)
    self.__is_tail: bool = bool(text_result.is_tail)

is_tail

is_tail() -> bool

Check if this text node represents the ‘tail’ part of its parent.

Returns:

Name Type Description
bool bool

True if it’s the tail part, False otherwise.

Source code in odfdo/element.py
472
473
474
475
476
477
478
def is_tail(self) -> bool:
    """Check if this text node represents the 'tail' part of its parent.

    Returns:
        bool: True if it's the tail part, False otherwise.
    """
    return self.__is_tail

is_text

is_text() -> bool

Check if this text node represents the ‘text’ part of its parent.

Returns:

Name Type Description
bool bool

True if it’s the text part, False otherwise.

Source code in odfdo/element.py
464
465
466
467
468
469
470
def is_text(self) -> bool:
    """Check if this text node represents the 'text' part of its parent.

    Returns:
        bool: True if it's the text part, False otherwise.
    """
    return self.__is_text

Element

Bases: MDBase

Base class for all ODF elements, providing an abstraction of the underlying XML structure.

This class handles the creation, manipulation, and serialization of ODF elements, acting as a wrapper around lxml.etree._Element objects.

Methods:

Name Description
__init__

Initialize an Element instance.

__repr__
__str__
clear

Removes all text content, child elements, and attributes from the element.

del_attribute

Deletes a specified attribute from the element.

del_attribute_list

Deletes a list of attributes from the element if present.

delete

Deletes an element from the XML tree.

elements_repeated_sequence

Extracts repeated sequence information from elements for table handling.

extend

Appends multiple ODF elements efficiently to the end of the current element.

from_tag

Factory method to create an Element instance (or a subclass) from an XML tag.

from_tag_for_clone

Factory method used internally for cloning elements.

get_attribute

Returns the value of a specified attribute.

get_attribute_integer

Returns the value of a specified attribute as an integer.

get_attribute_number

Returns the value of a specified attribute as a number (Decimal or int).

get_attribute_string

Returns the value of a specified attribute as a string.

get_changes_ids

Returns a list of IDs that refer to change regions in the tracked changes list.

get_draw_connector

Returns a single draw connector that matches the specified criteria.

get_draw_connectors

Returns all draw connectors that match the specified criteria.

get_draw_ellipse

Returns a single draw ellipse that matches the specified criteria.

get_draw_ellipses

Returns all draw ellipses that match the specified criteria.

get_draw_group

Returns a single draw group that matches the specified criteria.

get_draw_groups

Returns all draw groups that match the specified criteria.

get_draw_line

Returns a single draw line that matches the specified criteria.

get_draw_lines

Returns all draw lines that match the specified criteria.

get_draw_page

Returns a single draw page that matches the specified criteria.

get_draw_pages

Returns all draw pages that match the specified criteria.

get_draw_rectangle

Returns a single draw rectangle that matches the specified criteria.

get_draw_rectangles

Returns all draw rectangles that match the specified criteria.

get_element

Returns the first element obtained by applying an XPath query.

get_elements

Returns a list of elements obtained by applying an XPath query.

get_formatted_text

Returns a formatted version of the element’s text.

get_frame

Returns a single frame that matches the specified criteria.

get_frames

Returns all frames that match the specified criteria.

get_header

Returns a single header that matches the specified criteria.

get_headers

Returns all headers that match the specified criteria.

get_image

Returns a single image that matches the specified criteria.

get_images

Returns all images that match the specified criteria.

get_office_names

Returns all unique values of ‘office:name’ attributes within the element’s subtree.

get_orphan_draw_connectors

Returns a list of connectors that are not connected to any shapes.

get_paragraph

Returns a single paragraph that matches the specified criteria.

get_paragraphs

Returns all paragraphs that match the specified criteria.

get_span

Returns a single span that matches the specified criteria.

get_spans

Returns all spans that match the specified criteria.

get_style

Returns a single style uniquely identified by family/name, or a

get_styled_elements

Finds elements (paragraphs, tables, etc.) using a given style name.

get_styles

Returns all styles (common and default) that match the specified family.

get_text_change

Returns a single text change that matches the specified criteria.

get_text_change_deletion

Returns a single text change of deletion kind (text:change tag) matching criteria.

get_text_change_deletions

Returns all text changes representing deletions (text:change tags).

get_text_change_end

Returns a single text change-end element (text:change-end tag) matching criteria.

get_text_change_ends

Returns all text change-end elements (text:change-end tags).

get_text_change_start

Returns a single text change-start element (text:change-start tag) matching criteria.

get_text_change_starts

Returns all text change-start elements (text:change-start tags).

get_text_changes

Returns all text changes, including single deletions (text:change) and

get_variable_set

Returns a single variable set that matches the specified criteria.

get_variable_set_value

Returns the value of the last variable set for the given name.

get_variable_sets

Returns all variable sets that match the specified criteria.

index

Returns the position of a child element within this element.

insert

Inserts an element relative to the current element.

is_empty

Checks if the element is empty (no text, no children, no tail).

match

Checks if a pattern is found one or more times within the element’s text content.

replace

Replaces occurrences of a pattern with new text within the element’s content.

replace_element

Replaces an existing sub-element with a new one in place.

search

Returns the first position of a pattern in the element’s text content.

search_all

Returns all start and end positions of a regex pattern in the element’s text content.

search_first

Returns the start and end positions of the first occurrence of a regex pattern.

serialize

Returns the text serialization of the XML element.

set_attribute

Sets the value of a specified attribute.

set_style_attribute

Sets a style-related attribute, allowing a Style object as a value.

text_at

Returns the recursive text content of the element between specified positions.

xpath

Applies an XPath query to the element and its subtree.

Attributes:

Name Type Description
append
attributes dict[str, str]

Gets all attributes of the element as a dictionary.

children list[Element]

Returns a list of immediate child elements.

clone Element

Creates a deep copy of the current element.

document_body Body | None

Returns the first child of the document body, if any.

frames list[Frame]

Returns all frames as a list.

headers list[Header]

Returns all headers as a list.

images list[DrawImage]

Returns all images as a list.

inner_text str

Returns the concatenated text content of the element and its children (excluding its own tail).

is_bound bool

Checks if the element is currently part of an XML tree (has a parent).

paragraphs list[Paragraph]

Returns all paragraphs as a list.

parent Element | None

Returns the parent element of this element.

root Element

Returns the root element of the XML tree containing this element.

spans list[Span]

Returns all spans as a list.

tag str

Gets the underlying XML tag with the qualified name.

tail str | None

Gets the text immediately following the element.

text str

Gets the text content of the element.

text_changes list[TextChange | TextChangeStart]

Returns all text changes, including single deletions (text:change) and

text_content str

Gets the text content of embedded paragraphs, including annotations and cells.

text_recursive str

Returns the full recursive text content of the element, including its own tail.

Source code in odfdo/element.py
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
class Element(MDBase):
    """Base class for all ODF elements, providing an abstraction of the underlying XML structure.

    This class handles the creation, manipulation, and serialization of ODF elements,
    acting as a wrapper around `lxml.etree._Element` objects.
    """

    _tag: str = ""
    _properties: tuple[PropDef | PropDefBool, ...] = ()

    def __init__(self, **kwargs: Any) -> None:
        """Initialize an Element instance.

        This constructor can be used to create a new ODF element from scratch
        or to wrap an existing `lxml.etree._Element` object.

        Args:
            **kwargs (Any):
                - tag_or_elem (str | lxml.etree._Element, optional): An existing
                  lxml element to wrap, or an ODF tag string (e.g., "text:p")
                  to create a new element. If not provided, a new element is
                  created based on the class's `_tag` attribute.
                - tag (str, optional): The ODF tag string to use when creating a
                  new element, if `tag_or_elem` is not provided. Defaults to
                  `_tag` of the class.

        Raises:
            TypeError: If `tag_or_elem` is provided but is not an `_Element` instance.
        """
        tag_or_elem = kwargs.pop("tag_or_elem", None)
        if tag_or_elem is None:
            # Instance for newly created object: create new lxml element and
            # continue by subclass __init__
            # If the tag key word exists, make a custom element
            self._do_init = True
            tag = kwargs.pop("tag", self._tag)
            self.__element = self._make_etree_element(tag)
        else:
            # called with an existing lxml element, sould be a result of
            # from_tag() casting, do not execute the subclass __init__
            if not isinstance(tag_or_elem, _Element):
                raise TypeError(f'"{type(tag_or_elem)}" is not an element node')
            self._do_init = False
            self.__element = tag_or_elem

    def __repr__(self) -> str:
        return f"<{self.__class__.__name__} tag={self.tag}>"

    @classmethod
    def from_tag(cls, tag_or_elem: str | _Element) -> Element:
        """Factory method to create an Element instance (or a subclass) from an XML tag.

        This method can convert an lxml Element or an ODF string tag into an
        ODF XML Element of the appropriate class (e.g., Paragraph, Table, etc.).

        Args:
            tag_or_elem: Either an ODF string tag (e.g., "text:p")
                or an existing `lxml.etree._Element` instance.

        Returns:
            Element: An instance of Element or its appropriate subclass.
        """
        if isinstance(tag_or_elem, str):
            # assume the argument is a prefix:name tag
            elem = cls._make_etree_element(tag_or_elem)
        else:
            elem = tag_or_elem
        klass = _class_registry.get(elem.tag, cls)
        return klass(tag_or_elem=elem)

    @classmethod
    def from_tag_for_clone(
        cls: Any,  # ABCMeta, type, ...
        tree_element: _Element,
        cache: tuple | None,
    ) -> Element:
        """Factory method used internally for cloning elements.

        This method is similar to `from_tag` but is specifically optimized
        for cloning operations, potentially utilizing a cache.

        Args:
            tree_element: The `lxml.etree._Element` instance to clone.
            cache: An optional cache to be copied to the new element.

        Returns:
            Element: A new Element instance (or subclass) representing the cloned element.
        """
        tag = to_str(tree_element.tag)
        klass = _class_registry.get(tag, cls)
        element: Element = klass(tag_or_elem=tree_element)
        if cache:
            element._copy_cache(cache)
        return element

    def _copy_cache(self, cache: tuple) -> None:
        """Copies cache data to the element.

        This method is intended to be redefined by subclasses that utilize caching.

        Args:
            cache: The cache data to be copied.
        """
        pass

    @staticmethod
    def _make_etree_element(tag: str) -> _Element:
        """Create an lxml Element from an ODF tag string.

        Args:
            tag: The ODF tag string (e.g., "text:p", "<text:p/>").

        Returns:
            _Element: An lxml Element instance.

        Raises:
            TypeError: If the tag is not a string.
            ValueError: If the tag is empty.
        """
        if not isinstance(tag, str):
            raise TypeError(f"Tag is not str: {tag!r}")
        tag = tag.strip()
        if not tag:
            raise ValueError("Tag is empty")
        if "<" not in tag:
            # Qualified name
            # XXX don't build the element from scratch or lxml will pollute with
            # repeated namespace declarations
            tag = f"<{tag}/>"
        # XML fragment
        root = fromstring(NAMESPACES_XML % str_to_bytes(tag))
        return root[0]

    def _base_attrib_getter(self, attr_name: str) -> str | None:
        """Internal method to get the value of an attribute by its qualified name.

        Args:
            attr_name: The qualified name of the attribute (e.g., "office:name").

        Returns:
            str | None: The attribute's value as a string, or None if the attribute is not found.
        """
        value = self.__element.get(_get_lxml_tag(attr_name))
        if value is None:
            return None
        return str(value)

    def _base_attrib_setter(
        self,
        attr_name: str,
        value: str | int | float | bool | None,
    ) -> None:
        """Internal method to set the value of an attribute by its qualified name.

        Args:
            attr_name: The qualified name of the attribute (e.g., "office:name").
            value: The value to set for the attribute. If None, the attribute
                is removed. Boolean values are encoded.
        """
        if value is None:
            with contextlib.suppress(KeyError):
                del self.__element.attrib[_get_lxml_tag(attr_name)]
            return
        if isinstance(value, bool):
            value = Boolean.encode(value)
        self.__element.set(_get_lxml_tag(attr_name), str(value))

    @staticmethod
    def _generic_attrib_getter(attr_name: str, family: str | None = None) -> Callable:
        """Creates a getter function for a generic attribute.

        Args:
            attr_name: The qualified name of the attribute.
            family: Optional family name to filter by.

        Returns:
            Callable: A getter function that takes an Element instance and returns
                the attribute's value as a string, boolean, or None.
        """

        def getter(self: Element) -> str | bool | None:
            try:
                if family and self.family != family:  # type: ignore
                    return None
            except AttributeError:
                return None
            value = self._base_attrib_getter(attr_name)
            if value is None:
                return None
            elif value in ("true", "false"):
                return Boolean.decode(value)
            return value

        return getter

    @staticmethod
    def _generic_attrib_setter(attr_name: str, family: str | None = None) -> Callable:
        """Creates a setter function for a generic attribute.

        Args:
            attr_name: The qualified name of the attribute.
            family: Optional family name to filter by.

        Returns:
            Callable: A setter function that takes an Element instance and the value
                to set for the attribute.
        """

        def setter(self: Element, value: Any) -> None:
            try:
                if family and self.family != family:  # type: ignore
                    return None
            except AttributeError:
                return None
            self._base_attrib_setter(attr_name, value)

        return setter

    @staticmethod
    def _boolean_attrib_getter(prop: PropDefBool) -> Callable:
        """Creates a getter function for a boolean attribute.

        Args:
            prop: A NamedTuple defining the boolean property.

        Returns:
            Callable: A getter function that takes an Element instance and returns
                the boolean value of the attribute, or its default.
        """

        def getter(self: Element) -> bool:
            return self._get_attribute_bool_default(prop.attr, prop.default)

        return getter

    @staticmethod
    def _boolean_attrib_setter(prop: PropDefBool) -> Callable:
        """Creates a setter function for a boolean attribute.

        Args:
            prop: A NamedTuple defining the boolean property.

        Returns:
            Callable: A setter function that takes an Element instance and the boolean
                value to set for the attribute.
        """

        def setter(self: Element, value: bool) -> None:
            self._set_attribute_bool_default(prop.attr, value, prop.default)

        return setter

    @classmethod
    def _define_attribut_property(cls: type[Element]) -> None:
        """Dynamically defines properties for the class based on `_properties`.

        This method iterates through the `_properties` tuple of the class and
        creates corresponding getter and setter properties for XML attributes.
        """
        for prop in cls._properties:
            if isinstance(prop, PropDef):
                setattr(
                    cls,
                    prop.name,
                    property(
                        cls._generic_attrib_getter(prop.attr, prop.family or None),
                        cls._generic_attrib_setter(prop.attr, prop.family or None),
                        None,
                        f"Get/set the attribute {prop.attr}",
                    ),
                )
            else:
                setattr(
                    cls,
                    prop.name,
                    property(
                        cls._boolean_attrib_getter(prop),
                        cls._boolean_attrib_setter(prop),
                        None,
                        f"Get/set the attribute {prop.attr}",
                    ),
                )

    @staticmethod
    def _make_before_regex(
        before: str | None,
        after: str | None,
    ) -> re.Pattern:
        """Compiles a regular expression for insertion before or after text.

        Args:
            before: A regex pattern to match text before which to insert.
            after: A regex pattern to match text after which to insert.

        Returns:
            re.Pattern: A compiled regex pattern based on `before` or `after`.

        Raises:
            ValueError: If both `before` and `after` are None.
        """
        # 1) before xor after is not None
        if before is not None:
            return re.compile(before)
        else:
            if after is None:
                raise ValueError("Both 'before' and 'after' are None")
            return re.compile(after)

    @staticmethod
    def _search_negative_position(
        xpath_result: list[str],
        regex: re.Pattern,
    ) -> tuple[str, re.Match]:
        """Searches for the last occurrence of a regex pattern in a list of strings.

        Args:
            xpath_result: A list of strings to search within.
            regex: The compiled regex pattern to search for.

        Returns:
            tuple[str, re.Match]: A tuple containing the string where the match was
                found and the match object itself.

        Raises:
            ValueError: If the text matching the regex is not found.
        """
        # Found the last text that matches the regex
        for text in xpath_result:
            if regex.search(text) is not None:
                break
        else:
            raise ValueError(f"Text not found: {xpath_result!r}")
        return text, list(regex.finditer(text))[-1]

    @staticmethod
    def _search_positive_position(
        xpath_result: list[str],
        regex: re.Pattern,
        position: int,
    ) -> tuple[str, re.Match]:
        """Searches for the nth occurrence of a regex pattern in a list of strings.

        Args:
            xpath_result: A list of strings to search within.
            regex: The compiled regex pattern to search for.
            position: The 0-based index of the match to find.

        Returns:
            tuple[str, re.Match]: A tuple containing the string where the match was
                found and the match object itself.

        Raises:
            ValueError: If the text matching the regex is not found.
        """
        # Found the last text that matches the regex
        count = 0
        for text in xpath_result:
            found_nb = len(regex.findall(text))
            if found_nb + count >= position + 1:
                break
            count += found_nb
        else:
            raise ValueError(f"Text not found: {xpath_result!r}")
        return text, list(regex.finditer(text))[position - count]

    def _insert_before_after(
        self,
        current: _Element,
        element: _Element,
        before: str | None,
        after: str | None,
        position: int,
        xpath_text: XPath,
    ) -> tuple[int, str]:
        """Calculates the insertion position based on 'before' or 'after' regex.

        Args:
            current: The current lxml element.
            element: The element to be inserted.
            before: Regex pattern to find position before.
            after: Regex pattern to find position after.
            position: The occurrence of the regex to consider (negative for last).
            xpath_text: Compiled XPath for text extraction.

        Returns:
            tuple[int, str]: A tuple containing the calculated insertion position
                and the text string where the insertion will occur.
        """
        regex = self._make_before_regex(before, after)
        xpath_result = xpath_return_strings(xpath_text, current)
        # position = -1
        if position < 0:
            text, sre = self._search_negative_position(xpath_result, regex)
        # position >= 0
        else:
            text, sre = self._search_positive_position(xpath_result, regex, position)
        # Compute pos
        if before is None:
            pos = sre.end()
        else:
            pos = sre.start()
        return pos, text

    def _insert_find_text(
        self,
        current: _Element,
        element: _Element,
        before: str | None,
        after: str | None,
        position: int,
        xpath_text: XPath,
    ) -> tuple[int, str]:
        """Finds the text and insertion point based on a character position.

        Args:
            current: The current lxml element.
            element: The element to be inserted.
            before: Not used in this method, kept for signature compatibility.
            after: Not used in this method, kept for signature compatibility.
            position: The character position for insertion.
            xpath_text: Compiled XPath for text extraction.

        Returns:
            tuple[int, str]: A tuple containing the calculated insertion point within
                the text and the text string where the insertion will occur.

        Raises:
            ValueError: If the text at the specified position is not found.
        """
        # Find the text
        xpath_result = xpath_return_strings(xpath_text, current)
        count = 0
        for text in xpath_result:
            found_nb = len(text)
            if found_nb + count >= position:
                break
            count += found_nb
        else:
            raise ValueError(f"Text not found: {xpath_result!r}")
        # We insert before the character
        pos = position - count
        return pos, text

    def _insert(
        self,
        element: Element,
        before: str | None = None,
        after: str | None = None,
        position: int = 0,
    ) -> None:
        """Insert an element before or after characters matching a regex.

        When the regex matches multiple parts of the text, `position` can specify
        which part to use. If both `before` and `after` are None, `position`
        refers to the character index. A positive `position` inserts before that
        character; `position=-1` inserts after the last character.
        Annotation text content is ignored.

        Args:
            element: The element to insert.
            before: A regex pattern. The element will be inserted
                before the text matching this pattern.
            after: A regex pattern. The element will be inserted
                after the text matching this pattern.
            position: The 0-based index of the regex match to consider,
                or a character position if `before` and `after` are None.

        Raises:
            ValueError: If an invalid combination of arguments is provided.
        """
        current = self.__element
        xelement = element.__element

        # 1) before xor after is not None
        if (before is not None) ^ (after is not None):
            pos, text = self._insert_before_after(
                current,
                xelement,
                before,
                after,
                position,
                _xpath_text_descendant_no_annotation,
            )
        # 2) before=after=None => only with position
        elif before is None and after is None:
            # Hack if position is negative => quickly
            if position < 0:
                current.append(xelement)
                return
            pos, text = self._insert_find_text(
                current,
                xelement,
                before,
                after,
                position,
                _xpath_text_descendant_no_annotation,
            )
        else:
            raise ValueError("bad combination of arguments")

        # Compute new texts
        text_before = text[:pos] if text[:pos] else None
        text_after = text[pos:] if text[pos:] else None

        # Insert!
        parent = text.getparent()  # type: ignore
        if text.is_text:  # type: ignore
            parent.text = text_before
            element.tail = text_after
            parent.insert(0, xelement)
        else:
            parent.addnext(xelement)
            parent.tail = text_before
            element.tail = text_after

    @property
    def tag(self) -> str:
        """Gets the underlying XML tag with the qualified name.

        Returns:
            str: The qualified name of the XML tag (e.g., "text:span").
        """
        return _get_prefixed_name(self.__element.tag)

    @tag.setter
    def tag(self, qname: str) -> None:
        """Sets the underlying XML tag with the given qualified name.

        Warning: Direct change of the tag does not change the Python element class itself.

        Args:
            qname: The new qualified name for the XML tag (e.g., "text:span").
        """
        self.__element.tag = _get_lxml_tag(qname)

    def elements_repeated_sequence(
        self,
        xpath_instance: XPath,
        name: str,
    ) -> list[tuple[int, int]]:
        """Extracts repeated sequence information from elements for table handling.

        This utility method is primarily used by the table module to process
        elements that might have a 'number-columns-repeated' or similar attribute.
        It returns a list of tuples, where each tuple contains the index of the
        element and how many times it is logically repeated.

        Args:
            xpath_instance: A compiled XPath object to select sub-elements.
            name: The name of the attribute (e.g., "table:number-columns-repeated")
                that indicates repetition.

        Returns:
            list[tuple[int, int]]: A list of (index, repetition_count) tuples.
        """
        lxml_tag = _get_lxml_tag_or_name(name)
        sub_elements = xpath_return_elements(xpath_instance, self.__element)
        result: list[tuple[int, int]] = []
        idx = -1
        for sub_element in sub_elements:
            idx += 1
            value = sub_element.get(lxml_tag)
            if value is None:
                result.append((idx, 1))
                continue
            try:
                int_value = int(value)
            except ValueError:  # pragma: nocover
                int_value = 1
            result.append((idx, max(int_value, 1)))
        return result

    def get_elements(self, xpath_query: XPath | str) -> list[Element]:
        """Returns a list of elements obtained by applying an XPath query.

        Args:
            xpath_query: The XPath query string or a compiled `lxml.etree.XPath` object.

        Returns:
            list[Element]: A list of Element instances matching the query.
        """
        if isinstance(xpath_query, str):
            elements = xpath_return_elements(xpath_compile(xpath_query), self.__element)
        else:
            elements = xpath_return_elements(xpath_query, self.__element)
        return [Element.from_tag_for_clone(e, None) for e in elements]

    def get_element(self, xpath_query: str) -> Element | None:
        """Returns the first element obtained by applying an XPath query.

        Args:
            xpath_query: The XPath query string.

        Returns:
            Element | None: The first Element instance matching the query, or None if no match.
        """
        result = self.__element.xpath(f"({xpath_query})[1]", namespaces=ODF_NAMESPACES)
        if result:
            return Element.from_tag(result[0])
        return None

    def _get_element_idx(self, xpath_query: XPath | str, idx: int) -> Element | None:
        """Returns the element at a specific index from an XPath query result.

        Args:
            xpath_query: The XPath query string or a compiled `lxml.etree.XPath` object.
            idx: The 0-based index of the desired element in the query result.

        Returns:
            Element | None: The Element instance at the specified index, or None if not found.
        """
        result = self.__element.xpath(
            f"({xpath_query})[{idx + 1}]", namespaces=ODF_NAMESPACES
        )
        if result:
            return Element.from_tag(result[0])
        return None

    def _get_element_idx2(self, xpath_instance: XPath, idx: int) -> Element | None:
        """Returns the element at a specific index using a pre-compiled XPath instance.

        Args:
            xpath_instance: A compiled `lxml.etree.XPath` object.
            idx: The 0-based index of the desired element in the query result.

        Returns:
            Element | None: The Element instance at the specified index, or None if not found.
        """
        result = xpath_instance(self.__element, idx=idx + 1)
        if result:
            return Element.from_tag(result[0])
        return None

    @property
    def attributes(self) -> dict[str, str]:
        """Gets all attributes of the element as a dictionary.

        The keys are qualified attribute names (e.g., "office:name"),
        and the values are their string representations.

        Returns:
            dict[str, str]: A dictionary of attribute names and their values.
        """
        return {
            _get_prefixed_name(str(key)): str(value)
            for key, value in self.__element.attrib.items()
        }

    def get_attribute(self, name: str) -> str | bool | None:
        """Returns the value of a specified attribute.

        Args:
            name: The qualified name of the attribute to retrieve (e.g., "office:name").

        Returns:
            str | bool | None: The attribute's value, which can be a string, a boolean
                (if the original value was "true" or "false"), or None if the attribute is not found.
        """
        element = self.__element
        lxml_tag = _get_lxml_tag_or_name(name)
        value = element.get(lxml_tag)
        if value is None:
            return None
        elif value in ("true", "false"):
            return Boolean.decode(value)
        return str(value)

    def get_attribute_integer(self, name: str) -> int | None:
        """Returns the value of a specified attribute as an integer.

        Args:
            name: The qualified name of the attribute to retrieve.

        Returns:
            int | None: The attribute's value as an integer, or None if the attribute
                is not found or cannot be converted to an integer.
        """
        element = self.__element
        lxml_tag = _get_lxml_tag_or_name(name)
        value = element.get(lxml_tag)
        if value is None:
            return None
        try:
            return int(value)
        except ValueError:
            return None

    def get_attribute_number(self, name: str) -> int | Decimal | None:
        """Returns the value of a specified attribute as a number (Decimal or int).

        Args:
            name: The qualified name of the attribute to retrieve.

        Returns:
            int | Decimal | None: The attribute's value as an int (if it's a whole number)
                or a Decimal, or None if the attribute is not found or cannot be
                converted to a number.
        """
        element = self.__element
        lxml_tag = _get_lxml_tag_or_name(name)
        value = element.get(lxml_tag)
        if value is None:
            return None
        value = Decimal(value)
        # Return 3 instead of 3.0 if possible
        with contextlib.suppress(ValueError):
            if int(value) == value:
                return int(value)
        return value

    def get_attribute_string(self, name: str) -> str | None:
        """Returns the value of a specified attribute as a string.

        Args:
            name: The qualified name of the attribute to retrieve.

        Returns:
            str | None: The attribute's value as a string, or None if the attribute is not found.
        """
        element = self.__element
        lxml_tag = _get_lxml_tag_or_name(name)
        value = element.get(lxml_tag)
        if value is None:
            return None
        return str(value)

    def _get_attribute_bool_default(self, name: str, default: bool = True) -> bool:
        """Returns the value of a specified boolean attribute, using a default if not present.

        Args:
            name: The qualified name of the attribute to retrieve.
            default: The default boolean value to return if the attribute is not found.

        Returns:
            bool: The attribute's boolean value or the provided default value.
        """
        element = self.__element
        lxml_tag = _get_lxml_tag_or_name(name)
        value = element.get(lxml_tag)
        if value is None:
            return default
        return Boolean.decode(value)

    def _set_attribute_bool_default(
        self, name: str, value: bool | str | None, default: bool = True
    ) -> None:
        """Sets the value of a specified boolean attribute, removing it if it matches the default.

        Args:
            name: The qualified name of the attribute to set.
            value: The boolean value to set. Can be a bool,
                "true"/"false" string, or None. If None, it defaults to False.
            default: The default boolean value. If the `value` to set
                matches this default, the attribute is removed.
        """
        element = self.__element
        lxml_tag = _get_lxml_tag_or_name(name)
        if value is None:
            value = False
        if isinstance(value, str):
            value = value.lower() == "true"
        if value == default:
            with contextlib.suppress(KeyError):
                del element.attrib[lxml_tag]
            return
        element.set(lxml_tag, Boolean.encode(value))

    def _get_attribute_str_default(self, name: str, default: str = "") -> str:
        """Returns the value of a specified string attribute, using a default if not present.

        Args:
            name: The qualified name of the attribute to retrieve.
            default: The default string value to return if the attribute is not found.

        Returns:
            str: The attribute's string value or the provided default value.
        """
        element = self.__element
        lxml_tag = _get_lxml_tag_or_name(name)
        value = element.get(lxml_tag)
        if value is None:
            return default
        return str(value)

    def _set_attribute_str(self, name: str, value: str) -> None:
        """Sets the value of a string attribute.

        This internal method directly sets the value of an attribute without
        any default handling or type conversions beyond converting the value
        to a string if necessary.

        Args:
            name: The qualified name of the attribute to set.
            value: The string value to set for the attribute.
        """
        lxml_tag = _get_lxml_tag_or_name(name)
        self.__element.set(lxml_tag, value)

    def _set_attribute_str_default(
        self, name: str, value: str | None, default: str = ""
    ) -> None:
        """Sets the value of a specified string attribute, removing it if it matches the default.

        Args:
            name: The qualified name of the attribute to set.
            value: The string value to set. If None or matches `default`,
                the attribute is removed.
            default: The default string value. If the `value` to set
                matches this default, the attribute is removed.
        """
        element = self.__element
        lxml_tag = _get_lxml_tag_or_name(name)
        if value is None or value == default:
            with contextlib.suppress(KeyError):
                del element.attrib[lxml_tag]
            return
        element.set(lxml_tag, value)

    def _get_attribute_int_default(self, name: str, default: int) -> int:
        """Returns the value of a specified integer attribute, using a default if not present.

        Args:
            name: The qualified name of the attribute to retrieve.
            default: The default integer value to return if the attribute is not found
                or cannot be converted.

        Returns:
            int: The attribute's integer value or the provided default value.
        """
        element = self.__element
        lxml_tag = _get_lxml_tag_or_name(name)
        value = element.get(lxml_tag)
        if value is None:
            return default
        try:
            return int(value)
        except ValueError:
            return default

    def _set_attribute_int(self, name: str, value: int | None) -> None:
        """Sets the value of a specified integer attribute.

        Args:
            name: The qualified name of the attribute to set.
            value: The integer value to set. If None, the attribute is
                removed.
        """
        element = self.__element
        lxml_tag = _get_lxml_tag_or_name(name)
        if value is None:
            with contextlib.suppress(KeyError):
                del element.attrib[lxml_tag]
            return
        element.set(lxml_tag, str(value))

    def _set_attribute_int_default(
        self, name: str, value: int | None, default: int
    ) -> None:
        """Sets the value of a specified integer attribute, removing it if it matches the default.

        Args:
            name: The qualified name of the attribute to set.
            value: The integer value to set. If None or matches `default`,
                the attribute is removed.
            default: The default integer value. If the `value` to set
                matches this default, the attribute is removed.
        """
        element = self.__element
        lxml_tag = _get_lxml_tag_or_name(name)
        if value is None or value == default:
            with contextlib.suppress(KeyError):
                del element.attrib[lxml_tag]
            return
        element.set(lxml_tag, str(value))

    def _set_attribute_number_default(
        self,
        name: str,
        value: Decimal | int | float | None,
        default: Decimal | int | float | None,
    ) -> None:
        """Sets the value of a specified number attribute (Decimal, int, or float),
        removing it if it matches the default.

        Args:
            name: The qualified name of the attribute to set.
            value: The numeric value to set.
                If None or matches `default`, the attribute is removed.
            default: The default numeric value.
                If the `value` to set matches this default, the attribute is removed.
        """
        element = self.__element
        lxml_tag = _get_lxml_tag_or_name(name)
        if value is None or value == default:
            with contextlib.suppress(KeyError):
                del element.attrib[lxml_tag]
            return
        element.set(lxml_tag, str(value))

    def set_attribute(
        self, name: str, value: bool | str | tuple[int, int, int] | None
    ) -> None:
        """Sets the value of a specified attribute.

        Handles special cases for color properties and boolean values.

        Args:
            name: The qualified name of the attribute to set.
            value: The value to set.
                Can be a boolean, string, a color tuple (R, G, B), or None.
                If None, the attribute is removed.

        Raises:
            TypeError: If a boolean value is provided for a color property.
        """
        if name in ODF_COLOR_PROPERTY:
            if isinstance(value, bool):
                raise TypeError(f"Wrong color type {value!r}")
            if value != "transparent":
                value = hexa_color(value)
        element = self.__element
        lxml_tag = _get_lxml_tag_or_name(name)
        if isinstance(value, bool):
            value = Boolean.encode(value)
        elif value is None:
            with contextlib.suppress(KeyError):
                del element.attrib[lxml_tag]
            return
        element.set(lxml_tag, str(value))

    def set_style_attribute(self, name: str, value: Style | str | None) -> None:
        """Sets a style-related attribute, allowing a Style object as a value.

        Args:
            name: The qualified name of the style attribute to set.
            value: The value for the style attribute.
                Can be a `Style` object (its name will be used), a string, or None.
        """
        if isinstance(value, Element):
            value = str(value.name)
        return self.set_attribute(name, value)

    def del_attribute(self, name: str) -> None:
        """Deletes a specified attribute from the element.

        Args:
            name: The qualified name of the attribute to delete.

        Raises:
            KeyError: If the specified attribute does not exist.
        """
        element = self.__element
        lxml_tag = _get_lxml_tag_or_name(name)
        del element.attrib[lxml_tag]

    def del_attribute_list(self, names: Iterable[str]) -> None:
        """Deletes a list of attributes from the element if present.

        Args:
            names: The qualified names of the attributes to delete.
        """
        for name in names:
            with contextlib.suppress(KeyError):
                del self.__element.attrib[_get_lxml_tag_or_name(name)]

    @property
    def text(self) -> str:
        """Gets the text content of the element.

        Returns:
            str: The text content of the element. Defaults to an empty string if no text is present.
        """
        return self.__element.text or ""

    @text.setter
    def text(self, text: str | None) -> None:
        """Sets the text content of the element.

        Args:
            text: The new text content. If None, it is set to an empty string.

        Raises:
            TypeError: If the provided text is not a string type.
        """
        if text is None:
            text = ""
        try:
            self.__element.text = text
        except TypeError as e:
            raise TypeError(f'Str type expected: "{type(text)}"') from e

    def __str__(self) -> str:
        return self.inner_text

    @property
    def _text_tail(self) -> str:
        """Returns the concatenated inner text and tail of the element.

        Returns:
            str: The string representation of the element's inner text plus its tail.
        """
        return str(self) + (self.tail or "")

    # def _elements_descendants(self) -> Iterator[Element]:
    #     for elem in self.__element.iterdescendants():
    #         if isinstance(elem, _Element):
    #             yield Element.from_tag(elem)

    @property
    def inner_text(self) -> str:
        """Returns the concatenated text content of the element and its children (excluding its own tail).

        Returns:
            str: The inner text of the element.
        """
        return self.text + "".join(e._text_tail for e in self.children)

    @property
    def text_recursive(self) -> str:
        """Returns the full recursive text content of the element, including its own tail.

        Returns:
            str: The entire text content, recursively.
        """
        return self.inner_text + (self.tail or "")

    @property
    def tail(self) -> str | None:
        """Gets the text immediately following the element.

        Returns:
            str | None: The tail text, or None if no tail text is present.
        """
        return self.__element.tail  # type: ignore[no-any-return]

    @tail.setter
    def tail(self, text: str | None) -> None:
        """Sets the text immediately following the element.

        Args:
            text: The new tail text. If None, it is set to an empty string.
        """
        self.__element.tail = text or ""

    def search(self, pattern: str) -> int | None:
        """Returns the first position of a pattern in the element's text content.

        Python regular expression syntax applies.

        Args:
            pattern: The regex pattern to search for.

        Returns:
            int | None: The starting index of the first match, or None if not found.
        """
        match = re.search(pattern, self.text_recursive)
        if match is None:
            return None
        return match.start()

    def search_first(self, pattern: str) -> tuple[int, int] | None:
        """Returns the start and end positions of the first occurrence of a regex pattern.

        Python regular expression syntax applies.

        Args:
            pattern: The regex pattern to search for.

        Returns:
            tuple[int, int] | None: A tuple (start_position, end_position) of the
                first match, or None if no match is found.
        """
        match = re.search(pattern, self.text_recursive)
        if match is None:
            return None
        return match.start(), match.end()

    def search_all(self, pattern: str) -> list[tuple[int, int]]:
        """Returns all start and end positions of a regex pattern in the element's text content.

        Python regular expression syntax applies.

        Args:
            pattern: The regex pattern to search for.

        Returns:
            list[tuple[int, int]]: A list of (start_position, end_position) tuples for all matches.
        """
        results: list[tuple[int, int]] = []
        for match in re.finditer(pattern, self.text_recursive):
            results.append((match.start(), match.end()))
        return results

    def text_at(self, start: int, end: int | None = None) -> str:
        """Returns the recursive text content of the element between specified positions.

        Args:
            start: The starting character position (0-based).
            end: The ending character position (exclusive). If None,
                returns text from `start` to the end.

        Returns:
            str: The substring of the element's recursive text.
        """
        if start < 0:
            start = 0
        if end is None:
            return self.text_recursive[start:]
        else:
            if end < start:
                end = start
            return self.text_recursive[start:end]

    def match(self, pattern: str) -> bool:
        """Checks if a pattern is found one or more times within the element's text content.

        Python regular expression syntax applies.

        Args:
            pattern: The regex pattern to match.

        Returns:
            bool: True if the pattern is found, False otherwise.
        """
        return self.search(pattern) is not None

    def replace(
        self,
        pattern: str,
        new: str | None = None,
        formatted: bool = False,
    ) -> int:
        """Replaces occurrences of a pattern with new text within the element's content.

        It cannot replace patterns found across several elements (e.g., a word
        split into two consecutive spans).

        Python regular expression syntax applies.

        If `formatted` is True, and the target is a Paragraph, Span, or Header,
        and the replacement text contains spaces, tabs, or newlines, an attempt
        is made to convert them into actual ODF elements to obtain a formatted result.
        On very complex contents, the result may differ from expectations.

        Args:
            pattern: The regex pattern to search and replace.
            new: The replacement string. If None, it counts occurrences.
                If an empty string, it deletes matches.
            formatted: If True, attempts to convert whitespace in replacement
                text to ODF elements for formatting.

        Returns:
            int: The number of replacements made.
        """
        if not isinstance(pattern, str):
            # Fail properly if the pattern is an non-ascii bytestring
            pattern = str(pattern)
        cpattern = re.compile(pattern)
        count = 0
        for text in self.xpath("descendant::text()"):
            if new is None:
                count += len(cpattern.findall(str(text)))
            else:
                new_text, number = cpattern.subn(new, str(text))
                container = text.parent
                if not container:  # pragma: nocover
                    continue
                if text.is_text():  # type: ignore
                    container.text = new_text
                else:
                    container.tail = new_text
                if formatted and container.tag in {  # type; ignore
                    "text:h",
                    "text:p",
                    "text:span",
                }:
                    container.append_plain_text("")  # type: ignore[attr-defined]
                count += number
        return count

    @property
    def root(self) -> Element:
        """Returns the root element of the XML tree containing this element.

        Returns:
            Element: The root Element instance.
        """
        element = self.__element
        tree = element.getroottree()
        root = tree.getroot()
        return Element.from_tag(root)

    @property
    def parent(self) -> Element | None:
        """Returns the parent element of this element.

        Returns:
            Element | None: The parent Element instance, or None if this element is the root.
        """
        element = self.__element
        parent = element.getparent()
        if parent is None:
            # Already at root
            return None
        return Element.from_tag(parent)

    @property
    def is_bound(self) -> bool:
        """Checks if the element is currently part of an XML tree (has a parent).

        Returns:
            bool: True if the element has a parent, False otherwise.
        """
        return self.parent is not None

    # def get_next_sibling(self):
    #     element = self.__element
    #     next_one = element.getnext()
    #     if next_one is None:
    #         return None
    #     return Element.from_tag(next_one)
    #
    # def get_prev_sibling(self):
    #     element = self.__element
    #     prev = element.getprevious()
    #     if prev is None:
    #         return None
    #     return Element.from_tag(prev)

    @property
    def children(self) -> list[Element]:
        """Returns a list of immediate child elements.

        Returns:
            list[Element]: A list of Element instances representing the direct children.
        """
        element = self.__element
        return [
            Element.from_tag(e)
            for e in element.iterchildren()
            if isinstance(e, _Element)
        ]

    def index(self, child: Element) -> int:
        """Returns the position of a child element within this element.

        Inspired by lxml's behavior.

        Args:
            child: The child element to find the index of.

        Returns:
            int: The 0-based index of the child element.
        """
        idx: int = self.__element.index(child.__element)
        return idx

    @property
    def text_content(self) -> str:
        """Gets the text content of embedded paragraphs, including annotations and cells.

        Returns:
            str: The concatenated text content of all embedded paragraphs.
        """
        content = "".join(
            str(child) for child in self.get_elements("descendant::text:p")
        )
        if content.endswith("\n"):
            return content[:-1]
        return content

    @text_content.setter
    def text_content(self, text: str | Element | None) -> None:
        """Sets the text content of the embedded paragraphs.

        If no paragraph exists, one is created. This operation overwrites all
        existing text nodes and children that may contain text.

        Args:
            text: The new text content. Can be a string,
                another `Element`, or None (clears content).
        """
        paragraphs = self.get_elements("text:p")
        if not paragraphs:
            # E.g., text:p in draw:text-box in draw:frame
            paragraphs = self.get_elements("*/text:p")
        if paragraphs:
            paragraph = paragraphs.pop(0)
            for obsolete in paragraphs:
                obsolete.delete()
        else:
            paragraph = Element.from_tag("text:p")
            self.insert(paragraph, FIRST_CHILD)
        # As "text_content" returned all text nodes, "text_content"
        # will overwrite all text nodes and children that may contain them
        element = paragraph.__element
        # Clear but the attributes
        del element[:]
        if text is None:
            text = ""
        element.text = str(text)

    def is_empty(self) -> bool:
        """Checks if the element is empty (no text, no children, no tail).

        Returns:
            bool: True if the element is empty, False otherwise.
        """
        element = self.__element
        if element.tail is not None:
            return False
        if element.text is not None:
            return False
        if list(element.iterchildren()):  # noqa: SIM103
            return False
        return True

    def insert(
        self,
        element: Element,
        xmlposition: int | None = None,
        position: int | None = None,
        start: bool = False,
    ) -> None:
        """Inserts an element relative to the current element.

        Insertion can be done using DOM vocabulary (`xmlposition`) or by numeric position.
        If `start` is True, the element is inserted before any existing text content.
        Positions are 0-based.

        Args:
            element: The element to insert.
            xmlposition: Specifies insertion relative to DOM, using
                `FIRST_CHILD`, `LAST_CHILD`, `NEXT_SIBLING`, or `PREV_SIBLING`.
            position: A 0-based numeric index for insertion. Used if
                `xmlposition` is None.
            start: If True, insert the element before any existing text of the
                current element, preserving the text as the tail of the inserted element.

        Raises:
            ValueError: If `xmlposition` is not defined and `position` is also None.
        """
        # child_tag = element.tag
        current = self.__element
        lx_element = element.__element
        if start:
            text = current.text
            if text is not None:
                current.text = None
                tail = lx_element.tail
                if tail is None:
                    tail = text
                else:
                    tail = tail + text
                lx_element.tail = tail
            position = 0
        if position is not None:
            current.insert(position, lx_element)
        elif xmlposition is FIRST_CHILD:
            current.insert(0, lx_element)
        elif xmlposition is LAST_CHILD:
            current.append(lx_element)
        elif xmlposition is NEXT_SIBLING:
            parent = current.getparent()
            index = parent.index(current)
            parent.insert(index + 1, lx_element)
        elif xmlposition is PREV_SIBLING:
            parent = current.getparent()
            index = parent.index(current)
            parent.insert(index, lx_element)
        else:
            raise ValueError("(xml)position must be defined")

    def extend(self, odf_elements: Iterable[Element]) -> None:
        """Appends multiple ODF elements efficiently to the end of the current element.

        Args:
            odf_elements: An iterable (e.g., list) of Element instances to append.
        """
        if odf_elements:
            current = self.__element
            elements = [element.__element for element in odf_elements]
            current.extend(elements)

    def _xml_append(self, element: Element) -> None:
        """Appends the underlying lxml element of another Element instance.

        Args:
            element: The Element instance whose underlying XML element will be appended.
        """
        self.__element.append(element.__element)

    @property
    def _xml_element(self) -> _Element:
        """Returns the underlying lxml.etree._Element object.

        Returns:
            _Element: The raw lxml element.
        """
        return self.__element

    def __append(self, str_or_element: str | Element) -> None:
        """Appends an element or text to the end of the current element.

        If `str_or_element` is a string, it is appended as text. If it is an
        `Element`, its underlying XML element is appended.

        Args:
            str_or_element: The string or Element to append.

        Raises:
            TypeError: If the provided argument is neither a string nor an Element.
        """

        def _add_text(text1: str | None, text2: str | None) -> str:
            return _re_anyspace.sub(" ", (text1 or "") + (text2 or ""))

        current = self.__element
        if isinstance(str_or_element, str):
            # Has children ?
            children = list(current.iterchildren())
            if children:
                # Append to tail of the last child
                last_child = children[-1]
                last_child.tail = _add_text(last_child.tail, str_or_element)
            else:
                # Append to text of the element
                current.text = _add_text(current.text, str_or_element)
        elif isinstance(str_or_element, Element):
            current.append(str_or_element.__element)
        else:
            raise TypeError(f'Element or string expected, not "{type(str_or_element)}"')

    append = __append

    def delete(self, child: Element | None = None, keep_tail: bool = True) -> None:
        """Deletes an element from the XML tree.

        If `child` is provided, that specific child element is deleted from this element.
        If `child` is None, the current element (`self`) is deleted from its parent.
        The XML library may allow orphaned elements to be used as long as a reference exists.

        Args:
            child: The child element to delete. If None, `self` is deleted.
            keep_tail: If True (default), the tail text of the deleted element
                is preserved and appended to the previous sibling or parent's text.

        Raises:
            ValueError: If an attempt is made to delete the root element (`self` has no parent).
        """
        if child is None:
            parent = self.parent
            if parent is None:
                raise ValueError(f"Can't delete the root element\n{self.serialize()}")
            child = self
        else:
            parent = self
        if keep_tail and child.__element.tail is not None:
            current = child.__element
            tail = str(current.tail)
            current.tail = None
            prev = current.getprevious()
            if prev is not None:
                if prev.tail is None:
                    prev.tail = tail
                else:
                    prev.tail += tail
            else:
                if parent.__element.text is None:
                    parent.__element.text = tail
                else:
                    parent.__element.text += tail
        parent.__element.remove(child.__element)

    def replace_element(self, old_element: Element, new_element: Element) -> None:
        """Replaces an existing sub-element with a new one in place.

        Warning: This operation does not clone the `old_element`; it is directly
        removed from the tree.

        Args:
            old_element: The existing child element to be replaced.
            new_element: The new element to insert in place of `old_element`.
        """
        current = self.__element
        current.replace(old_element.__element, new_element.__element)

    def xpath(self, xpath_query: str) -> list[Element | EText]:
        """Applies an XPath query to the element and its subtree.

        Args:
            xpath_query: The XPath query string to apply.

        Returns:
            list[Element | EText]: A list of matching Element or EText instances.
        """
        xpath_instance = xpath_compile(xpath_query)
        x_elements = xpath_instance(self.__element)
        result: list[Element | EText] = []
        if isinstance(x_elements, list):
            for obj in x_elements:
                if isinstance(obj, (str, bytes)):
                    result.append(EText(obj))
                elif isinstance(obj, _Element):  # pragma: nocover
                    result.append(Element.from_tag(obj))
        return result

    def clear(self) -> None:
        """Removes all text content, child elements, and attributes from the element."""
        self.__element.clear()

    @property
    def clone(self) -> Element:
        """Creates a deep copy of the current element.

        Returns:
            Element: A new Element instance that is a deep copy of the original.
        """
        clone = deepcopy(self.__element)
        root = lxml_Element("ROOT", nsmap=ODF_NAMESPACES)
        root.append(clone)
        return self.from_tag(clone)

        # slow data = tostring(self.__element, encoding='unicode')
        # return self.from_tag(data)

    @staticmethod
    def _strip_namespaces(data: str) -> str:
        """Removes xmlns:* attributes from a serialized XML string.

        Args:
            data: The serialized XML string.

        Returns:
            str: The XML string with xmlns attributes removed.
        """
        return re.sub(r' xmlns:\w*="[\w:\-\/\.#]*"', "", data)

    def serialize(self, pretty: bool = False, with_ns: bool = False) -> str:
        """Returns the text serialization of the XML element.

        Args:
            pretty: If True, the output XML will be pretty-printed.
            with_ns: If True, namespace declarations will be included in the output.

        Returns:
            str: The serialized XML content as a string.
        """
        # This copy bypasses serialization side-effects in lxml
        native = deepcopy(self.__element)
        data: str = tostring(
            native,
            with_tail=False,
            pretty_print=pretty,
            encoding="unicode",
        )
        if with_ns:
            return data
        # Remove namespaces
        return self._strip_namespaces(data)

    def _canonicalize(self) -> str:
        """(Internal) Returns a canonical representation of the Element
        (C14N2), with namespaces stripped.

        Used in the test suite.

        Returns:
            str: The normalized XML content as a string.
        """
        return self._strip_namespaces(
            canonicalize(tostring(self.__element, with_tail=False))
        )

    # Element helpers usable from any context

    @property
    def document_body(self) -> Body | None:
        """Returns the first child of the document body, if any.

        This typically corresponds to the main content area of an ODF document.

        Returns:
            Body | None: The first child Element of `office:body`, or None if not found.
        """
        return self.get_element("//office:body/*[1]")  # type: ignore[return-value]

    def get_formatted_text(self, context: dict | None = None) -> str:
        """Returns a formatted version of the element's text.

        This method is typically overridden by subclasses to provide specific
        text formatting based on the element type and context.

        Args:
            context: Optional dictionary providing context for formatting.

        Returns:
            str: A formatted string representation of the element's text.
        """
        return ""

    def get_styled_elements(self, name: str = "") -> list[Element]:
        """Finds elements (paragraphs, tables, etc.) using a given style name.

        Args:
            name: The name of the style to filter by. If an empty string,
                all styled elements are returned.

        Returns:
            list[Element]: A list of Element instances that match the specified style.
        """
        # FIXME incomplete (and possibly inaccurate)
        return (
            self._filtered_elements("descendant::*", text_style=name)
            + self._filtered_elements("descendant::*", draw_style=name)
            + self._filtered_elements("descendant::*", draw_text_style=name)
            + self._filtered_elements("descendant::*", table_style=name)
            + self._filtered_elements("descendant::*", page_layout=name)
            + self._filtered_elements("descendant::*", master_page=name)
            + self._filtered_elements("descendant::*", parent_style=name)
        )

    # Common attributes

    def _get_inner_text(self, tag: str) -> str | None:
        """Retrieves the text content of a specified inner element.

        Args:
            tag: The qualified name of the inner element (e.g., "svg:title").

        Returns:
            str | None: The text content of the inner element, or None if the element is not found.
        """
        element = self.get_element(tag)
        if element is None:
            return None
        return element.text

    def _set_inner_text(self, tag: str, text: str) -> None:
        """Sets the text content of a specified inner element.

        If the inner element does not exist, it is created.

        Args:
            tag: The qualified name of the inner element (e.g., "svg:title").
            text: The new text content to set.
        """
        element = self.get_element(tag)
        if element is None:
            element = Element.from_tag(tag)
            self.__append(element)
        element.text = text

    # Paragraphs

    def get_paragraphs(
        self,
        style: str | None = None,
        content: str | None = None,
    ) -> list[Paragraph]:
        """Returns all paragraphs that match the specified criteria.

        Args:
            style: The name of the style to filter paragraphs by.
            content: A regex pattern to match against the paragraph's content.

        Returns:
            list[Paragraph]: A list of Paragraph instances matching the criteria.
        """
        return self._filtered_elements(
            "descendant::text:p", text_style=style, content=content
        )  # type: ignore[return-value]

    @property
    def paragraphs(self) -> list[Paragraph]:
        """Returns all paragraphs as a list.

        Returns:
            list[Paragraph]: A list of all Paragraph instances that are descendants of this element.
        """
        return self.get_elements(
            "descendant::text:p",
        )  # type: ignore[return-value]

    def get_paragraph(
        self,
        position: int = 0,
        content: str | None = None,
    ) -> Paragraph | None:
        """Returns a single paragraph that matches the specified criteria.

        Args:
            position: The 0-based index of the matching paragraph to return.
            content: A regex pattern to match against the paragraph's content.

        Returns:
            Paragraph | None: A Paragraph instance, or None if no paragraph matches the criteria.
        """
        return self._filtered_element(
            "descendant::text:p",
            position,
            content=content,
        )  # type: ignore[return-value]

    # Span

    def get_spans(
        self,
        style: str | None = None,
        content: str | None = None,
    ) -> list[Span]:
        """Returns all spans that match the specified criteria.

        Args:
            style: The name of the style to filter spans by.
            content: A regex pattern to match against the span's content.

        Returns:
            list[Span]: A list of Span instances matching the criteria.
        """
        return self._filtered_elements(
            "descendant::text:span", text_style=style, content=content
        )  # type: ignore[return-value]

    @property
    def spans(self) -> list[Span]:
        """Returns all spans as a list.

        Returns:
            list[Span]: A list of all Span instances that are descendants of this element.
        """
        return self.get_elements("descendant::text:span")  # type: ignore[return-value]

    def get_span(
        self,
        position: int = 0,
        content: str | None = None,
    ) -> Span | None:
        """Returns a single span that matches the specified criteria.

        Args:
            position: The 0-based index of the matching span to return.
            content: A regex pattern to match against the span's content.

        Returns:
            Span | None: A Span instance, or None if no span matches the criteria.
        """
        return self._filtered_element(
            "descendant::text:span", position, content=content
        )  # type: ignore[return-value]

    # Headers

    def get_headers(
        self,
        style: str | None = None,
        outline_level: str | None = None,
        content: str | None = None,
    ) -> list[Header]:
        """Returns all headers that match the specified criteria.

        Args:
            style: The name of the style to filter headers by.
            outline_level: The outline level to filter headers by.
            content: A regex pattern to match against the header's content.

        Returns:
            list[Header]: A list of Header instances matching the criteria.
        """
        return self._filtered_elements(
            "descendant::text:h",
            text_style=style,
            outline_level=outline_level,
            content=content,
        )  # type: ignore[return-value]

    @property
    def headers(self) -> list[Header]:
        """Returns all headers as a list.

        Returns:
            list[Header]: A list of all Header instances that are descendants of this element.
        """
        return self.get_elements("descendant::text:h")  # type: ignore[return-value]

    def get_header(
        self,
        position: int = 0,
        outline_level: str | None = None,
        content: str | None = None,
    ) -> Header | None:
        """Returns a single header that matches the specified criteria.

        Args:
            position: The 0-based index of the matching header to return.
            outline_level: The outline level to filter headers by.
            content: A regex pattern to match against the header's content.

        Returns:
            Header | None: A Header instance, or None if no header matches the criteria.
        """
        return self._filtered_element(
            "descendant::text:h",
            position,
            outline_level=outline_level,
            content=content,
        )  # type: ignore[return-value]

    # Frames

    def get_frames(
        self,
        presentation_class: str | None = None,
        style: str | None = None,
        title: str | None = None,
        description: str | None = None,
        content: str | None = None,
    ) -> list[Frame]:
        """Returns all frames that match the specified criteria.

        Args:
            presentation_class: The presentation class to filter frames by.
            style: The name of the style to filter frames by.
            title: A regex pattern to match against the frame's title.
            description: A regex pattern to match against the frame's description.
            content: A regex pattern to match against the frame's content.

        Returns:
            list[Frame]: A list of Frame instances matching the criteria.
        """
        return self._filtered_elements(
            "descendant::draw:frame",
            presentation_class=presentation_class,
            draw_style=style,
            svg_title=title,
            svg_desc=description,
            content=content,
        )  # type: ignore[return-value]

    @property
    def frames(self) -> list[Frame]:
        """Returns all frames as a list.

        Returns:
            list[Frame]: A list of all Frame instances that are descendants of this element.
        """
        return self.get_elements("descendant::draw:frame")  # type: ignore[return-value]

    def get_frame(
        self,
        position: int = 0,
        name: str | None = None,
        presentation_class: str | None = None,
        title: str | None = None,
        description: str | None = None,
        content: str | None = None,
    ) -> Frame | None:
        """Returns a single frame that matches the specified criteria.

        Args:
            position: The 0-based index of the matching frame to return.
            name: The name of the frame.
            presentation_class: The presentation class to filter frames by.
            title: A regex pattern to match against the frame's title.
            description: A regex pattern to match against the frame's description.
            content: A regex pattern to match against the frame's content.

        Returns:
            Frame | None: A Frame instance, or None if no frame matches the criteria.
        """
        return self._filtered_element(
            "descendant::draw:frame",
            position,
            draw_name=name,
            presentation_class=presentation_class,
            svg_title=title,
            svg_desc=description,
            content=content,
        )  # type: ignore[return-value]

    # Images

    def get_images(
        self,
        style: str | None = None,
        url: str | None = None,
        content: str | None = None,
    ) -> list[DrawImage]:
        """Returns all images that match the specified criteria.

        Args:
            style: The name of the style to filter images by.
            url: A regex pattern to match against the image's URL.
            content: A regex pattern to match against the image's content.

        Returns:
            list[DrawImage]: A list of DrawImage instances matching the criteria.
        """
        return self._filtered_elements(
            "descendant::draw:image", text_style=style, url=url, content=content
        )  # type: ignore[return-value]

    @property
    def images(self) -> list[DrawImage]:
        """Returns all images as a list.

        Returns:
            list[DrawImage]: A list of all DrawImage instances that are descendants of this element.
        """
        return self.get_elements("descendant::draw:image")  # type: ignore[return-value]

    def get_image(
        self,
        position: int = 0,
        name: str | None = None,
        url: str | None = None,
        content: str | None = None,
    ) -> DrawImage | None:
        """Returns a single image that matches the specified criteria.

        Args:
            position: The 0-based index of the matching image to return.
            name: The name of the image (stored in its parent frame).
            url: A regex pattern to match against the image's URL.
            content: A regex pattern to match against the image's content.

        Returns:
            DrawImage | None: A DrawImage instance, or None if no image matches the criteria.
        """
        # The frame is holding the name
        if name is not None:
            frame = self._filtered_element(
                "descendant::draw:frame", position, draw_name=name
            )
            if frame is None:
                return None
            # The name is supposedly unique
            return frame.get_element("draw:image")  # type: ignore[return-value]
        return self._filtered_element(
            "descendant::draw:image", position, url=url, content=content
        )  # type: ignore[return-value]

    # office:names

    def get_office_names(self) -> list[str]:
        """Returns all unique values of 'office:name' attributes within the element's subtree.

        Returns:
            list[str]: A list of unique strings representing the 'office:name' attribute values.
        """
        name_xpath_query = xpath_compile("//@office:name")
        strings = xpath_return_strings(name_xpath_query, self.__element)
        return list({name for name in strings if name})

    # Variables

    def get_variable_sets(self, name: str | None = None) -> list[VarSet]:
        """Returns all variable sets that match the specified criteria.

        Args:
            name: The name of the variable set to filter by.

        Returns:
            list[VarSet]: A list of VarSet instances matching the criteria.
        """
        return self._filtered_elements(
            "descendant::text:variable-set",
            text_name=name,
        )  # type: ignore[return-value]

    def get_variable_set(self, name: str, position: int = -1) -> VarSet | None:
        """Returns a single variable set that matches the specified criteria.

        Args:
            name: The name of the variable set to retrieve.
            position: The 0-based index of the matching variable set to return.
                A negative value (e.g., -1) typically refers to the last one found.

        Returns:
            VarSet | None: A VarSet instance, or None if no variable set matches the criteria.
        """
        return self._filtered_element(
            "descendant::text:variable-set", position, text_name=name
        )  # type: ignore[return-value]

    def get_variable_set_value(
        self,
        name: str,
        value_type: str | None = None,
    ) -> bool | str | int | float | Decimal | datetime | timedelta | None:
        """Returns the value of the last variable set for the given name.

        Args:
            name: The name of the variable to retrieve its value.
            value_type: The expected type of the variable's value.
                Can be 'boolean', 'currency', 'date', 'float', 'percentage',
                'string', 'time', or None for automatic type detection.

        Returns:
            bool | str | int | float | Decimal | datetime | timedelta | None:
                The value of the variable, cast to the most appropriate Python type,
                or None if the variable set is not found.
        """
        variable_set = self.get_variable_set(name)
        if not variable_set:
            return None
        return variable_set.get_value(value_type)  # type: ignore[return-value]

    # Draw Pages

    def get_draw_pages(
        self,
        style: str | None = None,
        content: str | None = None,
    ) -> list[DrawPage]:
        """Returns all draw pages that match the specified criteria.

        Args:
            style: The name of the style to filter draw pages by.
            content: A regex pattern to match against the draw page's content.

        Returns:
            list[DrawPage]: A list of DrawPage instances matching the criteria.
        """
        return self._filtered_elements(
            "descendant::draw:page", draw_style=style, content=content
        )  # type: ignore[return-value]

    def get_draw_page(
        self,
        position: int = 0,
        name: str | None = None,
        content: str | None = None,
    ) -> DrawPage | None:
        """Returns a single draw page that matches the specified criteria.

        Args:
            position: The 0-based index of the matching draw page to return.
            name: The name of the draw page.
            content: A regex pattern to match against the draw page's content.

        Returns:
            DrawPage | None: A DrawPage instance, or None if no draw page matches the criteria.
        """
        return self._filtered_element(
            "descendant::draw:page", position, draw_name=name, content=content
        )  # type: ignore[return-value]

    # Shapes elements

    # Groups

    def get_draw_groups(
        self,
        title: str | None = None,
        description: str | None = None,
        content: str | None = None,
    ) -> list[DrawGroup]:
        """Returns all draw groups that match the specified criteria.

        Args:
            title: A regex pattern to match against the group's title.
            description: A regex pattern to match against the group's description.
            content: A regex pattern to match against the group's content.

        Returns:
            list[DrawGroup]: A list of DrawGroup instances matching the criteria.
        """
        return self._filtered_elements(
            "descendant::draw:g",
            svg_title=title,
            svg_desc=description,
            content=content,
        )  # type: ignore[return-value]

    def get_draw_group(
        self,
        position: int = 0,
        name: str | None = None,
        title: str | None = None,
        description: str | None = None,
        content: str | None = None,
    ) -> DrawGroup | None:
        """Returns a single draw group that matches the specified criteria.

        Args:
            position: The 0-based index of the matching draw group to return.
            name: The name of the draw group.
            title: A regex pattern to match against the group's title.
            description: A regex pattern to match against the group's description.
            content: A regex pattern to match against the group's content.

        Returns:
            DrawGroup | None: A DrawGroup instance, or None if no group matches the criteria.
        """
        return self._filtered_element(
            "descendant::draw:g",
            position,
            draw_name=name,
            svg_title=title,
            svg_desc=description,
            content=content,
        )  # type: ignore[return-value]

    # Lines

    def get_draw_lines(
        self,
        draw_style: str | None = None,
        draw_text_style: str | None = None,
        content: str | None = None,
    ) -> list[LineShape]:
        """Returns all draw lines that match the specified criteria.

        Args:
            draw_style: The name of the draw style to filter lines by.
            draw_text_style: The name of the draw text style to filter lines by.
            content: A regex pattern to match against the line's content.

        Returns:
            list[LineShape]: A list of LineShape instances matching the criteria.
        """
        return self._filtered_elements(
            "descendant::draw:line",
            draw_style=draw_style,
            draw_text_style=draw_text_style,
            content=content,
        )  # type: ignore[return-value]

    def get_draw_line(
        self,
        position: int = 0,
        id: str | None = None,  # noqa:A002
        content: str | None = None,
    ) -> LineShape | None:
        """Returns a single draw line that matches the specified criteria.

        Args:
            position: The 0-based index of the matching draw line to return.
            id: The ID of the draw line.
            content: A regex pattern to match against the line's content.

        Returns:
            LineShape | None: A LineShape instance, or None if no line matches the criteria.
        """
        return self._filtered_element(
            "descendant::draw:line", position, draw_id=id, content=content
        )  # type: ignore[return-value]

    # Rectangles

    def get_draw_rectangles(
        self,
        draw_style: str | None = None,
        draw_text_style: str | None = None,
        content: str | None = None,
    ) -> list[RectangleShape]:
        """Returns all draw rectangles that match the specified criteria.

        Args:
            draw_style: The name of the draw style to filter rectangles by.
            draw_text_style: The name of the draw text style to filter rectangles by.
            content: A regex pattern to match against the rectangle's content.

        Returns:
            list[RectangleShape]: A list of RectangleShape instances matching the criteria.
        """
        return self._filtered_elements(
            "descendant::draw:rect",
            draw_style=draw_style,
            draw_text_style=draw_text_style,
            content=content,
        )  # type: ignore[return-value]

    def get_draw_rectangle(
        self,
        position: int = 0,
        id: str | None = None,  # noqa:A002
        content: str | None = None,
    ) -> RectangleShape | None:
        """Returns a single draw rectangle that matches the specified criteria.

        Args:
            position: The 0-based index of the matching draw rectangle to return.
            id: The ID of the draw rectangle.
            content: A regex pattern to match against the rectangle's content.

        Returns:
            RectangleShape | None: A RectangleShape instance, or None if no rectangle matches the criteria.
        """
        return self._filtered_element(
            "descendant::draw:rect", position, draw_id=id, content=content
        )  # type: ignore[return-value]

    # Ellipse

    def get_draw_ellipses(
        self,
        draw_style: str | None = None,
        draw_text_style: str | None = None,
        content: str | None = None,
    ) -> list[EllipseShape]:
        """Returns all draw ellipses that match the specified criteria.

        Args:
            draw_style: The name of the draw style to filter ellipses by.
            draw_text_style: The name of the draw text style to filter ellipses by.
            content: A regex pattern to match against the ellipse's content.

        Returns:
            list[EllipseShape]: A list of EllipseShape instances matching the criteria.
        """
        return self._filtered_elements(
            "descendant::draw:ellipse",
            draw_style=draw_style,
            draw_text_style=draw_text_style,
            content=content,
        )  # type: ignore[return-value]

    def get_draw_ellipse(
        self,
        position: int = 0,
        id: str | None = None,  # noqa:A002
        content: str | None = None,
    ) -> EllipseShape | None:
        """Returns a single draw ellipse that matches the specified criteria.

        Args:
            position: The 0-based index of the matching draw ellipse to return.
            id: The ID of the draw ellipse.
            content: A regex pattern to match against the ellipse's content.

        Returns:
            EllipseShape | None: An EllipseShape instance, or None if no ellipse matches the criteria.
        """
        return self._filtered_element(
            "descendant::draw:ellipse", position, draw_id=id, content=content
        )  # type: ignore[return-value]

    # Connectors

    def get_draw_connectors(
        self,
        draw_style: str | None = None,
        draw_text_style: str | None = None,
        content: str | None = None,
    ) -> list[ConnectorShape]:
        """Returns all draw connectors that match the specified criteria.

        Args:
            draw_style: The name of the draw style to filter connectors by.
            draw_text_style: The name of the draw text style to filter connectors by.
            content: A regex pattern to match against the connector's content.

        Returns:
            list[ConnectorShape]: A list of ConnectorShape instances matching the criteria.
        """
        return self._filtered_elements(
            "descendant::draw:connector",
            draw_style=draw_style,
            draw_text_style=draw_text_style,
            content=content,
        )  # type: ignore[return-value]

    def get_draw_connector(
        self,
        position: int = 0,
        id: str | None = None,  # noqa:A002
        content: str | None = None,
    ) -> ConnectorShape | None:
        """Returns a single draw connector that matches the specified criteria.

        Args:
            position: The 0-based index of the matching draw connector to return.
            id: The ID of the draw connector.
            content: A regex pattern to match against the connector's content.

        Returns:
            ConnectorShape | None: A ConnectorShape instance, or None if no connector matches the criteria.
        """
        return self._filtered_element(
            "descendant::draw:connector", position, draw_id=id, content=content
        )  # type: ignore[return-value]

    def get_orphan_draw_connectors(self) -> list[ConnectorShape]:
        """Returns a list of connectors that are not connected to any shapes.

        Returns:
            list[ConnectorShape]: A list of ConnectorShape instances that are orphans.
        """
        connectors = []
        for connector in self.get_draw_connectors():
            start_shape = connector.get_attribute("draw:start-shape")
            end_shape = connector.get_attribute("draw:end-shape")
            if start_shape is None and end_shape is None:
                connectors.append(connector)
        return connectors

    # Tracked changes and text change

    def get_changes_ids(self) -> list[Element | EText]:
        """Returns a list of IDs that refer to change regions in the tracked changes list.

        Returns:
            list[Element | EText]: A list of Element or EText instances representing change IDs.
        """
        # Insertion changes or deletion changes
        xpath_query = (
            "descendant::text:change-start/@text:change-id "
            "| descendant::text:change/@text:change-id"
        )
        return self.xpath(xpath_query)

    def get_text_change_deletions(self) -> list[TextChange]:
        """Returns all text changes representing deletions (text:change tags).

        Consider using `get_text_changes()` for a more general approach.

        Returns:
            list[TextChange]: A list of TextChange instances representing deletions.
        """
        return self._filtered_elements(
            "descendant::text:change",
        )  # type: ignore[return-value]

    def get_text_change_deletion(
        self,
        position: int = 0,
        idx: str | None = None,
    ) -> TextChange | None:
        """Returns a single text change of deletion kind (text:change tag) matching criteria.

        Consider using `get_text_change()` for a more general approach.

        Args:
            position: The 0-based index of the matching text:change element to return.
            idx: The `change-id` attribute of the element.

        Returns:
            TextChange | None: A TextChange instance, or None if no match is found.
        """
        return self._filtered_element(
            "descendant::text:change", position, change_id=idx
        )  # type: ignore[return-value]

    def get_text_change_starts(self) -> list[TextChangeStart]:
        """Returns all text change-start elements (text:change-start tags).

        Consider using `get_text_changes()` for a more general approach.

        Returns:
            list[TextChangeStart]: A list of TextChangeStart instances.
        """
        return self._filtered_elements(
            "descendant::text:change-start",
        )  # type: ignore[return-value]

    def get_text_change_start(
        self,
        position: int = 0,
        idx: str | None = None,
    ) -> TextChangeStart | None:
        """Returns a single text change-start element (text:change-start tag) matching criteria.

        Consider using `get_text_change()` for a more general approach.

        Args:
            position: The 0-based index of the matching text:change-start element to return.
            idx: The `change-id` attribute of the element.

        Returns:
            TextChangeStart | None: A TextChangeStart instance, or None if no match is found.
        """
        return self._filtered_element(
            "descendant::text:change-start", position, change_id=idx
        )  # type: ignore[return-value]

    def get_text_change_ends(self) -> list[TextChangeEnd]:
        """Returns all text change-end elements (text:change-end tags).

        Consider using `get_text_changes()` for a more general approach.

        Returns:
            list[TextChangeEnd]: A list of TextChangeEnd instances.
        """
        return self._filtered_elements(
            "descendant::text:change-end",
        )  # type: ignore[return-value]

    def get_text_change_end(
        self,
        position: int = 0,
        idx: str | None = None,
    ) -> TextChangeEnd | None:
        """Returns a single text change-end element (text:change-end tag) matching criteria.

        Consider using `get_text_change()` for a more general approach.

        Args:
            position: The 0-based index of the matching text:change-end element to return.
            idx: The `change-id` attribute of the element.

        Returns:
            TextChangeEnd | None: A TextChangeEnd instance, or None if no match is found.
        """
        return self._filtered_element(
            "descendant::text:change-end", position, change_id=idx
        )  # type: ignore[return-value]

    def get_text_changes(self) -> list[TextChange | TextChangeStart]:
        """Returns all text changes, including single deletions (text:change) and
        starts of change ranges (text:change-start).

        Returns:
            list[TextChange | TextChangeStart]: A list of TextChange or TextChangeStart instances.
        """
        request = "descendant::text:change-start | descendant::text:change"
        return self._filtered_elements(request)  # type: ignore[return-value]

    @property
    def text_changes(self) -> list[TextChange | TextChangeStart]:
        """Returns all text changes, including single deletions (text:change) and
        starts of change ranges (text:change-start).

        Returns:
            list[TextChange | TextChangeStart]: A list of TextChange or TextChangeStart instances.
        """
        return self.get_text_changes()

    def get_text_change(
        self,
        position: int = 0,
        idx: str | None = None,
    ) -> TextChange | TextChangeStart | None:
        """Returns a single text change that matches the specified criteria.

        The change can be either a single deletion (text:change) or the start
        of a range of changes (text:change-start).

        Args:
            position: The 0-based index of the element to retrieve if
                several matches are found. Defaults to 0.
            idx: The `change-id` attribute of the element to match.

        Returns:
            TextChange | TextChangeStart | None: A TextChange or TextChangeStart
                instance, or None if no match is found.
        """
        if idx:
            request = (
                f'descendant::text:change-start[@text:change-id="{idx}"] '
                f'| descendant::text:change[@text:change-id="{idx}"]'
            )
            return self._filtered_element(request, 0)  # type: ignore[return-value]

        request = "descendant::text:change-start | descendant::text:change"
        return self._filtered_element(request, position)  # type: ignore[return-value]

    # Styles

    @staticmethod
    def _get_style_tagname(family: str | None, is_default: bool = False) -> str:
        """Determines the appropriate ODF tag name for a given style family.

        Args:
            family: The style family (e.g., "paragraph", "text").
            is_default: If True, specifically look for default styles.

        Returns:
            str: The ODF tag name(s) to match for the given style family.
        """
        tagname: str
        if not family:
            # here is a problem: to retrive actual styles we sould use this:
            #   tagname = "style:default-style|*[@style:name]"
            # however, background images are usually considered as styles too
            tagname = "(style:default-style|*[@style:name]|draw:fill-image|draw:marker)"
        elif is_default:
            # Default style
            tagname = "style:default-style"
        else:
            # This calls _family_style_tagname, which can raise ValueError
            # If it does, the exception will propagate from here.
            tagname = _family_style_tagname(family)
            if family in FAMILY_ODF_STD:
                tagname = f"({tagname}|style:default-style)"
        return tagname

    def get_styles(
        self, family: str | None = None
    ) -> list[StyleBase | DrawFillImage | DrawMarker]:
        """Returns all styles (common and default) that match the specified family.

        Args:
            family: The style family to filter by (e.g., "paragraph", "text").
                If None, retrieves all styles regardless of family.

        Returns:
            list[StyleBase|DrawFillImage|DrawMarker]: A list of style-like
            instances matching the criteria.
        """
        # Both common and default styles
        tagname = self._get_style_tagname(family)
        return self._filtered_elements(tagname, family=family)  # type: ignore[return-value]

    def get_style(
        self,
        family: str,
        name_or_element: str | Element | None = None,
        display_name: str | None = None,
    ) -> StyleBase | DrawFillImage | DrawMarker | None:
        """Returns a single style uniquely identified by family/name, or a
        provided style object.

        If the provided `name_or_element` is already a style object, it is
        returned directly. Use `display_name` if the style is known by its
        user-facing name instead of its internal name.

        Args:
            family: The style family (e.g., "paragraph", "text", "graphic",
                "table", "list", "number").
            name_or_element: The internal name of the style, or
                an existing Style (or subclass) instance.
            display_name: The user-facing name of the style.

        Returns:
            StyleBase | DrawFillImage | DrawMarker | None: A style-like
                instance, or None if no matching style is found.

        Raises:
            ValueError: If `name_or_element` is an Element but not a
                recognized odf_style.
        """
        if isinstance(name_or_element, Element):
            name = name_or_element.get_attribute("style:name")
            if name is not None:
                return name_or_element  # type: ignore[return-value]
            else:
                raise ValueError(f"Not a odf_style ? {name_or_element!r}")
        style_name = name_or_element
        is_default = not (style_name or display_name)
        tagname = self._get_style_tagname(family, is_default=is_default)
        # famattr became None if no "style:family" attribute
        if family:
            return self._filtered_element(
                tagname,
                0,
                style_name=style_name,
                display_name=display_name,
                family=family,
            )  # type: ignore[return-value]
        # family is empty
        if style_name:
            result = self._filtered_element(tagname, 0, style_name=style_name)
            if result:
                return result  # type: ignore[return-value]
            return self._filtered_element(tagname, 0, draw_name=style_name)  # type: ignore[return-value]

        if display_name:
            return self._filtered_element(tagname, 0, display_name=display_name)  # type: ignore[return-value]

        return self._filtered_element(tagname, 0)  # type: ignore[return-value]

    def _filtered_element(
        self,
        query_string: str,
        position: int,
        **kwargs: Any,
    ) -> Element | None:
        """Returns a single filtered element at a specific position.

        Args:
            query_string: The XPath query string to apply.
            position: The 0-based index of the desired element from the filtered
                results.
            **kwargs: Additional keyword arguments to pass to `_filtered_elements`
                for filtering criteria.

        Returns:
            Element | None: The Element instance at the specified position, or None
                if not found.
        """
        results = self._filtered_elements(query_string, **kwargs)
        try:
            return results[position]
        except IndexError:
            return None

    def _filtered_elements(
        self,
        query_string: str,
        content: str | None = None,
        url: str | None = None,
        svg_title: str | None = None,
        svg_desc: str | None = None,
        dc_creator: str | None = None,
        dc_date: datetime | None = None,
        **kwargs: Any,
    ) -> list[Element]:
        """Returns a list of elements filtered by various criteria.

        This internal method applies an XPath query first and then further
        filters the results based on content, URL, SVG title/description,
        Dublin Core creator/date, and other keyword arguments.

        Args:
            query_string: The initial XPath query string to select elements.
            content: A regex pattern to match against the element's text content.
            url: A regex pattern to match against the `xlink:href` attribute.
            svg_title: A regex pattern to match against an inner `svg:title` element.
            svg_desc: A regex pattern to match against an inner `svg:desc` element.
            dc_creator: A regex pattern to match against an inner `dc:creator` element.
            dc_date: A datetime object to match against an inner `dc:date` element.
            **kwargs: Additional keyword arguments representing attribute filters
                (e.g., `text_style="MyStyle"`, `draw_name="MyDraw"`, etc.).

        Returns:
            list[Element]: A list of Element instances that match all specified criteria.
        """
        query = make_xpath_query(query_string, **kwargs)
        elements = self.get_elements(query)
        # Filter the elements with the regex (TODO use XPath)
        if content is not None:
            elements = [element for element in elements if element.match(content)]
        if url is not None:
            filtered = []
            for element in elements:
                url_attr = element.get_attribute("xlink:href")
                if isinstance(url_attr, str) and search(url, url_attr) is not None:
                    filtered.append(element)
            elements = filtered
        if dc_date is None:
            dt_dc_date = None
        else:
            dt_dc_date = DateTime.encode(dc_date)
        for variable, childname in [
            (svg_title, "svg:title"),
            (svg_desc, "svg:desc"),
            (dc_creator, "descendant::dc:creator"),
            (dt_dc_date, "descendant::dc:date"),
        ]:
            if not variable:
                continue
            filtered = []
            for element in elements:
                child = element.get_element(childname)
                if child and child.match(variable):
                    filtered.append(element)
            elements = filtered
        return elements

__element instance-attribute

__element = _make_etree_element(tag)

_do_init instance-attribute

_do_init = True

_properties class-attribute instance-attribute

_properties: tuple[PropDef | PropDefBool, ...] = ()

_tag class-attribute instance-attribute

_tag: str = ''

_text_tail property

_text_tail: str

Returns the concatenated inner text and tail of the element.

Returns:

Name Type Description
str str

The string representation of the element’s inner text plus its tail.

_xml_element property

_xml_element: _Element

Returns the underlying lxml.etree._Element object.

Returns:

Name Type Description
_Element _Element

The raw lxml element.

append class-attribute instance-attribute

append = __append

attributes property

attributes: dict[str, str]

Gets all attributes of the element as a dictionary.

The keys are qualified attribute names (e.g., “office:name”), and the values are their string representations.

Returns:

Type Description
dict[str, str]

dict[str, str]: A dictionary of attribute names and their values.

children property

children: list[Element]

Returns a list of immediate child elements.

Returns:

Type Description
list[Element]

list[Element]: A list of Element instances representing the direct children.

clone property

clone: Element

Creates a deep copy of the current element.

Returns:

Name Type Description
Element Element

A new Element instance that is a deep copy of the original.

document_body property

document_body: Body | None

Returns the first child of the document body, if any.

This typically corresponds to the main content area of an ODF document.

Returns:

Type Description
Body | None

Body | None: The first child Element of office:body, or None if not found.

frames property

frames: list[Frame]

Returns all frames as a list.

Returns:

Type Description
list[Frame]

list[Frame]: A list of all Frame instances that are descendants of this element.

headers property

headers: list[Header]

Returns all headers as a list.

Returns:

Type Description
list[Header]

list[Header]: A list of all Header instances that are descendants of this element.

images property

images: list[DrawImage]

Returns all images as a list.

Returns:

Type Description
list[DrawImage]

list[DrawImage]: A list of all DrawImage instances that are descendants of this element.

inner_text property

inner_text: str

Returns the concatenated text content of the element and its children (excluding its own tail).

Returns:

Name Type Description
str str

The inner text of the element.

is_bound property

is_bound: bool

Checks if the element is currently part of an XML tree (has a parent).

Returns:

Name Type Description
bool bool

True if the element has a parent, False otherwise.

paragraphs property

paragraphs: list[Paragraph]

Returns all paragraphs as a list.

Returns:

Type Description
list[Paragraph]

list[Paragraph]: A list of all Paragraph instances that are descendants of this element.

parent property

parent: Element | None

Returns the parent element of this element.

Returns:

Type Description
Element | None

Element | None: The parent Element instance, or None if this element is the root.

root property

root: Element

Returns the root element of the XML tree containing this element.

Returns:

Name Type Description
Element Element

The root Element instance.

spans property

spans: list[Span]

Returns all spans as a list.

Returns:

Type Description
list[Span]

list[Span]: A list of all Span instances that are descendants of this element.

tag property writable

tag: str

Gets the underlying XML tag with the qualified name.

Returns:

Name Type Description
str str

The qualified name of the XML tag (e.g., “text:span”).

tail property writable

tail: str | None

Gets the text immediately following the element.

Returns:

Type Description
str | None

str | None: The tail text, or None if no tail text is present.

text property writable

text: str

Gets the text content of the element.

Returns:

Name Type Description
str str

The text content of the element. Defaults to an empty string if no text is present.

text_changes property

text_changes: list[TextChange | TextChangeStart]

Returns all text changes, including single deletions (text:change) and starts of change ranges (text:change-start).

Returns:

Type Description
list[TextChange | TextChangeStart]

list[TextChange | TextChangeStart]: A list of TextChange or TextChangeStart instances.

text_content property writable

text_content: str

Gets the text content of embedded paragraphs, including annotations and cells.

Returns:

Name Type Description
str str

The concatenated text content of all embedded paragraphs.

text_recursive property

text_recursive: str

Returns the full recursive text content of the element, including its own tail.

Returns:

Name Type Description
str str

The entire text content, recursively.

__append

__append(str_or_element: str | Element) -> None

Appends an element or text to the end of the current element.

If str_or_element is a string, it is appended as text. If it is an Element, its underlying XML element is appended.

Parameters:

Name Type Description Default
str_or_element str | Element

The string or Element to append.

required

Raises:

Type Description
TypeError

If the provided argument is neither a string nor an Element.

Source code in odfdo/element.py
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
def __append(self, str_or_element: str | Element) -> None:
    """Appends an element or text to the end of the current element.

    If `str_or_element` is a string, it is appended as text. If it is an
    `Element`, its underlying XML element is appended.

    Args:
        str_or_element: The string or Element to append.

    Raises:
        TypeError: If the provided argument is neither a string nor an Element.
    """

    def _add_text(text1: str | None, text2: str | None) -> str:
        return _re_anyspace.sub(" ", (text1 or "") + (text2 or ""))

    current = self.__element
    if isinstance(str_or_element, str):
        # Has children ?
        children = list(current.iterchildren())
        if children:
            # Append to tail of the last child
            last_child = children[-1]
            last_child.tail = _add_text(last_child.tail, str_or_element)
        else:
            # Append to text of the element
            current.text = _add_text(current.text, str_or_element)
    elif isinstance(str_or_element, Element):
        current.append(str_or_element.__element)
    else:
        raise TypeError(f'Element or string expected, not "{type(str_or_element)}"')

__init__

__init__(**kwargs: Any) -> None

Initialize an Element instance.

This constructor can be used to create a new ODF element from scratch or to wrap an existing lxml.etree._Element object.

Parameters:

Name Type Description Default
**kwargs Any
  • tag_or_elem (str | lxml.etree._Element, optional): An existing lxml element to wrap, or an ODF tag string (e.g., “text:p”) to create a new element. If not provided, a new element is created based on the class’s _tag attribute.
  • tag (str, optional): The ODF tag string to use when creating a new element, if tag_or_elem is not provided. Defaults to _tag of the class.
{}

Raises:

Type Description
TypeError

If tag_or_elem is provided but is not an _Element instance.

Source code in odfdo/element.py
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
def __init__(self, **kwargs: Any) -> None:
    """Initialize an Element instance.

    This constructor can be used to create a new ODF element from scratch
    or to wrap an existing `lxml.etree._Element` object.

    Args:
        **kwargs (Any):
            - tag_or_elem (str | lxml.etree._Element, optional): An existing
              lxml element to wrap, or an ODF tag string (e.g., "text:p")
              to create a new element. If not provided, a new element is
              created based on the class's `_tag` attribute.
            - tag (str, optional): The ODF tag string to use when creating a
              new element, if `tag_or_elem` is not provided. Defaults to
              `_tag` of the class.

    Raises:
        TypeError: If `tag_or_elem` is provided but is not an `_Element` instance.
    """
    tag_or_elem = kwargs.pop("tag_or_elem", None)
    if tag_or_elem is None:
        # Instance for newly created object: create new lxml element and
        # continue by subclass __init__
        # If the tag key word exists, make a custom element
        self._do_init = True
        tag = kwargs.pop("tag", self._tag)
        self.__element = self._make_etree_element(tag)
    else:
        # called with an existing lxml element, sould be a result of
        # from_tag() casting, do not execute the subclass __init__
        if not isinstance(tag_or_elem, _Element):
            raise TypeError(f'"{type(tag_or_elem)}" is not an element node')
        self._do_init = False
        self.__element = tag_or_elem

__repr__

__repr__() -> str
Source code in odfdo/element.py
526
527
def __repr__(self) -> str:
    return f"<{self.__class__.__name__} tag={self.tag}>"

__str__

__str__() -> str
Source code in odfdo/element.py
1472
1473
def __str__(self) -> str:
    return self.inner_text

_base_attrib_getter

_base_attrib_getter(attr_name: str) -> str | None

Internal method to get the value of an attribute by its qualified name.

Parameters:

Name Type Description Default
attr_name str

The qualified name of the attribute (e.g., “office:name”).

required

Returns:

Type Description
str | None

str | None: The attribute’s value as a string, or None if the attribute is not found.

Source code in odfdo/element.py
614
615
616
617
618
619
620
621
622
623
624
625
626
def _base_attrib_getter(self, attr_name: str) -> str | None:
    """Internal method to get the value of an attribute by its qualified name.

    Args:
        attr_name: The qualified name of the attribute (e.g., "office:name").

    Returns:
        str | None: The attribute's value as a string, or None if the attribute is not found.
    """
    value = self.__element.get(_get_lxml_tag(attr_name))
    if value is None:
        return None
    return str(value)

_base_attrib_setter

_base_attrib_setter(
    attr_name: str, value: str | int | float | bool | None
) -> None

Internal method to set the value of an attribute by its qualified name.

Parameters:

Name Type Description Default
attr_name str

The qualified name of the attribute (e.g., “office:name”).

required
value str | int | float | bool | None

The value to set for the attribute. If None, the attribute is removed. Boolean values are encoded.

required
Source code in odfdo/element.py
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
def _base_attrib_setter(
    self,
    attr_name: str,
    value: str | int | float | bool | None,
) -> None:
    """Internal method to set the value of an attribute by its qualified name.

    Args:
        attr_name: The qualified name of the attribute (e.g., "office:name").
        value: The value to set for the attribute. If None, the attribute
            is removed. Boolean values are encoded.
    """
    if value is None:
        with contextlib.suppress(KeyError):
            del self.__element.attrib[_get_lxml_tag(attr_name)]
        return
    if isinstance(value, bool):
        value = Boolean.encode(value)
    self.__element.set(_get_lxml_tag(attr_name), str(value))

_boolean_attrib_getter staticmethod

_boolean_attrib_getter(prop: PropDefBool) -> Callable

Creates a getter function for a boolean attribute.

Parameters:

Name Type Description Default
prop PropDefBool

A NamedTuple defining the boolean property.

required

Returns:

Name Type Description
Callable Callable

A getter function that takes an Element instance and returns the boolean value of the attribute, or its default.

Source code in odfdo/element.py
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
@staticmethod
def _boolean_attrib_getter(prop: PropDefBool) -> Callable:
    """Creates a getter function for a boolean attribute.

    Args:
        prop: A NamedTuple defining the boolean property.

    Returns:
        Callable: A getter function that takes an Element instance and returns
            the boolean value of the attribute, or its default.
    """

    def getter(self: Element) -> bool:
        return self._get_attribute_bool_default(prop.attr, prop.default)

    return getter

_boolean_attrib_setter staticmethod

_boolean_attrib_setter(prop: PropDefBool) -> Callable

Creates a setter function for a boolean attribute.

Parameters:

Name Type Description Default
prop PropDefBool

A NamedTuple defining the boolean property.

required

Returns:

Name Type Description
Callable Callable

A setter function that takes an Element instance and the boolean value to set for the attribute.

Source code in odfdo/element.py
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
@staticmethod
def _boolean_attrib_setter(prop: PropDefBool) -> Callable:
    """Creates a setter function for a boolean attribute.

    Args:
        prop: A NamedTuple defining the boolean property.

    Returns:
        Callable: A setter function that takes an Element instance and the boolean
            value to set for the attribute.
    """

    def setter(self: Element, value: bool) -> None:
        self._set_attribute_bool_default(prop.attr, value, prop.default)

    return setter

_canonicalize

_canonicalize() -> str

(Internal) Returns a canonical representation of the Element (C14N2), with namespaces stripped.

Used in the test suite.

Returns:

Name Type Description
str str

The normalized XML content as a string.

Source code in odfdo/element.py
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
def _canonicalize(self) -> str:
    """(Internal) Returns a canonical representation of the Element
    (C14N2), with namespaces stripped.

    Used in the test suite.

    Returns:
        str: The normalized XML content as a string.
    """
    return self._strip_namespaces(
        canonicalize(tostring(self.__element, with_tail=False))
    )

_copy_cache

_copy_cache(cache: tuple) -> None

Copies cache data to the element.

This method is intended to be redefined by subclasses that utilize caching.

Parameters:

Name Type Description Default
cache tuple

The cache data to be copied.

required
Source code in odfdo/element.py
576
577
578
579
580
581
582
583
584
def _copy_cache(self, cache: tuple) -> None:
    """Copies cache data to the element.

    This method is intended to be redefined by subclasses that utilize caching.

    Args:
        cache: The cache data to be copied.
    """
    pass

_define_attribut_property classmethod

_define_attribut_property() -> None

Dynamically defines properties for the class based on _properties.

This method iterates through the _properties tuple of the class and creates corresponding getter and setter properties for XML attributes.

Source code in odfdo/element.py
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
@classmethod
def _define_attribut_property(cls: type[Element]) -> None:
    """Dynamically defines properties for the class based on `_properties`.

    This method iterates through the `_properties` tuple of the class and
    creates corresponding getter and setter properties for XML attributes.
    """
    for prop in cls._properties:
        if isinstance(prop, PropDef):
            setattr(
                cls,
                prop.name,
                property(
                    cls._generic_attrib_getter(prop.attr, prop.family or None),
                    cls._generic_attrib_setter(prop.attr, prop.family or None),
                    None,
                    f"Get/set the attribute {prop.attr}",
                ),
            )
        else:
            setattr(
                cls,
                prop.name,
                property(
                    cls._boolean_attrib_getter(prop),
                    cls._boolean_attrib_setter(prop),
                    None,
                    f"Get/set the attribute {prop.attr}",
                ),
            )

_filtered_element

_filtered_element(
    query_string: str, position: int, **kwargs: Any
) -> Element | None

Returns a single filtered element at a specific position.

Parameters:

Name Type Description Default
query_string str

The XPath query string to apply.

required
position int

The 0-based index of the desired element from the filtered results.

required
**kwargs Any

Additional keyword arguments to pass to _filtered_elements for filtering criteria.

{}

Returns:

Type Description
Element | None

Element | None: The Element instance at the specified position, or None if not found.

Source code in odfdo/element.py
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
def _filtered_element(
    self,
    query_string: str,
    position: int,
    **kwargs: Any,
) -> Element | None:
    """Returns a single filtered element at a specific position.

    Args:
        query_string: The XPath query string to apply.
        position: The 0-based index of the desired element from the filtered
            results.
        **kwargs: Additional keyword arguments to pass to `_filtered_elements`
            for filtering criteria.

    Returns:
        Element | None: The Element instance at the specified position, or None
            if not found.
    """
    results = self._filtered_elements(query_string, **kwargs)
    try:
        return results[position]
    except IndexError:
        return None

_filtered_elements

_filtered_elements(
    query_string: str,
    content: str | None = None,
    url: str | None = None,
    svg_title: str | None = None,
    svg_desc: str | None = None,
    dc_creator: str | None = None,
    dc_date: datetime | None = None,
    **kwargs: Any,
) -> list[Element]

Returns a list of elements filtered by various criteria.

This internal method applies an XPath query first and then further filters the results based on content, URL, SVG title/description, Dublin Core creator/date, and other keyword arguments.

Parameters:

Name Type Description Default
query_string str

The initial XPath query string to select elements.

required
content str | None

A regex pattern to match against the element’s text content.

None
url str | None

A regex pattern to match against the xlink:href attribute.

None
svg_title str | None

A regex pattern to match against an inner svg:title element.

None
svg_desc str | None

A regex pattern to match against an inner svg:desc element.

None
dc_creator str | None

A regex pattern to match against an inner dc:creator element.

None
dc_date datetime | None

A datetime object to match against an inner dc:date element.

None
**kwargs Any

Additional keyword arguments representing attribute filters (e.g., text_style="MyStyle", draw_name="MyDraw", etc.).

{}

Returns:

Type Description
list[Element]

list[Element]: A list of Element instances that match all specified criteria.

Source code in odfdo/element.py
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
def _filtered_elements(
    self,
    query_string: str,
    content: str | None = None,
    url: str | None = None,
    svg_title: str | None = None,
    svg_desc: str | None = None,
    dc_creator: str | None = None,
    dc_date: datetime | None = None,
    **kwargs: Any,
) -> list[Element]:
    """Returns a list of elements filtered by various criteria.

    This internal method applies an XPath query first and then further
    filters the results based on content, URL, SVG title/description,
    Dublin Core creator/date, and other keyword arguments.

    Args:
        query_string: The initial XPath query string to select elements.
        content: A regex pattern to match against the element's text content.
        url: A regex pattern to match against the `xlink:href` attribute.
        svg_title: A regex pattern to match against an inner `svg:title` element.
        svg_desc: A regex pattern to match against an inner `svg:desc` element.
        dc_creator: A regex pattern to match against an inner `dc:creator` element.
        dc_date: A datetime object to match against an inner `dc:date` element.
        **kwargs: Additional keyword arguments representing attribute filters
            (e.g., `text_style="MyStyle"`, `draw_name="MyDraw"`, etc.).

    Returns:
        list[Element]: A list of Element instances that match all specified criteria.
    """
    query = make_xpath_query(query_string, **kwargs)
    elements = self.get_elements(query)
    # Filter the elements with the regex (TODO use XPath)
    if content is not None:
        elements = [element for element in elements if element.match(content)]
    if url is not None:
        filtered = []
        for element in elements:
            url_attr = element.get_attribute("xlink:href")
            if isinstance(url_attr, str) and search(url, url_attr) is not None:
                filtered.append(element)
        elements = filtered
    if dc_date is None:
        dt_dc_date = None
    else:
        dt_dc_date = DateTime.encode(dc_date)
    for variable, childname in [
        (svg_title, "svg:title"),
        (svg_desc, "svg:desc"),
        (dc_creator, "descendant::dc:creator"),
        (dt_dc_date, "descendant::dc:date"),
    ]:
        if not variable:
            continue
        filtered = []
        for element in elements:
            child = element.get_element(childname)
            if child and child.match(variable):
                filtered.append(element)
        elements = filtered
    return elements

_generic_attrib_getter staticmethod

_generic_attrib_getter(
    attr_name: str, family: str | None = None
) -> Callable

Creates a getter function for a generic attribute.

Parameters:

Name Type Description Default
attr_name str

The qualified name of the attribute.

required
family str | None

Optional family name to filter by.

None

Returns:

Name Type Description
Callable Callable

A getter function that takes an Element instance and returns the attribute’s value as a string, boolean, or None.

Source code in odfdo/element.py
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
@staticmethod
def _generic_attrib_getter(attr_name: str, family: str | None = None) -> Callable:
    """Creates a getter function for a generic attribute.

    Args:
        attr_name: The qualified name of the attribute.
        family: Optional family name to filter by.

    Returns:
        Callable: A getter function that takes an Element instance and returns
            the attribute's value as a string, boolean, or None.
    """

    def getter(self: Element) -> str | bool | None:
        try:
            if family and self.family != family:  # type: ignore
                return None
        except AttributeError:
            return None
        value = self._base_attrib_getter(attr_name)
        if value is None:
            return None
        elif value in ("true", "false"):
            return Boolean.decode(value)
        return value

    return getter

_generic_attrib_setter staticmethod

_generic_attrib_setter(
    attr_name: str, family: str | None = None
) -> Callable

Creates a setter function for a generic attribute.

Parameters:

Name Type Description Default
attr_name str

The qualified name of the attribute.

required
family str | None

Optional family name to filter by.

None

Returns:

Name Type Description
Callable Callable

A setter function that takes an Element instance and the value to set for the attribute.

Source code in odfdo/element.py
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
@staticmethod
def _generic_attrib_setter(attr_name: str, family: str | None = None) -> Callable:
    """Creates a setter function for a generic attribute.

    Args:
        attr_name: The qualified name of the attribute.
        family: Optional family name to filter by.

    Returns:
        Callable: A setter function that takes an Element instance and the value
            to set for the attribute.
    """

    def setter(self: Element, value: Any) -> None:
        try:
            if family and self.family != family:  # type: ignore
                return None
        except AttributeError:
            return None
        self._base_attrib_setter(attr_name, value)

    return setter

_get_attribute_bool_default

_get_attribute_bool_default(
    name: str, default: bool = True
) -> bool

Returns the value of a specified boolean attribute, using a default if not present.

Parameters:

Name Type Description Default
name str

The qualified name of the attribute to retrieve.

required
default bool

The default boolean value to return if the attribute is not found.

True

Returns:

Name Type Description
bool bool

The attribute’s boolean value or the provided default value.

Source code in odfdo/element.py
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
def _get_attribute_bool_default(self, name: str, default: bool = True) -> bool:
    """Returns the value of a specified boolean attribute, using a default if not present.

    Args:
        name: The qualified name of the attribute to retrieve.
        default: The default boolean value to return if the attribute is not found.

    Returns:
        bool: The attribute's boolean value or the provided default value.
    """
    element = self.__element
    lxml_tag = _get_lxml_tag_or_name(name)
    value = element.get(lxml_tag)
    if value is None:
        return default
    return Boolean.decode(value)

_get_attribute_int_default

_get_attribute_int_default(name: str, default: int) -> int

Returns the value of a specified integer attribute, using a default if not present.

Parameters:

Name Type Description Default
name str

The qualified name of the attribute to retrieve.

required
default int

The default integer value to return if the attribute is not found or cannot be converted.

required

Returns:

Name Type Description
int int

The attribute’s integer value or the provided default value.

Source code in odfdo/element.py
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
def _get_attribute_int_default(self, name: str, default: int) -> int:
    """Returns the value of a specified integer attribute, using a default if not present.

    Args:
        name: The qualified name of the attribute to retrieve.
        default: The default integer value to return if the attribute is not found
            or cannot be converted.

    Returns:
        int: The attribute's integer value or the provided default value.
    """
    element = self.__element
    lxml_tag = _get_lxml_tag_or_name(name)
    value = element.get(lxml_tag)
    if value is None:
        return default
    try:
        return int(value)
    except ValueError:
        return default

_get_attribute_str_default

_get_attribute_str_default(
    name: str, default: str = ""
) -> str

Returns the value of a specified string attribute, using a default if not present.

Parameters:

Name Type Description Default
name str

The qualified name of the attribute to retrieve.

required
default str

The default string value to return if the attribute is not found.

''

Returns:

Name Type Description
str str

The attribute’s string value or the provided default value.

Source code in odfdo/element.py
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
def _get_attribute_str_default(self, name: str, default: str = "") -> str:
    """Returns the value of a specified string attribute, using a default if not present.

    Args:
        name: The qualified name of the attribute to retrieve.
        default: The default string value to return if the attribute is not found.

    Returns:
        str: The attribute's string value or the provided default value.
    """
    element = self.__element
    lxml_tag = _get_lxml_tag_or_name(name)
    value = element.get(lxml_tag)
    if value is None:
        return default
    return str(value)

_get_element_idx

_get_element_idx(
    xpath_query: XPath | str, idx: int
) -> Element | None

Returns the element at a specific index from an XPath query result.

Parameters:

Name Type Description Default
xpath_query XPath | str

The XPath query string or a compiled lxml.etree.XPath object.

required
idx int

The 0-based index of the desired element in the query result.

required

Returns:

Type Description
Element | None

Element | None: The Element instance at the specified index, or None if not found.

Source code in odfdo/element.py
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
def _get_element_idx(self, xpath_query: XPath | str, idx: int) -> Element | None:
    """Returns the element at a specific index from an XPath query result.

    Args:
        xpath_query: The XPath query string or a compiled `lxml.etree.XPath` object.
        idx: The 0-based index of the desired element in the query result.

    Returns:
        Element | None: The Element instance at the specified index, or None if not found.
    """
    result = self.__element.xpath(
        f"({xpath_query})[{idx + 1}]", namespaces=ODF_NAMESPACES
    )
    if result:
        return Element.from_tag(result[0])
    return None

_get_element_idx2

_get_element_idx2(
    xpath_instance: XPath, idx: int
) -> Element | None

Returns the element at a specific index using a pre-compiled XPath instance.

Parameters:

Name Type Description Default
xpath_instance XPath

A compiled lxml.etree.XPath object.

required
idx int

The 0-based index of the desired element in the query result.

required

Returns:

Type Description
Element | None

Element | None: The Element instance at the specified index, or None if not found.

Source code in odfdo/element.py
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
def _get_element_idx2(self, xpath_instance: XPath, idx: int) -> Element | None:
    """Returns the element at a specific index using a pre-compiled XPath instance.

    Args:
        xpath_instance: A compiled `lxml.etree.XPath` object.
        idx: The 0-based index of the desired element in the query result.

    Returns:
        Element | None: The Element instance at the specified index, or None if not found.
    """
    result = xpath_instance(self.__element, idx=idx + 1)
    if result:
        return Element.from_tag(result[0])
    return None

_get_inner_text

_get_inner_text(tag: str) -> str | None

Retrieves the text content of a specified inner element.

Parameters:

Name Type Description Default
tag str

The qualified name of the inner element (e.g., “svg:title”).

required

Returns:

Type Description
str | None

str | None: The text content of the inner element, or None if the element is not found.

Source code in odfdo/element.py
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
def _get_inner_text(self, tag: str) -> str | None:
    """Retrieves the text content of a specified inner element.

    Args:
        tag: The qualified name of the inner element (e.g., "svg:title").

    Returns:
        str | None: The text content of the inner element, or None if the element is not found.
    """
    element = self.get_element(tag)
    if element is None:
        return None
    return element.text

_get_style_tagname staticmethod

_get_style_tagname(
    family: str | None, is_default: bool = False
) -> str

Determines the appropriate ODF tag name for a given style family.

Parameters:

Name Type Description Default
family str | None

The style family (e.g., “paragraph”, “text”).

required
is_default bool

If True, specifically look for default styles.

False

Returns:

Name Type Description
str str

The ODF tag name(s) to match for the given style family.

Source code in odfdo/element.py
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
@staticmethod
def _get_style_tagname(family: str | None, is_default: bool = False) -> str:
    """Determines the appropriate ODF tag name for a given style family.

    Args:
        family: The style family (e.g., "paragraph", "text").
        is_default: If True, specifically look for default styles.

    Returns:
        str: The ODF tag name(s) to match for the given style family.
    """
    tagname: str
    if not family:
        # here is a problem: to retrive actual styles we sould use this:
        #   tagname = "style:default-style|*[@style:name]"
        # however, background images are usually considered as styles too
        tagname = "(style:default-style|*[@style:name]|draw:fill-image|draw:marker)"
    elif is_default:
        # Default style
        tagname = "style:default-style"
    else:
        # This calls _family_style_tagname, which can raise ValueError
        # If it does, the exception will propagate from here.
        tagname = _family_style_tagname(family)
        if family in FAMILY_ODF_STD:
            tagname = f"({tagname}|style:default-style)"
    return tagname

_insert

_insert(
    element: Element,
    before: str | None = None,
    after: str | None = None,
    position: int = 0,
) -> None

Insert an element before or after characters matching a regex.

When the regex matches multiple parts of the text, position can specify which part to use. If both before and after are None, position refers to the character index. A positive position inserts before that character; position=-1 inserts after the last character. Annotation text content is ignored.

Parameters:

Name Type Description Default
element Element

The element to insert.

required
before str | None

A regex pattern. The element will be inserted before the text matching this pattern.

None
after str | None

A regex pattern. The element will be inserted after the text matching this pattern.

None
position int

The 0-based index of the regex match to consider, or a character position if before and after are None.

0

Raises:

Type Description
ValueError

If an invalid combination of arguments is provided.

Source code in odfdo/element.py
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
def _insert(
    self,
    element: Element,
    before: str | None = None,
    after: str | None = None,
    position: int = 0,
) -> None:
    """Insert an element before or after characters matching a regex.

    When the regex matches multiple parts of the text, `position` can specify
    which part to use. If both `before` and `after` are None, `position`
    refers to the character index. A positive `position` inserts before that
    character; `position=-1` inserts after the last character.
    Annotation text content is ignored.

    Args:
        element: The element to insert.
        before: A regex pattern. The element will be inserted
            before the text matching this pattern.
        after: A regex pattern. The element will be inserted
            after the text matching this pattern.
        position: The 0-based index of the regex match to consider,
            or a character position if `before` and `after` are None.

    Raises:
        ValueError: If an invalid combination of arguments is provided.
    """
    current = self.__element
    xelement = element.__element

    # 1) before xor after is not None
    if (before is not None) ^ (after is not None):
        pos, text = self._insert_before_after(
            current,
            xelement,
            before,
            after,
            position,
            _xpath_text_descendant_no_annotation,
        )
    # 2) before=after=None => only with position
    elif before is None and after is None:
        # Hack if position is negative => quickly
        if position < 0:
            current.append(xelement)
            return
        pos, text = self._insert_find_text(
            current,
            xelement,
            before,
            after,
            position,
            _xpath_text_descendant_no_annotation,
        )
    else:
        raise ValueError("bad combination of arguments")

    # Compute new texts
    text_before = text[:pos] if text[:pos] else None
    text_after = text[pos:] if text[pos:] else None

    # Insert!
    parent = text.getparent()  # type: ignore
    if text.is_text:  # type: ignore
        parent.text = text_before
        element.tail = text_after
        parent.insert(0, xelement)
    else:
        parent.addnext(xelement)
        parent.tail = text_before
        element.tail = text_after

_insert_before_after

_insert_before_after(
    current: _Element,
    element: _Element,
    before: str | None,
    after: str | None,
    position: int,
    xpath_text: XPath,
) -> tuple[int, str]

Calculates the insertion position based on ‘before’ or ‘after’ regex.

Parameters:

Name Type Description Default
current _Element

The current lxml element.

required
element _Element

The element to be inserted.

required
before str | None

Regex pattern to find position before.

required
after str | None

Regex pattern to find position after.

required
position int

The occurrence of the regex to consider (negative for last).

required
xpath_text XPath

Compiled XPath for text extraction.

required

Returns:

Type Description
tuple[int, str]

tuple[int, str]: A tuple containing the calculated insertion position and the text string where the insertion will occur.

Source code in odfdo/element.py
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
def _insert_before_after(
    self,
    current: _Element,
    element: _Element,
    before: str | None,
    after: str | None,
    position: int,
    xpath_text: XPath,
) -> tuple[int, str]:
    """Calculates the insertion position based on 'before' or 'after' regex.

    Args:
        current: The current lxml element.
        element: The element to be inserted.
        before: Regex pattern to find position before.
        after: Regex pattern to find position after.
        position: The occurrence of the regex to consider (negative for last).
        xpath_text: Compiled XPath for text extraction.

    Returns:
        tuple[int, str]: A tuple containing the calculated insertion position
            and the text string where the insertion will occur.
    """
    regex = self._make_before_regex(before, after)
    xpath_result = xpath_return_strings(xpath_text, current)
    # position = -1
    if position < 0:
        text, sre = self._search_negative_position(xpath_result, regex)
    # position >= 0
    else:
        text, sre = self._search_positive_position(xpath_result, regex, position)
    # Compute pos
    if before is None:
        pos = sre.end()
    else:
        pos = sre.start()
    return pos, text

_insert_find_text

_insert_find_text(
    current: _Element,
    element: _Element,
    before: str | None,
    after: str | None,
    position: int,
    xpath_text: XPath,
) -> tuple[int, str]

Finds the text and insertion point based on a character position.

Parameters:

Name Type Description Default
current _Element

The current lxml element.

required
element _Element

The element to be inserted.

required
before str | None

Not used in this method, kept for signature compatibility.

required
after str | None

Not used in this method, kept for signature compatibility.

required
position int

The character position for insertion.

required
xpath_text XPath

Compiled XPath for text extraction.

required

Returns:

Type Description
tuple[int, str]

tuple[int, str]: A tuple containing the calculated insertion point within the text and the text string where the insertion will occur.

Raises:

Type Description
ValueError

If the text at the specified position is not found.

Source code in odfdo/element.py
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
def _insert_find_text(
    self,
    current: _Element,
    element: _Element,
    before: str | None,
    after: str | None,
    position: int,
    xpath_text: XPath,
) -> tuple[int, str]:
    """Finds the text and insertion point based on a character position.

    Args:
        current: The current lxml element.
        element: The element to be inserted.
        before: Not used in this method, kept for signature compatibility.
        after: Not used in this method, kept for signature compatibility.
        position: The character position for insertion.
        xpath_text: Compiled XPath for text extraction.

    Returns:
        tuple[int, str]: A tuple containing the calculated insertion point within
            the text and the text string where the insertion will occur.

    Raises:
        ValueError: If the text at the specified position is not found.
    """
    # Find the text
    xpath_result = xpath_return_strings(xpath_text, current)
    count = 0
    for text in xpath_result:
        found_nb = len(text)
        if found_nb + count >= position:
            break
        count += found_nb
    else:
        raise ValueError(f"Text not found: {xpath_result!r}")
    # We insert before the character
    pos = position - count
    return pos, text

_make_before_regex staticmethod

_make_before_regex(
    before: str | None, after: str | None
) -> re.Pattern

Compiles a regular expression for insertion before or after text.

Parameters:

Name Type Description Default
before str | None

A regex pattern to match text before which to insert.

required
after str | None

A regex pattern to match text after which to insert.

required

Returns:

Type Description
Pattern

re.Pattern: A compiled regex pattern based on before or after.

Raises:

Type Description
ValueError

If both before and after are None.

Source code in odfdo/element.py
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
@staticmethod
def _make_before_regex(
    before: str | None,
    after: str | None,
) -> re.Pattern:
    """Compiles a regular expression for insertion before or after text.

    Args:
        before: A regex pattern to match text before which to insert.
        after: A regex pattern to match text after which to insert.

    Returns:
        re.Pattern: A compiled regex pattern based on `before` or `after`.

    Raises:
        ValueError: If both `before` and `after` are None.
    """
    # 1) before xor after is not None
    if before is not None:
        return re.compile(before)
    else:
        if after is None:
            raise ValueError("Both 'before' and 'after' are None")
        return re.compile(after)

_make_etree_element staticmethod

_make_etree_element(tag: str) -> _Element

Create an lxml Element from an ODF tag string.

Parameters:

Name Type Description Default
tag str

The ODF tag string (e.g., “text:p”, ““).

required

Returns:

Name Type Description
_Element _Element

An lxml Element instance.

Raises:

Type Description
TypeError

If the tag is not a string.

ValueError

If the tag is empty.

Source code in odfdo/element.py
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
@staticmethod
def _make_etree_element(tag: str) -> _Element:
    """Create an lxml Element from an ODF tag string.

    Args:
        tag: The ODF tag string (e.g., "text:p", "<text:p/>").

    Returns:
        _Element: An lxml Element instance.

    Raises:
        TypeError: If the tag is not a string.
        ValueError: If the tag is empty.
    """
    if not isinstance(tag, str):
        raise TypeError(f"Tag is not str: {tag!r}")
    tag = tag.strip()
    if not tag:
        raise ValueError("Tag is empty")
    if "<" not in tag:
        # Qualified name
        # XXX don't build the element from scratch or lxml will pollute with
        # repeated namespace declarations
        tag = f"<{tag}/>"
    # XML fragment
    root = fromstring(NAMESPACES_XML % str_to_bytes(tag))
    return root[0]

_search_negative_position staticmethod

_search_negative_position(
    xpath_result: list[str], regex: Pattern
) -> tuple[str, re.Match]

Searches for the last occurrence of a regex pattern in a list of strings.

Parameters:

Name Type Description Default
xpath_result list[str]

A list of strings to search within.

required
regex Pattern

The compiled regex pattern to search for.

required

Returns:

Type Description
tuple[str, Match]

tuple[str, re.Match]: A tuple containing the string where the match was found and the match object itself.

Raises:

Type Description
ValueError

If the text matching the regex is not found.

Source code in odfdo/element.py
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
@staticmethod
def _search_negative_position(
    xpath_result: list[str],
    regex: re.Pattern,
) -> tuple[str, re.Match]:
    """Searches for the last occurrence of a regex pattern in a list of strings.

    Args:
        xpath_result: A list of strings to search within.
        regex: The compiled regex pattern to search for.

    Returns:
        tuple[str, re.Match]: A tuple containing the string where the match was
            found and the match object itself.

    Raises:
        ValueError: If the text matching the regex is not found.
    """
    # Found the last text that matches the regex
    for text in xpath_result:
        if regex.search(text) is not None:
            break
    else:
        raise ValueError(f"Text not found: {xpath_result!r}")
    return text, list(regex.finditer(text))[-1]

_search_positive_position staticmethod

_search_positive_position(
    xpath_result: list[str], regex: Pattern, position: int
) -> tuple[str, re.Match]

Searches for the nth occurrence of a regex pattern in a list of strings.

Parameters:

Name Type Description Default
xpath_result list[str]

A list of strings to search within.

required
regex Pattern

The compiled regex pattern to search for.

required
position int

The 0-based index of the match to find.

required

Returns:

Type Description
tuple[str, Match]

tuple[str, re.Match]: A tuple containing the string where the match was found and the match object itself.

Raises:

Type Description
ValueError

If the text matching the regex is not found.

Source code in odfdo/element.py
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
@staticmethod
def _search_positive_position(
    xpath_result: list[str],
    regex: re.Pattern,
    position: int,
) -> tuple[str, re.Match]:
    """Searches for the nth occurrence of a regex pattern in a list of strings.

    Args:
        xpath_result: A list of strings to search within.
        regex: The compiled regex pattern to search for.
        position: The 0-based index of the match to find.

    Returns:
        tuple[str, re.Match]: A tuple containing the string where the match was
            found and the match object itself.

    Raises:
        ValueError: If the text matching the regex is not found.
    """
    # Found the last text that matches the regex
    count = 0
    for text in xpath_result:
        found_nb = len(regex.findall(text))
        if found_nb + count >= position + 1:
            break
        count += found_nb
    else:
        raise ValueError(f"Text not found: {xpath_result!r}")
    return text, list(regex.finditer(text))[position - count]

_set_attribute_bool_default

_set_attribute_bool_default(
    name: str,
    value: bool | str | None,
    default: bool = True,
) -> None

Sets the value of a specified boolean attribute, removing it if it matches the default.

Parameters:

Name Type Description Default
name str

The qualified name of the attribute to set.

required
value bool | str | None

The boolean value to set. Can be a bool, “true”/”false” string, or None. If None, it defaults to False.

required
default bool

The default boolean value. If the value to set matches this default, the attribute is removed.

True
Source code in odfdo/element.py
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
def _set_attribute_bool_default(
    self, name: str, value: bool | str | None, default: bool = True
) -> None:
    """Sets the value of a specified boolean attribute, removing it if it matches the default.

    Args:
        name: The qualified name of the attribute to set.
        value: The boolean value to set. Can be a bool,
            "true"/"false" string, or None. If None, it defaults to False.
        default: The default boolean value. If the `value` to set
            matches this default, the attribute is removed.
    """
    element = self.__element
    lxml_tag = _get_lxml_tag_or_name(name)
    if value is None:
        value = False
    if isinstance(value, str):
        value = value.lower() == "true"
    if value == default:
        with contextlib.suppress(KeyError):
            del element.attrib[lxml_tag]
        return
    element.set(lxml_tag, Boolean.encode(value))

_set_attribute_int

_set_attribute_int(name: str, value: int | None) -> None

Sets the value of a specified integer attribute.

Parameters:

Name Type Description Default
name str

The qualified name of the attribute to set.

required
value int | None

The integer value to set. If None, the attribute is removed.

required
Source code in odfdo/element.py
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
def _set_attribute_int(self, name: str, value: int | None) -> None:
    """Sets the value of a specified integer attribute.

    Args:
        name: The qualified name of the attribute to set.
        value: The integer value to set. If None, the attribute is
            removed.
    """
    element = self.__element
    lxml_tag = _get_lxml_tag_or_name(name)
    if value is None:
        with contextlib.suppress(KeyError):
            del element.attrib[lxml_tag]
        return
    element.set(lxml_tag, str(value))

_set_attribute_int_default

_set_attribute_int_default(
    name: str, value: int | None, default: int
) -> None

Sets the value of a specified integer attribute, removing it if it matches the default.

Parameters:

Name Type Description Default
name str

The qualified name of the attribute to set.

required
value int | None

The integer value to set. If None or matches default, the attribute is removed.

required
default int

The default integer value. If the value to set matches this default, the attribute is removed.

required
Source code in odfdo/element.py
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
def _set_attribute_int_default(
    self, name: str, value: int | None, default: int
) -> None:
    """Sets the value of a specified integer attribute, removing it if it matches the default.

    Args:
        name: The qualified name of the attribute to set.
        value: The integer value to set. If None or matches `default`,
            the attribute is removed.
        default: The default integer value. If the `value` to set
            matches this default, the attribute is removed.
    """
    element = self.__element
    lxml_tag = _get_lxml_tag_or_name(name)
    if value is None or value == default:
        with contextlib.suppress(KeyError):
            del element.attrib[lxml_tag]
        return
    element.set(lxml_tag, str(value))

_set_attribute_number_default

_set_attribute_number_default(
    name: str,
    value: Decimal | int | float | None,
    default: Decimal | int | float | None,
) -> None

Sets the value of a specified number attribute (Decimal, int, or float), removing it if it matches the default.

Parameters:

Name Type Description Default
name str

The qualified name of the attribute to set.

required
value Decimal | int | float | None

The numeric value to set. If None or matches default, the attribute is removed.

required
default Decimal | int | float | None

The default numeric value. If the value to set matches this default, the attribute is removed.

required
Source code in odfdo/element.py
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
def _set_attribute_number_default(
    self,
    name: str,
    value: Decimal | int | float | None,
    default: Decimal | int | float | None,
) -> None:
    """Sets the value of a specified number attribute (Decimal, int, or float),
    removing it if it matches the default.

    Args:
        name: The qualified name of the attribute to set.
        value: The numeric value to set.
            If None or matches `default`, the attribute is removed.
        default: The default numeric value.
            If the `value` to set matches this default, the attribute is removed.
    """
    element = self.__element
    lxml_tag = _get_lxml_tag_or_name(name)
    if value is None or value == default:
        with contextlib.suppress(KeyError):
            del element.attrib[lxml_tag]
        return
    element.set(lxml_tag, str(value))

_set_attribute_str

_set_attribute_str(name: str, value: str) -> None

Sets the value of a string attribute.

This internal method directly sets the value of an attribute without any default handling or type conversions beyond converting the value to a string if necessary.

Parameters:

Name Type Description Default
name str

The qualified name of the attribute to set.

required
value str

The string value to set for the attribute.

required
Source code in odfdo/element.py
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
def _set_attribute_str(self, name: str, value: str) -> None:
    """Sets the value of a string attribute.

    This internal method directly sets the value of an attribute without
    any default handling or type conversions beyond converting the value
    to a string if necessary.

    Args:
        name: The qualified name of the attribute to set.
        value: The string value to set for the attribute.
    """
    lxml_tag = _get_lxml_tag_or_name(name)
    self.__element.set(lxml_tag, value)

_set_attribute_str_default

_set_attribute_str_default(
    name: str, value: str | None, default: str = ""
) -> None

Sets the value of a specified string attribute, removing it if it matches the default.

Parameters:

Name Type Description Default
name str

The qualified name of the attribute to set.

required
value str | None

The string value to set. If None or matches default, the attribute is removed.

required
default str

The default string value. If the value to set matches this default, the attribute is removed.

''
Source code in odfdo/element.py
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
def _set_attribute_str_default(
    self, name: str, value: str | None, default: str = ""
) -> None:
    """Sets the value of a specified string attribute, removing it if it matches the default.

    Args:
        name: The qualified name of the attribute to set.
        value: The string value to set. If None or matches `default`,
            the attribute is removed.
        default: The default string value. If the `value` to set
            matches this default, the attribute is removed.
    """
    element = self.__element
    lxml_tag = _get_lxml_tag_or_name(name)
    if value is None or value == default:
        with contextlib.suppress(KeyError):
            del element.attrib[lxml_tag]
        return
    element.set(lxml_tag, value)

_set_inner_text

_set_inner_text(tag: str, text: str) -> None

Sets the text content of a specified inner element.

If the inner element does not exist, it is created.

Parameters:

Name Type Description Default
tag str

The qualified name of the inner element (e.g., “svg:title”).

required
text str

The new text content to set.

required
Source code in odfdo/element.py
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
def _set_inner_text(self, tag: str, text: str) -> None:
    """Sets the text content of a specified inner element.

    If the inner element does not exist, it is created.

    Args:
        tag: The qualified name of the inner element (e.g., "svg:title").
        text: The new text content to set.
    """
    element = self.get_element(tag)
    if element is None:
        element = Element.from_tag(tag)
        self.__append(element)
    element.text = text

_strip_namespaces staticmethod

_strip_namespaces(data: str) -> str

Removes xmlns:* attributes from a serialized XML string.

Parameters:

Name Type Description Default
data str

The serialized XML string.

required

Returns:

Name Type Description
str str

The XML string with xmlns attributes removed.

Source code in odfdo/element.py
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
@staticmethod
def _strip_namespaces(data: str) -> str:
    """Removes xmlns:* attributes from a serialized XML string.

    Args:
        data: The serialized XML string.

    Returns:
        str: The XML string with xmlns attributes removed.
    """
    return re.sub(r' xmlns:\w*="[\w:\-\/\.#]*"', "", data)

_xml_append

_xml_append(element: Element) -> None

Appends the underlying lxml element of another Element instance.

Parameters:

Name Type Description Default
element Element

The Element instance whose underlying XML element will be appended.

required
Source code in odfdo/element.py
1865
1866
1867
1868
1869
1870
1871
def _xml_append(self, element: Element) -> None:
    """Appends the underlying lxml element of another Element instance.

    Args:
        element: The Element instance whose underlying XML element will be appended.
    """
    self.__element.append(element.__element)

clear

clear() -> None

Removes all text content, child elements, and attributes from the element.

Source code in odfdo/element.py
1988
1989
1990
def clear(self) -> None:
    """Removes all text content, child elements, and attributes from the element."""
    self.__element.clear()

del_attribute

del_attribute(name: str) -> None

Deletes a specified attribute from the element.

Parameters:

Name Type Description Default
name str

The qualified name of the attribute to delete.

required

Raises:

Type Description
KeyError

If the specified attribute does not exist.

Source code in odfdo/element.py
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
def del_attribute(self, name: str) -> None:
    """Deletes a specified attribute from the element.

    Args:
        name: The qualified name of the attribute to delete.

    Raises:
        KeyError: If the specified attribute does not exist.
    """
    element = self.__element
    lxml_tag = _get_lxml_tag_or_name(name)
    del element.attrib[lxml_tag]

del_attribute_list

del_attribute_list(names: Iterable[str]) -> None

Deletes a list of attributes from the element if present.

Parameters:

Name Type Description Default
names Iterable[str]

The qualified names of the attributes to delete.

required
Source code in odfdo/element.py
1436
1437
1438
1439
1440
1441
1442
1443
1444
def del_attribute_list(self, names: Iterable[str]) -> None:
    """Deletes a list of attributes from the element if present.

    Args:
        names: The qualified names of the attributes to delete.
    """
    for name in names:
        with contextlib.suppress(KeyError):
            del self.__element.attrib[_get_lxml_tag_or_name(name)]

delete

delete(
    child: Element | None = None, keep_tail: bool = True
) -> None

Deletes an element from the XML tree.

If child is provided, that specific child element is deleted from this element. If child is None, the current element (self) is deleted from its parent. The XML library may allow orphaned elements to be used as long as a reference exists.

Parameters:

Name Type Description Default
child Element | None

The child element to delete. If None, self is deleted.

None
keep_tail bool

If True (default), the tail text of the deleted element is preserved and appended to the previous sibling or parent’s text.

True

Raises:

Type Description
ValueError

If an attempt is made to delete the root element (self has no parent).

Source code in odfdo/element.py
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
def delete(self, child: Element | None = None, keep_tail: bool = True) -> None:
    """Deletes an element from the XML tree.

    If `child` is provided, that specific child element is deleted from this element.
    If `child` is None, the current element (`self`) is deleted from its parent.
    The XML library may allow orphaned elements to be used as long as a reference exists.

    Args:
        child: The child element to delete. If None, `self` is deleted.
        keep_tail: If True (default), the tail text of the deleted element
            is preserved and appended to the previous sibling or parent's text.

    Raises:
        ValueError: If an attempt is made to delete the root element (`self` has no parent).
    """
    if child is None:
        parent = self.parent
        if parent is None:
            raise ValueError(f"Can't delete the root element\n{self.serialize()}")
        child = self
    else:
        parent = self
    if keep_tail and child.__element.tail is not None:
        current = child.__element
        tail = str(current.tail)
        current.tail = None
        prev = current.getprevious()
        if prev is not None:
            if prev.tail is None:
                prev.tail = tail
            else:
                prev.tail += tail
        else:
            if parent.__element.text is None:
                parent.__element.text = tail
            else:
                parent.__element.text += tail
    parent.__element.remove(child.__element)

elements_repeated_sequence

elements_repeated_sequence(
    xpath_instance: XPath, name: str
) -> list[tuple[int, int]]

Extracts repeated sequence information from elements for table handling.

This utility method is primarily used by the table module to process elements that might have a ‘number-columns-repeated’ or similar attribute. It returns a list of tuples, where each tuple contains the index of the element and how many times it is logically repeated.

Parameters:

Name Type Description Default
xpath_instance XPath

A compiled XPath object to select sub-elements.

required
name str

The name of the attribute (e.g., “table:number-columns-repeated”) that indicates repetition.

required

Returns:

Type Description
list[tuple[int, int]]

list[tuple[int, int]]: A list of (index, repetition_count) tuples.

Source code in odfdo/element.py
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
def elements_repeated_sequence(
    self,
    xpath_instance: XPath,
    name: str,
) -> list[tuple[int, int]]:
    """Extracts repeated sequence information from elements for table handling.

    This utility method is primarily used by the table module to process
    elements that might have a 'number-columns-repeated' or similar attribute.
    It returns a list of tuples, where each tuple contains the index of the
    element and how many times it is logically repeated.

    Args:
        xpath_instance: A compiled XPath object to select sub-elements.
        name: The name of the attribute (e.g., "table:number-columns-repeated")
            that indicates repetition.

    Returns:
        list[tuple[int, int]]: A list of (index, repetition_count) tuples.
    """
    lxml_tag = _get_lxml_tag_or_name(name)
    sub_elements = xpath_return_elements(xpath_instance, self.__element)
    result: list[tuple[int, int]] = []
    idx = -1
    for sub_element in sub_elements:
        idx += 1
        value = sub_element.get(lxml_tag)
        if value is None:
            result.append((idx, 1))
            continue
        try:
            int_value = int(value)
        except ValueError:  # pragma: nocover
            int_value = 1
        result.append((idx, max(int_value, 1)))
    return result

extend

extend(odf_elements: Iterable[Element]) -> None

Appends multiple ODF elements efficiently to the end of the current element.

Parameters:

Name Type Description Default
odf_elements Iterable[Element]

An iterable (e.g., list) of Element instances to append.

required
Source code in odfdo/element.py
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
def extend(self, odf_elements: Iterable[Element]) -> None:
    """Appends multiple ODF elements efficiently to the end of the current element.

    Args:
        odf_elements: An iterable (e.g., list) of Element instances to append.
    """
    if odf_elements:
        current = self.__element
        elements = [element.__element for element in odf_elements]
        current.extend(elements)

from_tag classmethod

from_tag(tag_or_elem: str | _Element) -> Element

Factory method to create an Element instance (or a subclass) from an XML tag.

This method can convert an lxml Element or an ODF string tag into an ODF XML Element of the appropriate class (e.g., Paragraph, Table, etc.).

Parameters:

Name Type Description Default
tag_or_elem str | _Element

Either an ODF string tag (e.g., “text:p”) or an existing lxml.etree._Element instance.

required

Returns:

Name Type Description
Element Element

An instance of Element or its appropriate subclass.

Source code in odfdo/element.py
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
@classmethod
def from_tag(cls, tag_or_elem: str | _Element) -> Element:
    """Factory method to create an Element instance (or a subclass) from an XML tag.

    This method can convert an lxml Element or an ODF string tag into an
    ODF XML Element of the appropriate class (e.g., Paragraph, Table, etc.).

    Args:
        tag_or_elem: Either an ODF string tag (e.g., "text:p")
            or an existing `lxml.etree._Element` instance.

    Returns:
        Element: An instance of Element or its appropriate subclass.
    """
    if isinstance(tag_or_elem, str):
        # assume the argument is a prefix:name tag
        elem = cls._make_etree_element(tag_or_elem)
    else:
        elem = tag_or_elem
    klass = _class_registry.get(elem.tag, cls)
    return klass(tag_or_elem=elem)

from_tag_for_clone classmethod

from_tag_for_clone(
    tree_element: _Element, cache: tuple | None
) -> Element

Factory method used internally for cloning elements.

This method is similar to from_tag but is specifically optimized for cloning operations, potentially utilizing a cache.

Parameters:

Name Type Description Default
tree_element _Element

The lxml.etree._Element instance to clone.

required
cache tuple | None

An optional cache to be copied to the new element.

required

Returns:

Name Type Description
Element Element

A new Element instance (or subclass) representing the cloned element.

Source code in odfdo/element.py
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
@classmethod
def from_tag_for_clone(
    cls: Any,  # ABCMeta, type, ...
    tree_element: _Element,
    cache: tuple | None,
) -> Element:
    """Factory method used internally for cloning elements.

    This method is similar to `from_tag` but is specifically optimized
    for cloning operations, potentially utilizing a cache.

    Args:
        tree_element: The `lxml.etree._Element` instance to clone.
        cache: An optional cache to be copied to the new element.

    Returns:
        Element: A new Element instance (or subclass) representing the cloned element.
    """
    tag = to_str(tree_element.tag)
    klass = _class_registry.get(tag, cls)
    element: Element = klass(tag_or_elem=tree_element)
    if cache:
        element._copy_cache(cache)
    return element

get_attribute

get_attribute(name: str) -> str | bool | None

Returns the value of a specified attribute.

Parameters:

Name Type Description Default
name str

The qualified name of the attribute to retrieve (e.g., “office:name”).

required

Returns:

Type Description
str | bool | None

str | bool | None: The attribute’s value, which can be a string, a boolean (if the original value was “true” or “false”), or None if the attribute is not found.

Source code in odfdo/element.py
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
def get_attribute(self, name: str) -> str | bool | None:
    """Returns the value of a specified attribute.

    Args:
        name: The qualified name of the attribute to retrieve (e.g., "office:name").

    Returns:
        str | bool | None: The attribute's value, which can be a string, a boolean
            (if the original value was "true" or "false"), or None if the attribute is not found.
    """
    element = self.__element
    lxml_tag = _get_lxml_tag_or_name(name)
    value = element.get(lxml_tag)
    if value is None:
        return None
    elif value in ("true", "false"):
        return Boolean.decode(value)
    return str(value)

get_attribute_integer

get_attribute_integer(name: str) -> int | None

Returns the value of a specified attribute as an integer.

Parameters:

Name Type Description Default
name str

The qualified name of the attribute to retrieve.

required

Returns:

Type Description
int | None

int | None: The attribute’s value as an integer, or None if the attribute is not found or cannot be converted to an integer.

Source code in odfdo/element.py
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
def get_attribute_integer(self, name: str) -> int | None:
    """Returns the value of a specified attribute as an integer.

    Args:
        name: The qualified name of the attribute to retrieve.

    Returns:
        int | None: The attribute's value as an integer, or None if the attribute
            is not found or cannot be converted to an integer.
    """
    element = self.__element
    lxml_tag = _get_lxml_tag_or_name(name)
    value = element.get(lxml_tag)
    if value is None:
        return None
    try:
        return int(value)
    except ValueError:
        return None

get_attribute_number

get_attribute_number(name: str) -> int | Decimal | None

Returns the value of a specified attribute as a number (Decimal or int).

Parameters:

Name Type Description Default
name str

The qualified name of the attribute to retrieve.

required

Returns:

Type Description
int | Decimal | None

int | Decimal | None: The attribute’s value as an int (if it’s a whole number) or a Decimal, or None if the attribute is not found or cannot be converted to a number.

Source code in odfdo/element.py
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
def get_attribute_number(self, name: str) -> int | Decimal | None:
    """Returns the value of a specified attribute as a number (Decimal or int).

    Args:
        name: The qualified name of the attribute to retrieve.

    Returns:
        int | Decimal | None: The attribute's value as an int (if it's a whole number)
            or a Decimal, or None if the attribute is not found or cannot be
            converted to a number.
    """
    element = self.__element
    lxml_tag = _get_lxml_tag_or_name(name)
    value = element.get(lxml_tag)
    if value is None:
        return None
    value = Decimal(value)
    # Return 3 instead of 3.0 if possible
    with contextlib.suppress(ValueError):
        if int(value) == value:
            return int(value)
    return value

get_attribute_string

get_attribute_string(name: str) -> str | None

Returns the value of a specified attribute as a string.

Parameters:

Name Type Description Default
name str

The qualified name of the attribute to retrieve.

required

Returns:

Type Description
str | None

str | None: The attribute’s value as a string, or None if the attribute is not found.

Source code in odfdo/element.py
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
def get_attribute_string(self, name: str) -> str | None:
    """Returns the value of a specified attribute as a string.

    Args:
        name: The qualified name of the attribute to retrieve.

    Returns:
        str | None: The attribute's value as a string, or None if the attribute is not found.
    """
    element = self.__element
    lxml_tag = _get_lxml_tag_or_name(name)
    value = element.get(lxml_tag)
    if value is None:
        return None
    return str(value)

get_changes_ids

get_changes_ids() -> list[Element | EText]

Returns a list of IDs that refer to change regions in the tracked changes list.

Returns:

Type Description
list[Element | EText]

list[Element | EText]: A list of Element or EText instances representing change IDs.

Source code in odfdo/element.py
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
def get_changes_ids(self) -> list[Element | EText]:
    """Returns a list of IDs that refer to change regions in the tracked changes list.

    Returns:
        list[Element | EText]: A list of Element or EText instances representing change IDs.
    """
    # Insertion changes or deletion changes
    xpath_query = (
        "descendant::text:change-start/@text:change-id "
        "| descendant::text:change/@text:change-id"
    )
    return self.xpath(xpath_query)

get_draw_connector

get_draw_connector(
    position: int = 0,
    id: str | None = None,
    content: str | None = None,
) -> ConnectorShape | None

Returns a single draw connector that matches the specified criteria.

Parameters:

Name Type Description Default
position int

The 0-based index of the matching draw connector to return.

0
id str | None

The ID of the draw connector.

None
content str | None

A regex pattern to match against the connector’s content.

None

Returns:

Type Description
ConnectorShape | None

ConnectorShape | None: A ConnectorShape instance, or None if no connector matches the criteria.

Source code in odfdo/element.py
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
def get_draw_connector(
    self,
    position: int = 0,
    id: str | None = None,  # noqa:A002
    content: str | None = None,
) -> ConnectorShape | None:
    """Returns a single draw connector that matches the specified criteria.

    Args:
        position: The 0-based index of the matching draw connector to return.
        id: The ID of the draw connector.
        content: A regex pattern to match against the connector's content.

    Returns:
        ConnectorShape | None: A ConnectorShape instance, or None if no connector matches the criteria.
    """
    return self._filtered_element(
        "descendant::draw:connector", position, draw_id=id, content=content
    )  # type: ignore[return-value]

get_draw_connectors

get_draw_connectors(
    draw_style: str | None = None,
    draw_text_style: str | None = None,
    content: str | None = None,
) -> list[ConnectorShape]

Returns all draw connectors that match the specified criteria.

Parameters:

Name Type Description Default
draw_style str | None

The name of the draw style to filter connectors by.

None
draw_text_style str | None

The name of the draw text style to filter connectors by.

None
content str | None

A regex pattern to match against the connector’s content.

None

Returns:

Type Description
list[ConnectorShape]

list[ConnectorShape]: A list of ConnectorShape instances matching the criteria.

Source code in odfdo/element.py
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
def get_draw_connectors(
    self,
    draw_style: str | None = None,
    draw_text_style: str | None = None,
    content: str | None = None,
) -> list[ConnectorShape]:
    """Returns all draw connectors that match the specified criteria.

    Args:
        draw_style: The name of the draw style to filter connectors by.
        draw_text_style: The name of the draw text style to filter connectors by.
        content: A regex pattern to match against the connector's content.

    Returns:
        list[ConnectorShape]: A list of ConnectorShape instances matching the criteria.
    """
    return self._filtered_elements(
        "descendant::draw:connector",
        draw_style=draw_style,
        draw_text_style=draw_text_style,
        content=content,
    )  # type: ignore[return-value]

get_draw_ellipse

get_draw_ellipse(
    position: int = 0,
    id: str | None = None,
    content: str | None = None,
) -> EllipseShape | None

Returns a single draw ellipse that matches the specified criteria.

Parameters:

Name Type Description Default
position int

The 0-based index of the matching draw ellipse to return.

0
id str | None

The ID of the draw ellipse.

None
content str | None

A regex pattern to match against the ellipse’s content.

None

Returns:

Type Description
EllipseShape | None

EllipseShape | None: An EllipseShape instance, or None if no ellipse matches the criteria.

Source code in odfdo/element.py
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
def get_draw_ellipse(
    self,
    position: int = 0,
    id: str | None = None,  # noqa:A002
    content: str | None = None,
) -> EllipseShape | None:
    """Returns a single draw ellipse that matches the specified criteria.

    Args:
        position: The 0-based index of the matching draw ellipse to return.
        id: The ID of the draw ellipse.
        content: A regex pattern to match against the ellipse's content.

    Returns:
        EllipseShape | None: An EllipseShape instance, or None if no ellipse matches the criteria.
    """
    return self._filtered_element(
        "descendant::draw:ellipse", position, draw_id=id, content=content
    )  # type: ignore[return-value]

get_draw_ellipses

get_draw_ellipses(
    draw_style: str | None = None,
    draw_text_style: str | None = None,
    content: str | None = None,
) -> list[EllipseShape]

Returns all draw ellipses that match the specified criteria.

Parameters:

Name Type Description Default
draw_style str | None

The name of the draw style to filter ellipses by.

None
draw_text_style str | None

The name of the draw text style to filter ellipses by.

None
content str | None

A regex pattern to match against the ellipse’s content.

None

Returns:

Type Description
list[EllipseShape]

list[EllipseShape]: A list of EllipseShape instances matching the criteria.

Source code in odfdo/element.py
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
def get_draw_ellipses(
    self,
    draw_style: str | None = None,
    draw_text_style: str | None = None,
    content: str | None = None,
) -> list[EllipseShape]:
    """Returns all draw ellipses that match the specified criteria.

    Args:
        draw_style: The name of the draw style to filter ellipses by.
        draw_text_style: The name of the draw text style to filter ellipses by.
        content: A regex pattern to match against the ellipse's content.

    Returns:
        list[EllipseShape]: A list of EllipseShape instances matching the criteria.
    """
    return self._filtered_elements(
        "descendant::draw:ellipse",
        draw_style=draw_style,
        draw_text_style=draw_text_style,
        content=content,
    )  # type: ignore[return-value]

get_draw_group

get_draw_group(
    position: int = 0,
    name: str | None = None,
    title: str | None = None,
    description: str | None = None,
    content: str | None = None,
) -> DrawGroup | None

Returns a single draw group that matches the specified criteria.

Parameters:

Name Type Description Default
position int

The 0-based index of the matching draw group to return.

0
name str | None

The name of the draw group.

None
title str | None

A regex pattern to match against the group’s title.

None
description str | None

A regex pattern to match against the group’s description.

None
content str | None

A regex pattern to match against the group’s content.

None

Returns:

Type Description
DrawGroup | None

DrawGroup | None: A DrawGroup instance, or None if no group matches the criteria.

Source code in odfdo/element.py
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
def get_draw_group(
    self,
    position: int = 0,
    name: str | None = None,
    title: str | None = None,
    description: str | None = None,
    content: str | None = None,
) -> DrawGroup | None:
    """Returns a single draw group that matches the specified criteria.

    Args:
        position: The 0-based index of the matching draw group to return.
        name: The name of the draw group.
        title: A regex pattern to match against the group's title.
        description: A regex pattern to match against the group's description.
        content: A regex pattern to match against the group's content.

    Returns:
        DrawGroup | None: A DrawGroup instance, or None if no group matches the criteria.
    """
    return self._filtered_element(
        "descendant::draw:g",
        position,
        draw_name=name,
        svg_title=title,
        svg_desc=description,
        content=content,
    )  # type: ignore[return-value]

get_draw_groups

get_draw_groups(
    title: str | None = None,
    description: str | None = None,
    content: str | None = None,
) -> list[DrawGroup]

Returns all draw groups that match the specified criteria.

Parameters:

Name Type Description Default
title str | None

A regex pattern to match against the group’s title.

None
description str | None

A regex pattern to match against the group’s description.

None
content str | None

A regex pattern to match against the group’s content.

None

Returns:

Type Description
list[DrawGroup]

list[DrawGroup]: A list of DrawGroup instances matching the criteria.

Source code in odfdo/element.py
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
def get_draw_groups(
    self,
    title: str | None = None,
    description: str | None = None,
    content: str | None = None,
) -> list[DrawGroup]:
    """Returns all draw groups that match the specified criteria.

    Args:
        title: A regex pattern to match against the group's title.
        description: A regex pattern to match against the group's description.
        content: A regex pattern to match against the group's content.

    Returns:
        list[DrawGroup]: A list of DrawGroup instances matching the criteria.
    """
    return self._filtered_elements(
        "descendant::draw:g",
        svg_title=title,
        svg_desc=description,
        content=content,
    )  # type: ignore[return-value]

get_draw_line

get_draw_line(
    position: int = 0,
    id: str | None = None,
    content: str | None = None,
) -> LineShape | None

Returns a single draw line that matches the specified criteria.

Parameters:

Name Type Description Default
position int

The 0-based index of the matching draw line to return.

0
id str | None

The ID of the draw line.

None
content str | None

A regex pattern to match against the line’s content.

None

Returns:

Type Description
LineShape | None

LineShape | None: A LineShape instance, or None if no line matches the criteria.

Source code in odfdo/element.py
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
def get_draw_line(
    self,
    position: int = 0,
    id: str | None = None,  # noqa:A002
    content: str | None = None,
) -> LineShape | None:
    """Returns a single draw line that matches the specified criteria.

    Args:
        position: The 0-based index of the matching draw line to return.
        id: The ID of the draw line.
        content: A regex pattern to match against the line's content.

    Returns:
        LineShape | None: A LineShape instance, or None if no line matches the criteria.
    """
    return self._filtered_element(
        "descendant::draw:line", position, draw_id=id, content=content
    )  # type: ignore[return-value]

get_draw_lines

get_draw_lines(
    draw_style: str | None = None,
    draw_text_style: str | None = None,
    content: str | None = None,
) -> list[LineShape]

Returns all draw lines that match the specified criteria.

Parameters:

Name Type Description Default
draw_style str | None

The name of the draw style to filter lines by.

None
draw_text_style str | None

The name of the draw text style to filter lines by.

None
content str | None

A regex pattern to match against the line’s content.

None

Returns:

Type Description
list[LineShape]

list[LineShape]: A list of LineShape instances matching the criteria.

Source code in odfdo/element.py
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
def get_draw_lines(
    self,
    draw_style: str | None = None,
    draw_text_style: str | None = None,
    content: str | None = None,
) -> list[LineShape]:
    """Returns all draw lines that match the specified criteria.

    Args:
        draw_style: The name of the draw style to filter lines by.
        draw_text_style: The name of the draw text style to filter lines by.
        content: A regex pattern to match against the line's content.

    Returns:
        list[LineShape]: A list of LineShape instances matching the criteria.
    """
    return self._filtered_elements(
        "descendant::draw:line",
        draw_style=draw_style,
        draw_text_style=draw_text_style,
        content=content,
    )  # type: ignore[return-value]

get_draw_page

get_draw_page(
    position: int = 0,
    name: str | None = None,
    content: str | None = None,
) -> DrawPage | None

Returns a single draw page that matches the specified criteria.

Parameters:

Name Type Description Default
position int

The 0-based index of the matching draw page to return.

0
name str | None

The name of the draw page.

None
content str | None

A regex pattern to match against the draw page’s content.

None

Returns:

Type Description
DrawPage | None

DrawPage | None: A DrawPage instance, or None if no draw page matches the criteria.

Source code in odfdo/element.py
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
def get_draw_page(
    self,
    position: int = 0,
    name: str | None = None,
    content: str | None = None,
) -> DrawPage | None:
    """Returns a single draw page that matches the specified criteria.

    Args:
        position: The 0-based index of the matching draw page to return.
        name: The name of the draw page.
        content: A regex pattern to match against the draw page's content.

    Returns:
        DrawPage | None: A DrawPage instance, or None if no draw page matches the criteria.
    """
    return self._filtered_element(
        "descendant::draw:page", position, draw_name=name, content=content
    )  # type: ignore[return-value]

get_draw_pages

get_draw_pages(
    style: str | None = None, content: str | None = None
) -> list[DrawPage]

Returns all draw pages that match the specified criteria.

Parameters:

Name Type Description Default
style str | None

The name of the style to filter draw pages by.

None
content str | None

A regex pattern to match against the draw page’s content.

None

Returns:

Type Description
list[DrawPage]

list[DrawPage]: A list of DrawPage instances matching the criteria.

Source code in odfdo/element.py
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
def get_draw_pages(
    self,
    style: str | None = None,
    content: str | None = None,
) -> list[DrawPage]:
    """Returns all draw pages that match the specified criteria.

    Args:
        style: The name of the style to filter draw pages by.
        content: A regex pattern to match against the draw page's content.

    Returns:
        list[DrawPage]: A list of DrawPage instances matching the criteria.
    """
    return self._filtered_elements(
        "descendant::draw:page", draw_style=style, content=content
    )  # type: ignore[return-value]

get_draw_rectangle

get_draw_rectangle(
    position: int = 0,
    id: str | None = None,
    content: str | None = None,
) -> RectangleShape | None

Returns a single draw rectangle that matches the specified criteria.

Parameters:

Name Type Description Default
position int

The 0-based index of the matching draw rectangle to return.

0
id str | None

The ID of the draw rectangle.

None
content str | None

A regex pattern to match against the rectangle’s content.

None

Returns:

Type Description
RectangleShape | None

RectangleShape | None: A RectangleShape instance, or None if no rectangle matches the criteria.

Source code in odfdo/element.py
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
def get_draw_rectangle(
    self,
    position: int = 0,
    id: str | None = None,  # noqa:A002
    content: str | None = None,
) -> RectangleShape | None:
    """Returns a single draw rectangle that matches the specified criteria.

    Args:
        position: The 0-based index of the matching draw rectangle to return.
        id: The ID of the draw rectangle.
        content: A regex pattern to match against the rectangle's content.

    Returns:
        RectangleShape | None: A RectangleShape instance, or None if no rectangle matches the criteria.
    """
    return self._filtered_element(
        "descendant::draw:rect", position, draw_id=id, content=content
    )  # type: ignore[return-value]

get_draw_rectangles

get_draw_rectangles(
    draw_style: str | None = None,
    draw_text_style: str | None = None,
    content: str | None = None,
) -> list[RectangleShape]

Returns all draw rectangles that match the specified criteria.

Parameters:

Name Type Description Default
draw_style str | None

The name of the draw style to filter rectangles by.

None
draw_text_style str | None

The name of the draw text style to filter rectangles by.

None
content str | None

A regex pattern to match against the rectangle’s content.

None

Returns:

Type Description
list[RectangleShape]

list[RectangleShape]: A list of RectangleShape instances matching the criteria.

Source code in odfdo/element.py
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
def get_draw_rectangles(
    self,
    draw_style: str | None = None,
    draw_text_style: str | None = None,
    content: str | None = None,
) -> list[RectangleShape]:
    """Returns all draw rectangles that match the specified criteria.

    Args:
        draw_style: The name of the draw style to filter rectangles by.
        draw_text_style: The name of the draw text style to filter rectangles by.
        content: A regex pattern to match against the rectangle's content.

    Returns:
        list[RectangleShape]: A list of RectangleShape instances matching the criteria.
    """
    return self._filtered_elements(
        "descendant::draw:rect",
        draw_style=draw_style,
        draw_text_style=draw_text_style,
        content=content,
    )  # type: ignore[return-value]

get_element

get_element(xpath_query: str) -> Element | None

Returns the first element obtained by applying an XPath query.

Parameters:

Name Type Description Default
xpath_query str

The XPath query string.

required

Returns:

Type Description
Element | None

Element | None: The first Element instance matching the query, or None if no match.

Source code in odfdo/element.py
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
def get_element(self, xpath_query: str) -> Element | None:
    """Returns the first element obtained by applying an XPath query.

    Args:
        xpath_query: The XPath query string.

    Returns:
        Element | None: The first Element instance matching the query, or None if no match.
    """
    result = self.__element.xpath(f"({xpath_query})[1]", namespaces=ODF_NAMESPACES)
    if result:
        return Element.from_tag(result[0])
    return None

get_elements

get_elements(xpath_query: XPath | str) -> list[Element]

Returns a list of elements obtained by applying an XPath query.

Parameters:

Name Type Description Default
xpath_query XPath | str

The XPath query string or a compiled lxml.etree.XPath object.

required

Returns:

Type Description
list[Element]

list[Element]: A list of Element instances matching the query.

Source code in odfdo/element.py
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
def get_elements(self, xpath_query: XPath | str) -> list[Element]:
    """Returns a list of elements obtained by applying an XPath query.

    Args:
        xpath_query: The XPath query string or a compiled `lxml.etree.XPath` object.

    Returns:
        list[Element]: A list of Element instances matching the query.
    """
    if isinstance(xpath_query, str):
        elements = xpath_return_elements(xpath_compile(xpath_query), self.__element)
    else:
        elements = xpath_return_elements(xpath_query, self.__element)
    return [Element.from_tag_for_clone(e, None) for e in elements]

get_formatted_text

get_formatted_text(context: dict | None = None) -> str

Returns a formatted version of the element’s text.

This method is typically overridden by subclasses to provide specific text formatting based on the element type and context.

Parameters:

Name Type Description Default
context dict | None

Optional dictionary providing context for formatting.

None

Returns:

Name Type Description
str str

A formatted string representation of the element’s text.

Source code in odfdo/element.py
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
def get_formatted_text(self, context: dict | None = None) -> str:
    """Returns a formatted version of the element's text.

    This method is typically overridden by subclasses to provide specific
    text formatting based on the element type and context.

    Args:
        context: Optional dictionary providing context for formatting.

    Returns:
        str: A formatted string representation of the element's text.
    """
    return ""

get_frame

get_frame(
    position: int = 0,
    name: str | None = None,
    presentation_class: str | None = None,
    title: str | None = None,
    description: str | None = None,
    content: str | None = None,
) -> Frame | None

Returns a single frame that matches the specified criteria.

Parameters:

Name Type Description Default
position int

The 0-based index of the matching frame to return.

0
name str | None

The name of the frame.

None
presentation_class str | None

The presentation class to filter frames by.

None
title str | None

A regex pattern to match against the frame’s title.

None
description str | None

A regex pattern to match against the frame’s description.

None
content str | None

A regex pattern to match against the frame’s content.

None

Returns:

Type Description
Frame | None

Frame | None: A Frame instance, or None if no frame matches the criteria.

Source code in odfdo/element.py
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
def get_frame(
    self,
    position: int = 0,
    name: str | None = None,
    presentation_class: str | None = None,
    title: str | None = None,
    description: str | None = None,
    content: str | None = None,
) -> Frame | None:
    """Returns a single frame that matches the specified criteria.

    Args:
        position: The 0-based index of the matching frame to return.
        name: The name of the frame.
        presentation_class: The presentation class to filter frames by.
        title: A regex pattern to match against the frame's title.
        description: A regex pattern to match against the frame's description.
        content: A regex pattern to match against the frame's content.

    Returns:
        Frame | None: A Frame instance, or None if no frame matches the criteria.
    """
    return self._filtered_element(
        "descendant::draw:frame",
        position,
        draw_name=name,
        presentation_class=presentation_class,
        svg_title=title,
        svg_desc=description,
        content=content,
    )  # type: ignore[return-value]

get_frames

get_frames(
    presentation_class: str | None = None,
    style: str | None = None,
    title: str | None = None,
    description: str | None = None,
    content: str | None = None,
) -> list[Frame]

Returns all frames that match the specified criteria.

Parameters:

Name Type Description Default
presentation_class str | None

The presentation class to filter frames by.

None
style str | None

The name of the style to filter frames by.

None
title str | None

A regex pattern to match against the frame’s title.

None
description str | None

A regex pattern to match against the frame’s description.

None
content str | None

A regex pattern to match against the frame’s content.

None

Returns:

Type Description
list[Frame]

list[Frame]: A list of Frame instances matching the criteria.

Source code in odfdo/element.py
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
def get_frames(
    self,
    presentation_class: str | None = None,
    style: str | None = None,
    title: str | None = None,
    description: str | None = None,
    content: str | None = None,
) -> list[Frame]:
    """Returns all frames that match the specified criteria.

    Args:
        presentation_class: The presentation class to filter frames by.
        style: The name of the style to filter frames by.
        title: A regex pattern to match against the frame's title.
        description: A regex pattern to match against the frame's description.
        content: A regex pattern to match against the frame's content.

    Returns:
        list[Frame]: A list of Frame instances matching the criteria.
    """
    return self._filtered_elements(
        "descendant::draw:frame",
        presentation_class=presentation_class,
        draw_style=style,
        svg_title=title,
        svg_desc=description,
        content=content,
    )  # type: ignore[return-value]

get_header

get_header(
    position: int = 0,
    outline_level: str | None = None,
    content: str | None = None,
) -> Header | None

Returns a single header that matches the specified criteria.

Parameters:

Name Type Description Default
position int

The 0-based index of the matching header to return.

0
outline_level str | None

The outline level to filter headers by.

None
content str | None

A regex pattern to match against the header’s content.

None

Returns:

Type Description
Header | None

Header | None: A Header instance, or None if no header matches the criteria.

Source code in odfdo/element.py
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
def get_header(
    self,
    position: int = 0,
    outline_level: str | None = None,
    content: str | None = None,
) -> Header | None:
    """Returns a single header that matches the specified criteria.

    Args:
        position: The 0-based index of the matching header to return.
        outline_level: The outline level to filter headers by.
        content: A regex pattern to match against the header's content.

    Returns:
        Header | None: A Header instance, or None if no header matches the criteria.
    """
    return self._filtered_element(
        "descendant::text:h",
        position,
        outline_level=outline_level,
        content=content,
    )  # type: ignore[return-value]

get_headers

get_headers(
    style: str | None = None,
    outline_level: str | None = None,
    content: str | None = None,
) -> list[Header]

Returns all headers that match the specified criteria.

Parameters:

Name Type Description Default
style str | None

The name of the style to filter headers by.

None
outline_level str | None

The outline level to filter headers by.

None
content str | None

A regex pattern to match against the header’s content.

None

Returns:

Type Description
list[Header]

list[Header]: A list of Header instances matching the criteria.

Source code in odfdo/element.py
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
def get_headers(
    self,
    style: str | None = None,
    outline_level: str | None = None,
    content: str | None = None,
) -> list[Header]:
    """Returns all headers that match the specified criteria.

    Args:
        style: The name of the style to filter headers by.
        outline_level: The outline level to filter headers by.
        content: A regex pattern to match against the header's content.

    Returns:
        list[Header]: A list of Header instances matching the criteria.
    """
    return self._filtered_elements(
        "descendant::text:h",
        text_style=style,
        outline_level=outline_level,
        content=content,
    )  # type: ignore[return-value]

get_image

get_image(
    position: int = 0,
    name: str | None = None,
    url: str | None = None,
    content: str | None = None,
) -> DrawImage | None

Returns a single image that matches the specified criteria.

Parameters:

Name Type Description Default
position int

The 0-based index of the matching image to return.

0
name str | None

The name of the image (stored in its parent frame).

None
url str | None

A regex pattern to match against the image’s URL.

None
content str | None

A regex pattern to match against the image’s content.

None

Returns:

Type Description
DrawImage | None

DrawImage | None: A DrawImage instance, or None if no image matches the criteria.

Source code in odfdo/element.py
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
def get_image(
    self,
    position: int = 0,
    name: str | None = None,
    url: str | None = None,
    content: str | None = None,
) -> DrawImage | None:
    """Returns a single image that matches the specified criteria.

    Args:
        position: The 0-based index of the matching image to return.
        name: The name of the image (stored in its parent frame).
        url: A regex pattern to match against the image's URL.
        content: A regex pattern to match against the image's content.

    Returns:
        DrawImage | None: A DrawImage instance, or None if no image matches the criteria.
    """
    # The frame is holding the name
    if name is not None:
        frame = self._filtered_element(
            "descendant::draw:frame", position, draw_name=name
        )
        if frame is None:
            return None
        # The name is supposedly unique
        return frame.get_element("draw:image")  # type: ignore[return-value]
    return self._filtered_element(
        "descendant::draw:image", position, url=url, content=content
    )  # type: ignore[return-value]

get_images

get_images(
    style: str | None = None,
    url: str | None = None,
    content: str | None = None,
) -> list[DrawImage]

Returns all images that match the specified criteria.

Parameters:

Name Type Description Default
style str | None

The name of the style to filter images by.

None
url str | None

A regex pattern to match against the image’s URL.

None
content str | None

A regex pattern to match against the image’s content.

None

Returns:

Type Description
list[DrawImage]

list[DrawImage]: A list of DrawImage instances matching the criteria.

Source code in odfdo/element.py
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
def get_images(
    self,
    style: str | None = None,
    url: str | None = None,
    content: str | None = None,
) -> list[DrawImage]:
    """Returns all images that match the specified criteria.

    Args:
        style: The name of the style to filter images by.
        url: A regex pattern to match against the image's URL.
        content: A regex pattern to match against the image's content.

    Returns:
        list[DrawImage]: A list of DrawImage instances matching the criteria.
    """
    return self._filtered_elements(
        "descendant::draw:image", text_style=style, url=url, content=content
    )  # type: ignore[return-value]

get_office_names

get_office_names() -> list[str]

Returns all unique values of ‘office:name’ attributes within the element’s subtree.

Returns:

Type Description
list[str]

list[str]: A list of unique strings representing the ‘office:name’ attribute values.

Source code in odfdo/element.py
2425
2426
2427
2428
2429
2430
2431
2432
2433
def get_office_names(self) -> list[str]:
    """Returns all unique values of 'office:name' attributes within the element's subtree.

    Returns:
        list[str]: A list of unique strings representing the 'office:name' attribute values.
    """
    name_xpath_query = xpath_compile("//@office:name")
    strings = xpath_return_strings(name_xpath_query, self.__element)
    return list({name for name in strings if name})

get_orphan_draw_connectors

get_orphan_draw_connectors() -> list[ConnectorShape]

Returns a list of connectors that are not connected to any shapes.

Returns:

Type Description
list[ConnectorShape]

list[ConnectorShape]: A list of ConnectorShape instances that are orphans.

Source code in odfdo/element.py
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
def get_orphan_draw_connectors(self) -> list[ConnectorShape]:
    """Returns a list of connectors that are not connected to any shapes.

    Returns:
        list[ConnectorShape]: A list of ConnectorShape instances that are orphans.
    """
    connectors = []
    for connector in self.get_draw_connectors():
        start_shape = connector.get_attribute("draw:start-shape")
        end_shape = connector.get_attribute("draw:end-shape")
        if start_shape is None and end_shape is None:
            connectors.append(connector)
    return connectors

get_paragraph

get_paragraph(
    position: int = 0, content: str | None = None
) -> Paragraph | None

Returns a single paragraph that matches the specified criteria.

Parameters:

Name Type Description Default
position int

The 0-based index of the matching paragraph to return.

0
content str | None

A regex pattern to match against the paragraph’s content.

None

Returns:

Type Description
Paragraph | None

Paragraph | None: A Paragraph instance, or None if no paragraph matches the criteria.

Source code in odfdo/element.py
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
def get_paragraph(
    self,
    position: int = 0,
    content: str | None = None,
) -> Paragraph | None:
    """Returns a single paragraph that matches the specified criteria.

    Args:
        position: The 0-based index of the matching paragraph to return.
        content: A regex pattern to match against the paragraph's content.

    Returns:
        Paragraph | None: A Paragraph instance, or None if no paragraph matches the criteria.
    """
    return self._filtered_element(
        "descendant::text:p",
        position,
        content=content,
    )  # type: ignore[return-value]

get_paragraphs

get_paragraphs(
    style: str | None = None, content: str | None = None
) -> list[Paragraph]

Returns all paragraphs that match the specified criteria.

Parameters:

Name Type Description Default
style str | None

The name of the style to filter paragraphs by.

None
content str | None

A regex pattern to match against the paragraph’s content.

None

Returns:

Type Description
list[Paragraph]

list[Paragraph]: A list of Paragraph instances matching the criteria.

Source code in odfdo/element.py
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
def get_paragraphs(
    self,
    style: str | None = None,
    content: str | None = None,
) -> list[Paragraph]:
    """Returns all paragraphs that match the specified criteria.

    Args:
        style: The name of the style to filter paragraphs by.
        content: A regex pattern to match against the paragraph's content.

    Returns:
        list[Paragraph]: A list of Paragraph instances matching the criteria.
    """
    return self._filtered_elements(
        "descendant::text:p", text_style=style, content=content
    )  # type: ignore[return-value]

get_span

get_span(
    position: int = 0, content: str | None = None
) -> Span | None

Returns a single span that matches the specified criteria.

Parameters:

Name Type Description Default
position int

The 0-based index of the matching span to return.

0
content str | None

A regex pattern to match against the span’s content.

None

Returns:

Type Description
Span | None

Span | None: A Span instance, or None if no span matches the criteria.

Source code in odfdo/element.py
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
def get_span(
    self,
    position: int = 0,
    content: str | None = None,
) -> Span | None:
    """Returns a single span that matches the specified criteria.

    Args:
        position: The 0-based index of the matching span to return.
        content: A regex pattern to match against the span's content.

    Returns:
        Span | None: A Span instance, or None if no span matches the criteria.
    """
    return self._filtered_element(
        "descendant::text:span", position, content=content
    )  # type: ignore[return-value]

get_spans

get_spans(
    style: str | None = None, content: str | None = None
) -> list[Span]

Returns all spans that match the specified criteria.

Parameters:

Name Type Description Default
style str | None

The name of the style to filter spans by.

None
content str | None

A regex pattern to match against the span’s content.

None

Returns:

Type Description
list[Span]

list[Span]: A list of Span instances matching the criteria.

Source code in odfdo/element.py
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
def get_spans(
    self,
    style: str | None = None,
    content: str | None = None,
) -> list[Span]:
    """Returns all spans that match the specified criteria.

    Args:
        style: The name of the style to filter spans by.
        content: A regex pattern to match against the span's content.

    Returns:
        list[Span]: A list of Span instances matching the criteria.
    """
    return self._filtered_elements(
        "descendant::text:span", text_style=style, content=content
    )  # type: ignore[return-value]

get_style

get_style(
    family: str,
    name_or_element: str | Element | None = None,
    display_name: str | None = None,
) -> StyleBase | DrawFillImage | DrawMarker | None

Returns a single style uniquely identified by family/name, or a provided style object.

If the provided name_or_element is already a style object, it is returned directly. Use display_name if the style is known by its user-facing name instead of its internal name.

Parameters:

Name Type Description Default
family str

The style family (e.g., “paragraph”, “text”, “graphic”, “table”, “list”, “number”).

required
name_or_element str | Element | None

The internal name of the style, or an existing Style (or subclass) instance.

None
display_name str | None

The user-facing name of the style.

None

Returns:

Type Description
StyleBase | DrawFillImage | DrawMarker | None

StyleBase | DrawFillImage | DrawMarker | None: A style-like instance, or None if no matching style is found.

Raises:

Type Description
ValueError

If name_or_element is an Element but not a recognized odf_style.

Source code in odfdo/element.py
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
def get_style(
    self,
    family: str,
    name_or_element: str | Element | None = None,
    display_name: str | None = None,
) -> StyleBase | DrawFillImage | DrawMarker | None:
    """Returns a single style uniquely identified by family/name, or a
    provided style object.

    If the provided `name_or_element` is already a style object, it is
    returned directly. Use `display_name` if the style is known by its
    user-facing name instead of its internal name.

    Args:
        family: The style family (e.g., "paragraph", "text", "graphic",
            "table", "list", "number").
        name_or_element: The internal name of the style, or
            an existing Style (or subclass) instance.
        display_name: The user-facing name of the style.

    Returns:
        StyleBase | DrawFillImage | DrawMarker | None: A style-like
            instance, or None if no matching style is found.

    Raises:
        ValueError: If `name_or_element` is an Element but not a
            recognized odf_style.
    """
    if isinstance(name_or_element, Element):
        name = name_or_element.get_attribute("style:name")
        if name is not None:
            return name_or_element  # type: ignore[return-value]
        else:
            raise ValueError(f"Not a odf_style ? {name_or_element!r}")
    style_name = name_or_element
    is_default = not (style_name or display_name)
    tagname = self._get_style_tagname(family, is_default=is_default)
    # famattr became None if no "style:family" attribute
    if family:
        return self._filtered_element(
            tagname,
            0,
            style_name=style_name,
            display_name=display_name,
            family=family,
        )  # type: ignore[return-value]
    # family is empty
    if style_name:
        result = self._filtered_element(tagname, 0, style_name=style_name)
        if result:
            return result  # type: ignore[return-value]
        return self._filtered_element(tagname, 0, draw_name=style_name)  # type: ignore[return-value]

    if display_name:
        return self._filtered_element(tagname, 0, display_name=display_name)  # type: ignore[return-value]

    return self._filtered_element(tagname, 0)  # type: ignore[return-value]

get_styled_elements

get_styled_elements(name: str = '') -> list[Element]

Finds elements (paragraphs, tables, etc.) using a given style name.

Parameters:

Name Type Description Default
name str

The name of the style to filter by. If an empty string, all styled elements are returned.

''

Returns:

Type Description
list[Element]

list[Element]: A list of Element instances that match the specified style.

Source code in odfdo/element.py
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
def get_styled_elements(self, name: str = "") -> list[Element]:
    """Finds elements (paragraphs, tables, etc.) using a given style name.

    Args:
        name: The name of the style to filter by. If an empty string,
            all styled elements are returned.

    Returns:
        list[Element]: A list of Element instances that match the specified style.
    """
    # FIXME incomplete (and possibly inaccurate)
    return (
        self._filtered_elements("descendant::*", text_style=name)
        + self._filtered_elements("descendant::*", draw_style=name)
        + self._filtered_elements("descendant::*", draw_text_style=name)
        + self._filtered_elements("descendant::*", table_style=name)
        + self._filtered_elements("descendant::*", page_layout=name)
        + self._filtered_elements("descendant::*", master_page=name)
        + self._filtered_elements("descendant::*", parent_style=name)
    )

get_styles

get_styles(
    family: str | None = None,
) -> list[StyleBase | DrawFillImage | DrawMarker]

Returns all styles (common and default) that match the specified family.

Parameters:

Name Type Description Default
family str | None

The style family to filter by (e.g., “paragraph”, “text”). If None, retrieves all styles regardless of family.

None

Returns:

Type Description
list[StyleBase | DrawFillImage | DrawMarker]

list[StyleBase|DrawFillImage|DrawMarker]: A list of style-like

list[StyleBase | DrawFillImage | DrawMarker]

instances matching the criteria.

Source code in odfdo/element.py
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
def get_styles(
    self, family: str | None = None
) -> list[StyleBase | DrawFillImage | DrawMarker]:
    """Returns all styles (common and default) that match the specified family.

    Args:
        family: The style family to filter by (e.g., "paragraph", "text").
            If None, retrieves all styles regardless of family.

    Returns:
        list[StyleBase|DrawFillImage|DrawMarker]: A list of style-like
        instances matching the criteria.
    """
    # Both common and default styles
    tagname = self._get_style_tagname(family)
    return self._filtered_elements(tagname, family=family)  # type: ignore[return-value]

get_text_change

get_text_change(
    position: int = 0, idx: str | None = None
) -> TextChange | TextChangeStart | None

Returns a single text change that matches the specified criteria.

The change can be either a single deletion (text:change) or the start of a range of changes (text:change-start).

Parameters:

Name Type Description Default
position int

The 0-based index of the element to retrieve if several matches are found. Defaults to 0.

0
idx str | None

The change-id attribute of the element to match.

None

Returns:

Type Description
TextChange | TextChangeStart | None

TextChange | TextChangeStart | None: A TextChange or TextChangeStart instance, or None if no match is found.

Source code in odfdo/element.py
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
def get_text_change(
    self,
    position: int = 0,
    idx: str | None = None,
) -> TextChange | TextChangeStart | None:
    """Returns a single text change that matches the specified criteria.

    The change can be either a single deletion (text:change) or the start
    of a range of changes (text:change-start).

    Args:
        position: The 0-based index of the element to retrieve if
            several matches are found. Defaults to 0.
        idx: The `change-id` attribute of the element to match.

    Returns:
        TextChange | TextChangeStart | None: A TextChange or TextChangeStart
            instance, or None if no match is found.
    """
    if idx:
        request = (
            f'descendant::text:change-start[@text:change-id="{idx}"] '
            f'| descendant::text:change[@text:change-id="{idx}"]'
        )
        return self._filtered_element(request, 0)  # type: ignore[return-value]

    request = "descendant::text:change-start | descendant::text:change"
    return self._filtered_element(request, position)  # type: ignore[return-value]

get_text_change_deletion

get_text_change_deletion(
    position: int = 0, idx: str | None = None
) -> TextChange | None

Returns a single text change of deletion kind (text:change tag) matching criteria.

Consider using get_text_change() for a more general approach.

Parameters:

Name Type Description Default
position int

The 0-based index of the matching text:change element to return.

0
idx str | None

The change-id attribute of the element.

None

Returns:

Type Description
TextChange | None

TextChange | None: A TextChange instance, or None if no match is found.

Source code in odfdo/element.py
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
def get_text_change_deletion(
    self,
    position: int = 0,
    idx: str | None = None,
) -> TextChange | None:
    """Returns a single text change of deletion kind (text:change tag) matching criteria.

    Consider using `get_text_change()` for a more general approach.

    Args:
        position: The 0-based index of the matching text:change element to return.
        idx: The `change-id` attribute of the element.

    Returns:
        TextChange | None: A TextChange instance, or None if no match is found.
    """
    return self._filtered_element(
        "descendant::text:change", position, change_id=idx
    )  # type: ignore[return-value]

get_text_change_deletions

get_text_change_deletions() -> list[TextChange]

Returns all text changes representing deletions (text:change tags).

Consider using get_text_changes() for a more general approach.

Returns:

Type Description
list[TextChange]

list[TextChange]: A list of TextChange instances representing deletions.

Source code in odfdo/element.py
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
def get_text_change_deletions(self) -> list[TextChange]:
    """Returns all text changes representing deletions (text:change tags).

    Consider using `get_text_changes()` for a more general approach.

    Returns:
        list[TextChange]: A list of TextChange instances representing deletions.
    """
    return self._filtered_elements(
        "descendant::text:change",
    )  # type: ignore[return-value]

get_text_change_end

get_text_change_end(
    position: int = 0, idx: str | None = None
) -> TextChangeEnd | None

Returns a single text change-end element (text:change-end tag) matching criteria.

Consider using get_text_change() for a more general approach.

Parameters:

Name Type Description Default
position int

The 0-based index of the matching text:change-end element to return.

0
idx str | None

The change-id attribute of the element.

None

Returns:

Type Description
TextChangeEnd | None

TextChangeEnd | None: A TextChangeEnd instance, or None if no match is found.

Source code in odfdo/element.py
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
def get_text_change_end(
    self,
    position: int = 0,
    idx: str | None = None,
) -> TextChangeEnd | None:
    """Returns a single text change-end element (text:change-end tag) matching criteria.

    Consider using `get_text_change()` for a more general approach.

    Args:
        position: The 0-based index of the matching text:change-end element to return.
        idx: The `change-id` attribute of the element.

    Returns:
        TextChangeEnd | None: A TextChangeEnd instance, or None if no match is found.
    """
    return self._filtered_element(
        "descendant::text:change-end", position, change_id=idx
    )  # type: ignore[return-value]

get_text_change_ends

get_text_change_ends() -> list[TextChangeEnd]

Returns all text change-end elements (text:change-end tags).

Consider using get_text_changes() for a more general approach.

Returns:

Type Description
list[TextChangeEnd]

list[TextChangeEnd]: A list of TextChangeEnd instances.

Source code in odfdo/element.py
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
def get_text_change_ends(self) -> list[TextChangeEnd]:
    """Returns all text change-end elements (text:change-end tags).

    Consider using `get_text_changes()` for a more general approach.

    Returns:
        list[TextChangeEnd]: A list of TextChangeEnd instances.
    """
    return self._filtered_elements(
        "descendant::text:change-end",
    )  # type: ignore[return-value]

get_text_change_start

get_text_change_start(
    position: int = 0, idx: str | None = None
) -> TextChangeStart | None

Returns a single text change-start element (text:change-start tag) matching criteria.

Consider using get_text_change() for a more general approach.

Parameters:

Name Type Description Default
position int

The 0-based index of the matching text:change-start element to return.

0
idx str | None

The change-id attribute of the element.

None

Returns:

Type Description
TextChangeStart | None

TextChangeStart | None: A TextChangeStart instance, or None if no match is found.

Source code in odfdo/element.py
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
def get_text_change_start(
    self,
    position: int = 0,
    idx: str | None = None,
) -> TextChangeStart | None:
    """Returns a single text change-start element (text:change-start tag) matching criteria.

    Consider using `get_text_change()` for a more general approach.

    Args:
        position: The 0-based index of the matching text:change-start element to return.
        idx: The `change-id` attribute of the element.

    Returns:
        TextChangeStart | None: A TextChangeStart instance, or None if no match is found.
    """
    return self._filtered_element(
        "descendant::text:change-start", position, change_id=idx
    )  # type: ignore[return-value]

get_text_change_starts

get_text_change_starts() -> list[TextChangeStart]

Returns all text change-start elements (text:change-start tags).

Consider using get_text_changes() for a more general approach.

Returns:

Type Description
list[TextChangeStart]

list[TextChangeStart]: A list of TextChangeStart instances.

Source code in odfdo/element.py
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
def get_text_change_starts(self) -> list[TextChangeStart]:
    """Returns all text change-start elements (text:change-start tags).

    Consider using `get_text_changes()` for a more general approach.

    Returns:
        list[TextChangeStart]: A list of TextChangeStart instances.
    """
    return self._filtered_elements(
        "descendant::text:change-start",
    )  # type: ignore[return-value]

get_text_changes

get_text_changes() -> list[TextChange | TextChangeStart]

Returns all text changes, including single deletions (text:change) and starts of change ranges (text:change-start).

Returns:

Type Description
list[TextChange | TextChangeStart]

list[TextChange | TextChangeStart]: A list of TextChange or TextChangeStart instances.

Source code in odfdo/element.py
2890
2891
2892
2893
2894
2895
2896
2897
2898
def get_text_changes(self) -> list[TextChange | TextChangeStart]:
    """Returns all text changes, including single deletions (text:change) and
    starts of change ranges (text:change-start).

    Returns:
        list[TextChange | TextChangeStart]: A list of TextChange or TextChangeStart instances.
    """
    request = "descendant::text:change-start | descendant::text:change"
    return self._filtered_elements(request)  # type: ignore[return-value]

get_variable_set

get_variable_set(
    name: str, position: int = -1
) -> VarSet | None

Returns a single variable set that matches the specified criteria.

Parameters:

Name Type Description Default
name str

The name of the variable set to retrieve.

required
position int

The 0-based index of the matching variable set to return. A negative value (e.g., -1) typically refers to the last one found.

-1

Returns:

Type Description
VarSet | None

VarSet | None: A VarSet instance, or None if no variable set matches the criteria.

Source code in odfdo/element.py
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
def get_variable_set(self, name: str, position: int = -1) -> VarSet | None:
    """Returns a single variable set that matches the specified criteria.

    Args:
        name: The name of the variable set to retrieve.
        position: The 0-based index of the matching variable set to return.
            A negative value (e.g., -1) typically refers to the last one found.

    Returns:
        VarSet | None: A VarSet instance, or None if no variable set matches the criteria.
    """
    return self._filtered_element(
        "descendant::text:variable-set", position, text_name=name
    )  # type: ignore[return-value]

get_variable_set_value

get_variable_set_value(
    name: str, value_type: str | None = None
) -> (
    bool
    | str
    | int
    | float
    | Decimal
    | datetime
    | timedelta
    | None
)

Returns the value of the last variable set for the given name.

Parameters:

Name Type Description Default
name str

The name of the variable to retrieve its value.

required
value_type str | None

The expected type of the variable’s value. Can be ‘boolean’, ‘currency’, ‘date’, ‘float’, ‘percentage’, ‘string’, ‘time’, or None for automatic type detection.

None

Returns:

Type Description
bool | str | int | float | Decimal | datetime | timedelta | None

bool | str | int | float | Decimal | datetime | timedelta | None: The value of the variable, cast to the most appropriate Python type, or None if the variable set is not found.

Source code in odfdo/element.py
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
def get_variable_set_value(
    self,
    name: str,
    value_type: str | None = None,
) -> bool | str | int | float | Decimal | datetime | timedelta | None:
    """Returns the value of the last variable set for the given name.

    Args:
        name: The name of the variable to retrieve its value.
        value_type: The expected type of the variable's value.
            Can be 'boolean', 'currency', 'date', 'float', 'percentage',
            'string', 'time', or None for automatic type detection.

    Returns:
        bool | str | int | float | Decimal | datetime | timedelta | None:
            The value of the variable, cast to the most appropriate Python type,
            or None if the variable set is not found.
    """
    variable_set = self.get_variable_set(name)
    if not variable_set:
        return None
    return variable_set.get_value(value_type)  # type: ignore[return-value]

get_variable_sets

get_variable_sets(name: str | None = None) -> list[VarSet]

Returns all variable sets that match the specified criteria.

Parameters:

Name Type Description Default
name str | None

The name of the variable set to filter by.

None

Returns:

Type Description
list[VarSet]

list[VarSet]: A list of VarSet instances matching the criteria.

Source code in odfdo/element.py
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
def get_variable_sets(self, name: str | None = None) -> list[VarSet]:
    """Returns all variable sets that match the specified criteria.

    Args:
        name: The name of the variable set to filter by.

    Returns:
        list[VarSet]: A list of VarSet instances matching the criteria.
    """
    return self._filtered_elements(
        "descendant::text:variable-set",
        text_name=name,
    )  # type: ignore[return-value]

index

index(child: Element) -> int

Returns the position of a child element within this element.

Inspired by lxml’s behavior.

Parameters:

Name Type Description Default
child Element

The child element to find the index of.

required

Returns:

Name Type Description
int int

The 0-based index of the child element.

Source code in odfdo/element.py
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
def index(self, child: Element) -> int:
    """Returns the position of a child element within this element.

    Inspired by lxml's behavior.

    Args:
        child: The child element to find the index of.

    Returns:
        int: The 0-based index of the child element.
    """
    idx: int = self.__element.index(child.__element)
    return idx

insert

insert(
    element: Element,
    xmlposition: int | None = None,
    position: int | None = None,
    start: bool = False,
) -> None

Inserts an element relative to the current element.

Insertion can be done using DOM vocabulary (xmlposition) or by numeric position. If start is True, the element is inserted before any existing text content. Positions are 0-based.

Parameters:

Name Type Description Default
element Element

The element to insert.

required
xmlposition int | None

Specifies insertion relative to DOM, using FIRST_CHILD, LAST_CHILD, NEXT_SIBLING, or PREV_SIBLING.

None
position int | None

A 0-based numeric index for insertion. Used if xmlposition is None.

None
start bool

If True, insert the element before any existing text of the current element, preserving the text as the tail of the inserted element.

False

Raises:

Type Description
ValueError

If xmlposition is not defined and position is also None.

Source code in odfdo/element.py
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
def insert(
    self,
    element: Element,
    xmlposition: int | None = None,
    position: int | None = None,
    start: bool = False,
) -> None:
    """Inserts an element relative to the current element.

    Insertion can be done using DOM vocabulary (`xmlposition`) or by numeric position.
    If `start` is True, the element is inserted before any existing text content.
    Positions are 0-based.

    Args:
        element: The element to insert.
        xmlposition: Specifies insertion relative to DOM, using
            `FIRST_CHILD`, `LAST_CHILD`, `NEXT_SIBLING`, or `PREV_SIBLING`.
        position: A 0-based numeric index for insertion. Used if
            `xmlposition` is None.
        start: If True, insert the element before any existing text of the
            current element, preserving the text as the tail of the inserted element.

    Raises:
        ValueError: If `xmlposition` is not defined and `position` is also None.
    """
    # child_tag = element.tag
    current = self.__element
    lx_element = element.__element
    if start:
        text = current.text
        if text is not None:
            current.text = None
            tail = lx_element.tail
            if tail is None:
                tail = text
            else:
                tail = tail + text
            lx_element.tail = tail
        position = 0
    if position is not None:
        current.insert(position, lx_element)
    elif xmlposition is FIRST_CHILD:
        current.insert(0, lx_element)
    elif xmlposition is LAST_CHILD:
        current.append(lx_element)
    elif xmlposition is NEXT_SIBLING:
        parent = current.getparent()
        index = parent.index(current)
        parent.insert(index + 1, lx_element)
    elif xmlposition is PREV_SIBLING:
        parent = current.getparent()
        index = parent.index(current)
        parent.insert(index, lx_element)
    else:
        raise ValueError("(xml)position must be defined")

is_empty

is_empty() -> bool

Checks if the element is empty (no text, no children, no tail).

Returns:

Name Type Description
bool bool

True if the element is empty, False otherwise.

Source code in odfdo/element.py
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
def is_empty(self) -> bool:
    """Checks if the element is empty (no text, no children, no tail).

    Returns:
        bool: True if the element is empty, False otherwise.
    """
    element = self.__element
    if element.tail is not None:
        return False
    if element.text is not None:
        return False
    if list(element.iterchildren()):  # noqa: SIM103
        return False
    return True

match

match(pattern: str) -> bool

Checks if a pattern is found one or more times within the element’s text content.

Python regular expression syntax applies.

Parameters:

Name Type Description Default
pattern str

The regex pattern to match.

required

Returns:

Name Type Description
bool bool

True if the pattern is found, False otherwise.

Source code in odfdo/element.py
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
def match(self, pattern: str) -> bool:
    """Checks if a pattern is found one or more times within the element's text content.

    Python regular expression syntax applies.

    Args:
        pattern: The regex pattern to match.

    Returns:
        bool: True if the pattern is found, False otherwise.
    """
    return self.search(pattern) is not None

replace

replace(
    pattern: str,
    new: str | None = None,
    formatted: bool = False,
) -> int

Replaces occurrences of a pattern with new text within the element’s content.

It cannot replace patterns found across several elements (e.g., a word split into two consecutive spans).

Python regular expression syntax applies.

If formatted is True, and the target is a Paragraph, Span, or Header, and the replacement text contains spaces, tabs, or newlines, an attempt is made to convert them into actual ODF elements to obtain a formatted result. On very complex contents, the result may differ from expectations.

Parameters:

Name Type Description Default
pattern str

The regex pattern to search and replace.

required
new str | None

The replacement string. If None, it counts occurrences. If an empty string, it deletes matches.

None
formatted bool

If True, attempts to convert whitespace in replacement text to ODF elements for formatting.

False

Returns:

Name Type Description
int int

The number of replacements made.

Source code in odfdo/element.py
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
def replace(
    self,
    pattern: str,
    new: str | None = None,
    formatted: bool = False,
) -> int:
    """Replaces occurrences of a pattern with new text within the element's content.

    It cannot replace patterns found across several elements (e.g., a word
    split into two consecutive spans).

    Python regular expression syntax applies.

    If `formatted` is True, and the target is a Paragraph, Span, or Header,
    and the replacement text contains spaces, tabs, or newlines, an attempt
    is made to convert them into actual ODF elements to obtain a formatted result.
    On very complex contents, the result may differ from expectations.

    Args:
        pattern: The regex pattern to search and replace.
        new: The replacement string. If None, it counts occurrences.
            If an empty string, it deletes matches.
        formatted: If True, attempts to convert whitespace in replacement
            text to ODF elements for formatting.

    Returns:
        int: The number of replacements made.
    """
    if not isinstance(pattern, str):
        # Fail properly if the pattern is an non-ascii bytestring
        pattern = str(pattern)
    cpattern = re.compile(pattern)
    count = 0
    for text in self.xpath("descendant::text()"):
        if new is None:
            count += len(cpattern.findall(str(text)))
        else:
            new_text, number = cpattern.subn(new, str(text))
            container = text.parent
            if not container:  # pragma: nocover
                continue
            if text.is_text():  # type: ignore
                container.text = new_text
            else:
                container.tail = new_text
            if formatted and container.tag in {  # type; ignore
                "text:h",
                "text:p",
                "text:span",
            }:
                container.append_plain_text("")  # type: ignore[attr-defined]
            count += number
    return count

replace_element

replace_element(
    old_element: Element, new_element: Element
) -> None

Replaces an existing sub-element with a new one in place.

Warning: This operation does not clone the old_element; it is directly removed from the tree.

Parameters:

Name Type Description Default
old_element Element

The existing child element to be replaced.

required
new_element Element

The new element to insert in place of old_element.

required
Source code in odfdo/element.py
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
def replace_element(self, old_element: Element, new_element: Element) -> None:
    """Replaces an existing sub-element with a new one in place.

    Warning: This operation does not clone the `old_element`; it is directly
    removed from the tree.

    Args:
        old_element: The existing child element to be replaced.
        new_element: The new element to insert in place of `old_element`.
    """
    current = self.__element
    current.replace(old_element.__element, new_element.__element)

search

search(pattern: str) -> int | None

Returns the first position of a pattern in the element’s text content.

Python regular expression syntax applies.

Parameters:

Name Type Description Default
pattern str

The regex pattern to search for.

required

Returns:

Type Description
int | None

int | None: The starting index of the first match, or None if not found.

Source code in odfdo/element.py
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
def search(self, pattern: str) -> int | None:
    """Returns the first position of a pattern in the element's text content.

    Python regular expression syntax applies.

    Args:
        pattern: The regex pattern to search for.

    Returns:
        int | None: The starting index of the first match, or None if not found.
    """
    match = re.search(pattern, self.text_recursive)
    if match is None:
        return None
    return match.start()

search_all

search_all(pattern: str) -> list[tuple[int, int]]

Returns all start and end positions of a regex pattern in the element’s text content.

Python regular expression syntax applies.

Parameters:

Name Type Description Default
pattern str

The regex pattern to search for.

required

Returns:

Type Description
list[tuple[int, int]]

list[tuple[int, int]]: A list of (start_position, end_position) tuples for all matches.

Source code in odfdo/element.py
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
def search_all(self, pattern: str) -> list[tuple[int, int]]:
    """Returns all start and end positions of a regex pattern in the element's text content.

    Python regular expression syntax applies.

    Args:
        pattern: The regex pattern to search for.

    Returns:
        list[tuple[int, int]]: A list of (start_position, end_position) tuples for all matches.
    """
    results: list[tuple[int, int]] = []
    for match in re.finditer(pattern, self.text_recursive):
        results.append((match.start(), match.end()))
    return results

search_first

search_first(pattern: str) -> tuple[int, int] | None

Returns the start and end positions of the first occurrence of a regex pattern.

Python regular expression syntax applies.

Parameters:

Name Type Description Default
pattern str

The regex pattern to search for.

required

Returns:

Type Description
tuple[int, int] | None

tuple[int, int] | None: A tuple (start_position, end_position) of the first match, or None if no match is found.

Source code in odfdo/element.py
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
def search_first(self, pattern: str) -> tuple[int, int] | None:
    """Returns the start and end positions of the first occurrence of a regex pattern.

    Python regular expression syntax applies.

    Args:
        pattern: The regex pattern to search for.

    Returns:
        tuple[int, int] | None: A tuple (start_position, end_position) of the
            first match, or None if no match is found.
    """
    match = re.search(pattern, self.text_recursive)
    if match is None:
        return None
    return match.start(), match.end()

serialize

serialize(
    pretty: bool = False, with_ns: bool = False
) -> str

Returns the text serialization of the XML element.

Parameters:

Name Type Description Default
pretty bool

If True, the output XML will be pretty-printed.

False
with_ns bool

If True, namespace declarations will be included in the output.

False

Returns:

Name Type Description
str str

The serialized XML content as a string.

Source code in odfdo/element.py
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
def serialize(self, pretty: bool = False, with_ns: bool = False) -> str:
    """Returns the text serialization of the XML element.

    Args:
        pretty: If True, the output XML will be pretty-printed.
        with_ns: If True, namespace declarations will be included in the output.

    Returns:
        str: The serialized XML content as a string.
    """
    # This copy bypasses serialization side-effects in lxml
    native = deepcopy(self.__element)
    data: str = tostring(
        native,
        with_tail=False,
        pretty_print=pretty,
        encoding="unicode",
    )
    if with_ns:
        return data
    # Remove namespaces
    return self._strip_namespaces(data)

set_attribute

set_attribute(
    name: str,
    value: bool | str | tuple[int, int, int] | None,
) -> None

Sets the value of a specified attribute.

Handles special cases for color properties and boolean values.

Parameters:

Name Type Description Default
name str

The qualified name of the attribute to set.

required
value bool | str | tuple[int, int, int] | None

The value to set. Can be a boolean, string, a color tuple (R, G, B), or None. If None, the attribute is removed.

required

Raises:

Type Description
TypeError

If a boolean value is provided for a color property.

Source code in odfdo/element.py
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
def set_attribute(
    self, name: str, value: bool | str | tuple[int, int, int] | None
) -> None:
    """Sets the value of a specified attribute.

    Handles special cases for color properties and boolean values.

    Args:
        name: The qualified name of the attribute to set.
        value: The value to set.
            Can be a boolean, string, a color tuple (R, G, B), or None.
            If None, the attribute is removed.

    Raises:
        TypeError: If a boolean value is provided for a color property.
    """
    if name in ODF_COLOR_PROPERTY:
        if isinstance(value, bool):
            raise TypeError(f"Wrong color type {value!r}")
        if value != "transparent":
            value = hexa_color(value)
    element = self.__element
    lxml_tag = _get_lxml_tag_or_name(name)
    if isinstance(value, bool):
        value = Boolean.encode(value)
    elif value is None:
        with contextlib.suppress(KeyError):
            del element.attrib[lxml_tag]
        return
    element.set(lxml_tag, str(value))

set_style_attribute

set_style_attribute(
    name: str, value: Style | str | None
) -> None

Sets a style-related attribute, allowing a Style object as a value.

Parameters:

Name Type Description Default
name str

The qualified name of the style attribute to set.

required
value Style | str | None

The value for the style attribute. Can be a Style object (its name will be used), a string, or None.

required
Source code in odfdo/element.py
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
def set_style_attribute(self, name: str, value: Style | str | None) -> None:
    """Sets a style-related attribute, allowing a Style object as a value.

    Args:
        name: The qualified name of the style attribute to set.
        value: The value for the style attribute.
            Can be a `Style` object (its name will be used), a string, or None.
    """
    if isinstance(value, Element):
        value = str(value.name)
    return self.set_attribute(name, value)

text_at

text_at(start: int, end: int | None = None) -> str

Returns the recursive text content of the element between specified positions.

Parameters:

Name Type Description Default
start int

The starting character position (0-based).

required
end int | None

The ending character position (exclusive). If None, returns text from start to the end.

None

Returns:

Name Type Description
str str

The substring of the element’s recursive text.

Source code in odfdo/element.py
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
def text_at(self, start: int, end: int | None = None) -> str:
    """Returns the recursive text content of the element between specified positions.

    Args:
        start: The starting character position (0-based).
        end: The ending character position (exclusive). If None,
            returns text from `start` to the end.

    Returns:
        str: The substring of the element's recursive text.
    """
    if start < 0:
        start = 0
    if end is None:
        return self.text_recursive[start:]
    else:
        if end < start:
            end = start
        return self.text_recursive[start:end]

xpath

xpath(xpath_query: str) -> list[Element | EText]

Applies an XPath query to the element and its subtree.

Parameters:

Name Type Description Default
xpath_query str

The XPath query string to apply.

required

Returns:

Type Description
list[Element | EText]

list[Element | EText]: A list of matching Element or EText instances.

Source code in odfdo/element.py
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
def xpath(self, xpath_query: str) -> list[Element | EText]:
    """Applies an XPath query to the element and its subtree.

    Args:
        xpath_query: The XPath query string to apply.

    Returns:
        list[Element | EText]: A list of matching Element or EText instances.
    """
    xpath_instance = xpath_compile(xpath_query)
    x_elements = xpath_instance(self.__element)
    result: list[Element | EText] = []
    if isinstance(x_elements, list):
        for obj in x_elements:
            if isinstance(obj, (str, bytes)):
                result.append(EText(obj))
            elif isinstance(obj, _Element):  # pragma: nocover
                result.append(Element.from_tag(obj))
    return result

PropDef

Bases: NamedTuple

Named tuple for class properties (internal).

Attributes:

Name Type Description
attr str
family str
name str
Source code in odfdo/element.py
162
163
164
165
166
167
class PropDef(NamedTuple):
    """Named tuple for class properties (internal)."""

    name: str
    attr: str
    family: str = ""

attr instance-attribute

attr: str

family class-attribute instance-attribute

family: str = ''

name instance-attribute

name: str

PropDefBool

Bases: NamedTuple

Named tuple for boolean class properties (internal).

Attributes:

Name Type Description
attr str
default bool
name str
Source code in odfdo/element.py
170
171
172
173
174
175
class PropDefBool(NamedTuple):
    """Named tuple for boolean class properties (internal)."""

    name: str
    attr: str
    default: bool = False

attr instance-attribute

attr: str

default class-attribute instance-attribute

default: bool = False

name instance-attribute

name: str

_decode_qname

_decode_qname(qname: str) -> tuple[str | None, str]

Decode a prefixed qualified XML name into its URI and local name.

For example, “office:document” would be decoded to (“urn:oasis:names:tc:opendocument:xmlns:office:1.0”, “document”).

Parameters:

Name Type Description Default
qname str

The qualified name (e.g., “prefix:localname” or “localname”).

required

Returns:

Type Description
tuple[str | None, str]

tuple[str | None, str]: A tuple containing the namespace URI (or None if no prefix) and the local name.

Raises:

Type Description
ValueError

If the XML prefix is unknown.

Source code in odfdo/element.py
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
def _decode_qname(qname: str) -> tuple[str | None, str]:
    """Decode a prefixed qualified XML name into its URI and local name.

    For example, "office:document" would be decoded to
    ("urn:oasis:names:tc:opendocument:xmlns:office:1.0", "document").

    Args:
        qname: The qualified name (e.g., "prefix:localname" or "localname").

    Returns:
        tuple[str | None, str]: A tuple containing the namespace URI (or None if no prefix)
            and the local name.

    Raises:
        ValueError: If the XML prefix is unknown.
    """
    if ":" in qname:
        prefix, name = qname.split(":")
        try:
            uri = ODF_NAMESPACES[prefix]
        except KeyError as e:
            raise ValueError(f'XML prefix "{prefix}" is unknown') from e
        return uri, name
    return None, qname

_family_style_tagname

_family_style_tagname(family: str) -> str

Map a style family string to its corresponding ODF tag name.

Parameters:

Name Type Description Default
family str

The style family (e.g., “paragraph”, “text”).

required

Returns:

Name Type Description
str str

The ODF tag name associated with the style family.

Raises:

Type Description
ValueError

If the provided family is unknown.

Source code in odfdo/element.py
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
def _family_style_tagname(family: str) -> str:
    """Map a style family string to its corresponding ODF tag name.

    Args:
        family: The style family (e.g., "paragraph", "text").

    Returns:
        str: The ODF tag name associated with the style family.

    Raises:
        ValueError: If the provided family is unknown.
    """
    try:
        return FAMILY_MAPPING[family]
    except KeyError as e:
        raise ValueError(f"Unknown family: {family!r}") from e

_generate_odf_namespaces

_generate_odf_namespaces() -> dict[str, str]
Source code in odfdo/element.py
138
139
140
141
142
def _generate_odf_namespaces() -> dict[str, str]:
    namespaces = _ODF_NAMESPACES_CORE.copy()
    if USE_LO_EXTENSIONS:
        namespaces.update(_ODF_NAMESPACES_EXTENSIONS)
    return namespaces

_get_lxml_tag

_get_lxml_tag(qname: str) -> str

Convert a prefixed qualified name (e.g., “prefix:name”) to an lxml-style tag name (e.g., “{uri}name”).

Parameters:

Name Type Description Default
qname str

The qualified name in “prefix:name” format.

required

Returns:

Name Type Description
str str

The tag name in lxml’s “{uri}name” format.

Source code in odfdo/element.py
238
239
240
241
242
243
244
245
246
247
248
def _get_lxml_tag(qname: str) -> str:
    """Convert a prefixed qualified name (e.g., "prefix:name") to an lxml-style tag name (e.g., "{uri}name").

    Args:
        qname: The qualified name in "prefix:name" format.

    Returns:
        str: The tag name in lxml's "{uri}name" format.
    """
    uri, name = _decode_qname(qname)
    return f"{{{uri}}}{name}"

_get_lxml_tag_or_name

_get_lxml_tag_or_name(qname: str) -> str

Convert a prefixed qualified name to an lxml-style tag name or just the local name.

If the qualified name has a prefix, it’s converted to “{uri}name” format. If it has no prefix, it returns just the local name.

Parameters:

Name Type Description Default
qname str

The qualified name (e.g., “prefix:localname” or “localname”).

required

Returns:

Name Type Description
str str

The tag name in lxml’s “{uri}name” format, or the local name if no prefix.

Source code in odfdo/element.py
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
def _get_lxml_tag_or_name(qname: str) -> str:
    """Convert a prefixed qualified name to an lxml-style tag name or just the local name.

    If the qualified name has a prefix, it's converted to "{uri}name" format.
    If it has no prefix, it returns just the local name.

    Args:
        qname: The qualified name (e.g., "prefix:localname" or "localname").

    Returns:
        str: The tag name in lxml's "{uri}name" format, or the local name if no prefix.
    """
    uri, name = _decode_qname(qname)
    if uri is None:
        return name
    return f"{{{uri}}}{name}"

_get_prefixed_name

_get_prefixed_name(tag: str) -> str

Convert an lxml-style tag name (e.g., “{uri}name”) to a prefixed name (e.g., “prefix:name”).

Parameters:

Name Type Description Default
tag str

The tag name in lxml’s “{uri}name” format.

required

Returns:

Name Type Description
str str

The tag name in “prefix:name” format.

Source code in odfdo/element.py
222
223
224
225
226
227
228
229
230
231
232
233
234
235
def _get_prefixed_name(tag: str) -> str:
    """Convert an lxml-style tag name (e.g., "{uri}name") to a prefixed name (e.g., "prefix:name").

    Args:
        tag: The tag name in lxml's "{uri}name" format.

    Returns:
        str: The tag name in "prefix:name" format.
    """
    if "}" not in tag:
        return f":{tag}"
    uri, name = tag.split("}", 1)
    prefix = _uri_to_prefix(uri[1:])
    return f"{prefix}:{name}"

_register_element_class

_register_element_class(
    cls: type[Element], qname: str
) -> None
Source code in odfdo/element.py
395
396
397
398
399
400
401
402
403
404
405
def _register_element_class(cls: type[Element], qname: str) -> None:
    # Turn tag name into what lxml is expecting
    tag = _get_lxml_tag(qname)
    if tag in _class_registry:  # pragma: nocover
        msg = f"Class with tag {qname!r} already seen: {_class_registry[tag]!r}"
        raise RuntimeError(msg)
    _class_registry[tag] = cls
    if qname in _tag_class_registry:  # pragma: nocover
        msg = f"Class with tag {qname!r} already seen: {_tag_class_registry[qname]!r}"
        raise RuntimeError(msg)
    _tag_class_registry[qname] = cls

_uri_to_prefix

_uri_to_prefix(uri: str) -> str

Find the XML prefix associated with a given namespace URI.

Parameters:

Name Type Description Default
uri str

The namespace URI to look up.

required

Returns:

Name Type Description
str str

The corresponding XML prefix.

Raises:

Type Description
ValueError

If the URI is not found in the known ODF namespaces.

Source code in odfdo/element.py
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
def _uri_to_prefix(uri: str) -> str:
    """Find the XML prefix associated with a given namespace URI.

    Args:
        uri: The namespace URI to look up.

    Returns:
        str: The corresponding XML prefix.

    Raises:
        ValueError: If the URI is not found in the known ODF namespaces.
    """
    for key, value in ODF_NAMESPACES.items():
        if value == uri:
            return key
    raise ValueError(f"uri {uri!r} not found")

class_from_tag

class_from_tag(qname: str) -> type[Element]

Retrieves the Python class associated with a given ODF qualified tag name.

This function looks up the registered class for a specific ODF XML tag, allowing for dynamic instantiation of the correct Element subclass based on the tag.

Parameters:

Name Type Description Default
qname str

The qualified name of the ODF tag (e.g., “text:p”, “office:body”).

required

Returns:

Type Description
type[Element]

The Python class (a subclass of Element) registered for the given tag.

Raises:

Type Description
KeyError

If no class is registered for the provided qualified name.

Source code in odfdo/element.py
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
def class_from_tag(qname: str) -> type[Element]:
    """Retrieves the Python class associated with a given ODF qualified tag
    name.

    This function looks up the registered class for a specific ODF XML tag,
    allowing for dynamic instantiation of the correct Element subclass based
    on the tag.

    Args:
        qname: The qualified name of the ODF tag (e.g., "text:p",
            "office:body").

    Returns:
        The Python class (a subclass of Element) registered for the given tag.

    Raises:
        KeyError: If no class is registered for the provided qualified name.
    """
    return _tag_class_registry[qname]

register_element_class

register_element_class(cls: type[Element]) -> None

(internal function) Associate a qualified element name to a Python class that handles this type of element.

Getting the right Python class when loading an existing ODF document is then transparent. Unassociated elements will be handled by the base Element class.

Parameters:

Name Type Description Default
cls type[Element]

Python class, subtype of Element.

required
Source code in odfdo/element.py
359
360
361
362
363
364
365
366
367
368
369
370
371
def register_element_class(cls: type[Element]) -> None:
    """(internal function) Associate a qualified element name to a Python class
    that handles this type of element.

    Getting the right Python class when loading an existing ODF document is
    then transparent. Unassociated elements will be handled by the base
    Element class.

    Args:
        cls: Python class, subtype of Element.
    """
    # Turn tag name into what lxml is expecting
    _register_element_class(cls, cls._tag)

register_element_class_list

register_element_class_list(
    cls: type[Element], tag_list: Iterable[str]
) -> None

(internal function) Associate a qualified element name to a Python class that handles this type of element.

Getting the right Python class when loading an existing ODF document is then transparent. Unassociated elements will be handled by the base Element class.

Most styles use the “style:style” qualified name and only differ by their “style:family” attribute. So the “family” attribute was added to register specialized style classes.

Parameters:

Name Type Description Default
cls type[Element]

Python class.

required
tag_list Iterable[str]

Iterable of qname tags for the class.

required
Source code in odfdo/element.py
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
def register_element_class_list(cls: type[Element], tag_list: Iterable[str]) -> None:
    """(internal function) Associate a qualified element name to a Python class
    that handles this type of element.

    Getting the right Python class when loading an existing ODF document is
    then transparent. Unassociated elements will be handled by the base
    Element class.

    Most styles use the "style:style" qualified name and only differ by their
    "style:family" attribute. So the "family" attribute was added to register
    specialized style classes.

    Args:
        cls: Python class.
        tag_list: Iterable of qname tags for the class.
    """
    # Turn tag name into what lxml is expecting
    for qname in tag_list:
        _register_element_class(cls, qname)

xpath_compile cached

xpath_compile(path: str) -> XPath

Compile an XPath query string into an lxml.etree.XPath object.

This function pre-compiles XPath expressions for efficiency and automatically includes ODF namespaces. It is cached to avoid recompiling the same XPath query multiple times.

Parameters:

Name Type Description Default
path str

The XPath query string.

required

Returns:

Name Type Description
XPath XPath

A compiled lxml.etree.XPath object.

Source code in odfdo/element.py
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
@cache
def xpath_compile(path: str) -> XPath:
    """Compile an XPath query string into an `lxml.etree.XPath` object.

    This function pre-compiles XPath expressions for efficiency and
    automatically includes ODF namespaces. It is cached to avoid recompiling
    the same XPath query multiple times.

    Args:
        path: The XPath query string.

    Returns:
        XPath: A compiled `lxml.etree.XPath` object.
    """
    return XPath(path, namespaces=ODF_NAMESPACES, regexp=False)

xpath_return_elements

xpath_return_elements(
    xpath: XPath, target: _Element
) -> list[_Element]

Execute a compiled XPath query and return a list of matching lxml elements.

This function filters the raw XPath results to ensure only lxml.etree._Element objects are returned.

Parameters:

Name Type Description Default
xpath XPath

A compiled lxml.etree.XPath object.

required
target _Element

The lxml element on which to apply the XPath query.

required

Returns:

Type Description
list[_Element]

list[_Element]: A list of matching lxml.etree._Element objects.

Source code in odfdo/element.py
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
def xpath_return_elements(xpath: XPath, target: _Element) -> list[_Element]:
    """Execute a compiled XPath query and return a list of matching lxml elements.

    This function filters the raw XPath results to ensure only `lxml.etree._Element`
    objects are returned.

    Args:
        xpath: A compiled `lxml.etree.XPath` object.
        target: The lxml element on which to apply the XPath query.

    Returns:
        list[_Element]: A list of matching `lxml.etree._Element` objects.
    """
    elements = xpath(target)
    try:
        return [e for e in elements if isinstance(e, _Element)]
    except TypeError as e:  # pragma: nocover
        # cant happen
        msg = f"Bad XPath result, list expected, got {elements!r}"
        raise TypeError(msg) from e

xpath_return_strings

xpath_return_strings(
    xpath: XPath, target: _Element
) -> list[str]

Execute a compiled XPath query and return a list of matching strings.

This function filters the raw XPath results to ensure only string objects are returned.

Parameters:

Name Type Description Default
xpath XPath

A compiled lxml.etree.XPath object.

required
target _Element

The lxml element on which to apply the XPath query.

required

Returns:

Type Description
list[str]

list[str]: A list of matching string objects.

Source code in odfdo/element.py
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
def xpath_return_strings(xpath: XPath, target: _Element) -> list[str]:
    """Execute a compiled XPath query and return a list of matching strings.

    This function filters the raw XPath results to ensure only string objects
    are returned.

    Args:
        xpath: A compiled `lxml.etree.XPath` object.
        target: The lxml element on which to apply the XPath query.

    Returns:
        list[str]: A list of matching string objects.
    """
    elements = xpath(target)
    try:
        return [s for s in elements if isinstance(s, str)]
    except TypeError as e:  # pragma: nocover
        # cant happen
        msg = f"Bad XPath result, list expected, got {elements!r}"
        raise TypeError(msg) from e