python - 使用与 OOXML 命名空间匹配的 XML 编写 Open Office XML(例如 docx)
问题描述
我有一个在 .docx 文件中编辑 XML 的 python 程序。我想用 ETree 编辑 XML。
当我从 .docx 文件中读取 XML 时,它的开头是这样的:
b'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n<w:document xmlns:wpc="http://schemas.micro'...
这是在一个名为 的变量中data
。我创建元素树:
import xml.etree.ElementTree as ElementTree
tree = ElementTree.XML(data)
我将其转换回:
data = ElementTree.tostring(tree)
但是,XML 发生了细微的变化。现在看起来像这样:
b'<ns0:document xmlns:ns0="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:ns1="ht...
Word 不会读取它,即使它是标准 XML。
编辑:我尝试将字符串添加到我的 XML 中,只是为了让它往返:
XML_HEADER=b'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
tree = ElementTree.XML(data)
data = XML_HEADER + ElementTree.tostring(tree)
但我仍然得到错误:
We're sorry. We can't open <filename>.docx because we found a problem with its contents.
Details:
The XML data is invalid according to the schema.
Location: Part: /word/document.xml, Line: 0, Column:0
我无法修复单词。我必须生成看起来与我开始使用的 XML 完全相同的 XML。如何让 ETree 生成它?
解决方案
推荐阅读
- java - Swagger UI 不显示对象类型的模型类字段的描述
- c# - 如何从 JSON 字符串中的字符串中删除双引号?
- windows - 这个 PowerShell 脚本是什么意思?
- hex - 将 ASCII 转换为十六进制(.scc 兼容)
- gitlab - 在自托管的 gitlab 实例中使文件夹可公开访问
- model-binding - 用于铸造模型属性的 Livewire 模型绑定
- javascript - 按名称动态调用从另一个模块导入的 javascript 函数
- php - 当使用对象的属性作为 where 语句的输入时,雄辩的查询构建器得到“BadMethodCallException”
- token - 使用提升的访问令牌运行时,对物理驱动器序列号的 WMI 查询返回不同的结果
- amazon-web-services - 是否可以在 SAML 响应到达 cognito 之前拦截它?