Skip to content

Custom namespaces for XPath #621

Closed
Closed

Description

@fdabek1

I created a sample document in Word and the namespaces contained within it seem to be different than those that are natively included with python-docx. I found the included namespace map here.

And it appears that the newest version overrides the XPath function and uses these included namespaces. In previous versions of python-docx I would use the child's namespace directly in the function to ensure that it was found, but with this override I am unable to do it and get the error:

TypeError: xpath() got an unexpected keyword argument 'namespaces'

Here is my sample document:

https://github.com/fdabek1/random_files/blob/master/checkbox_control.docx

Below is some sample code:

from docx import Document

doc = Document('checkbox_control.docx')

for paragraph in doc.paragraphs:
    checkboxes = paragraph._element.xpath('w14:checkBox')

    # Old method that no longer works
    # checkboxes = paragraph._element.xpath('w14:checkBox', namespaces=paragraph._element.nsmap)

Being able to get this functionality back would be great as I am using python-docx to parse through some Word documents with a lot more ease than using lxml/etc for the entire document.

Activity

  1. fdabek1 commented on Feb 27, 2019

    @fdabek1
    Author

    I found a solution that works for now, but is quite hacky:

    from docx import Document
    from lxml import etree
    
    doc = Document('checkbox_control.docx')
    
    for paragraph in doc.paragraphs:
        checkboxes = etree.ElementBase.xpath(paragraph._element, './/w14:checkbox', namespaces=paragraph._element.nsmap)
    
        # Old method that no longer works
        # checkboxes = paragraph._element.xpath('w14:checkBox', namespaces=paragraph._element.nsmap)
    
    
  2. scanny commented on May 16, 2026

    @scanny
    Contributor

    Closed as inactive.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions