Adding Arbitrary XML to python-docx

I am thankful to the developers of python-docx, they did a great job, especially since OpenXML is beyond confusing. However, I have two respectful criticisms: Python-docx lacks several key features and though it is properly written…its really confusing to follow the code.

Its just a few steps. Identify the entry-point, create a new tag, and append it to the document.

from docx.oxml.shared import OxmlElement # Necessary Import
tags = document.element.xpath('//w:r') # Locate the right <w:r> tag
tag = tags[0] # Specify which <w:r> tag you want
child = OxmlElement('w:ARBITRARY') # Create arbitrary tag
tag.append(child) # Append in the new tag

And that’s it!

I also found inserting xml-snippet into docx using the python-docx api online (giving credit where credit is due). Defining the variables:

from docx.oxml.shared import qn
child.set( qn('w:val'), 'VALUE') # Add in the value



About Nahraf
Providing interesting insight into the world of Economics, Theology, Computer Science and Social phenomena.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: