[英]How do you insert a lxml tag with namespace while skipping xmlns?
I'm trying to write my python scripts using python-docx to add equations to docx files.我正在尝试使用 python-docx 编写我的 python 脚本以将方程添加到 docx 文件。 Since this is not supported by python-docx yet, I need to modify the OOXML directly using lxml.由于 python-docx 尚不支持此功能,因此我需要直接使用 lxml 修改 OOXML。 I'd need to add some tags so the resulting XML looks like this:我需要添加一些标签,所以生成的 XML 看起来像这样:
<m:r>
<m:t>(5−x)</m:t>
</m:r>
I can't create a new naked <m:r>
node using lxml.我无法使用 lxml 创建新的裸<m:r>
节点。 Using something like the following code使用类似下面的代码
new_node = etree.Element('{m}r', nsmap={'m': ''})
gives me a <m:r xmlns:m="m">
node, except I don't need the xmlns part.给了我一个<m:r xmlns:m="m">
节点,除了我不需要 xmlns 部分。 (python-docx handles the remaining XML operations for me, and if the xmlns is there, the docx file actually wouldn't be recognised by MS Word.) Is there any way to make a naked <m:r>
node? (python-docx 为我处理剩余的 XML 操作,如果 xmlns 在那里,则 MS Word 实际上不会识别 docx 文件。)有没有办法制作一个裸<m:r>
节点?
python-docx
is aware of the "m": "http://schemas.openxmlformats.org/officeDocument/2006/math"
namespace-prefix mapping: https://github.com/python-openxml/python-docx/blob/master/docx/oxml/ns.py#L18 python-docx
知道"m": "http://schemas.openxmlformats.org/officeDocument/2006/math"
命名空间前缀映射: https://github.com/python-openxml/python-docx/blob /master/docx/oxml/ns.py#L18
So you can use python-docx
internals to create such an element:所以你可以使用python-docx
internals 来创建这样一个元素:
from docx.oxml import OxmlElement
r = OxmlElement("m:r")
You can then use that element like you would any other lxml
element, like appending or inserting it as a child of some other element.然后,您可以像使用任何其他lxml
元素一样使用该元素,例如将其作为某个其他元素的子元素附加或插入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.