docx_parser_converter.docx_parsers.helpers.common_helpers module
- docx_parser_converter.docx_parsers.helpers.common_helpers.extract_attribute(element: Element | None, attr: str) str | None[source]
Extracts an attribute value from an XML element.
- Parameters:
element (Optional[Element]) – The XML element.
attr (str) – The attribute name.
- Returns:
The attribute value, or None if not found.
- Return type:
Optional[str]
Example
The following is an example of extracting the ‘val’ attribute from a style element in a document.xml file:
<w:pStyle w:val="Heading1"/>
- Usage:
style_val = extract_attribute(style_element, ‘val’)
- docx_parser_converter.docx_parsers.helpers.common_helpers.extract_boolean_attribute(element: Element | None) bool | None[source]
Extracts a boolean attribute from an XML element.
- Parameters:
element (Optional[Element]) – The XML element.
- Returns:
- True if the element is present and its ‘val’ attribute is not ‘false’ or ‘0’,
False if its ‘val’ attribute is ‘false’ or ‘0’, None if the element is not present.
- Return type:
Optional[bool]
Example
The following is an example of extracting a boolean attribute from an element:
<w:b w:val="true"/>
- Usage:
bold = extract_boolean_attribute(bold_element) # Returns True if w:val is not ‘false’ or ‘0’
- docx_parser_converter.docx_parsers.helpers.common_helpers.extract_element(parent: Element | None, path: str) Element | None[source]
Extracts an XML element from the parent element using the given path.
- Parameters:
parent (Optional[Element]) – The parent XML element.
path (str) – The XPath to the desired child element.
- Returns:
The extracted XML element, or None if not found or if parent is None.
- Return type:
Optional[Element]
Example
The following is an example of extracting a paragraph properties element from a paragraph element in a document.xml file:
<w:p> <w:pPr> <!-- Paragraph properties here --> </w:pPr> </w:p>
- Usage:
pPr = extract_element(paragraph_element, “.//w:pPr”)
- docx_parser_converter.docx_parsers.helpers.common_helpers.safe_int(value: str | None) int | None[source]
Converts a string value to an integer safely.
- Parameters:
value (Optional[str]) – The string value to convert.
- Returns:
The integer value, or None if the input is None.
- Return type:
Optional[int]
Example
The following is an example of safely converting a string to an integer:
int_value = safe_int("123") # Returns 123 int_value = safe_int(None) # Returns None