首页 > 解决方案 > 使用与 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 生成它?

标签: pythonxmlms-word

解决方案


推荐阅读