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 # 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