document.xml 是 docx 文件 zip 包中存储文档主体结构化内容的 xml 文件,位于 word/document.xml 路径,含段落、文本、样式引用等,但不含图片、元数据及页眉页脚等内容。

document.xml 是什么
document.xml 是一个 ZIP 压缩包内部的 XML 文件,位于 DOCX 文件的 word/document.xml 路径下。DOCX 本质上是多个 XML、rels、media 等文件组成的 ZIP 包,document.xml 存储了文档主体的结构化内容(段落、文字、样式引用等),但不包含二进制资源(如图片)或元数据(如作者、修改时间)。
它不是纯文本,而是带命名空间的 XML,含大量 w:t(文本节点)、w:tab、w:br、w:hyperlink 等元素,且文本常被拆散在多个 w:t 下(尤其含格式变化时)。
直接解压 + 解析 document.xml 提取文本
手动提取可行,但要注意以下几点:
- 必须先用 ZIP 工具解压 DOCX(DOCX 就是 ZIP,可直接改后缀为
.zip解压) - 不要依赖正则匹配文本,必须用 XML 解析器(如 Python 的
xml.etree.ElementTree或lxml) - 必须处理命名空间:
{<a href="https://www.php.cn/link/0f18e4824fc601cd270a4d31b084bb5d">https://www.php.cn/link/0f18e4824fc601cd270a4d31b084bb5d</a>},否则find('w:t')找不到节点 - 需合并连续的
w:t(同一段落内可能有多个,中间夹着w:tab或w:br)
import zipfile
from xml.etree import ElementTree as ET
<p>def extract_text_from_document_xml(docx_path):
with zipfile.ZipFile(docx_path) as docx:
with docx.open('word/document.xml') as f:
tree = ET.parse(f)
root = tree.getroot()
ns = {'w': '<a href="https://www.php.cn/link/0f18e4824fc601cd270a4d31b084bb5d">https://www.php.cn/link/0f18e4824fc601cd270a4d31b084bb5d</a>'}</p><pre class='brush:php;toolbar:false;'>text_parts = []
for t in root.findall('.//w:t', ns):
if t.text:
text_parts.append(t.text)
return ''.join(text_parts)示例调用
print(extract_text_from_document_xml('example.docx'))
为什么不用正则或字符串替换
-
document.xml 中文本可能被 CDATA 包裹(如含特殊字符)
-
w:t 可能为空,或仅含空格,或嵌套在 w:instrText(字段代码)中,误提取会导致乱码或错误内容
- 表格、文本框、页眉页脚的内容不在
document.xml,而在 word/document.xml 的子结构或单独文件(如 word/header1.xml)中
- 样式信息(加粗、颜色)不参与文本提取,但若需保留结构(如标题层级),就得解析
w:pStyle 和 w:pPr
更可靠的做法:用专业库替代手撕 XML
document.xml 中文本可能被 CDATA 包裹(如含特殊字符)w:t 可能为空,或仅含空格,或嵌套在 w:instrText(字段代码)中,误提取会导致乱码或错误内容document.xml,而在 word/document.xml 的子结构或单独文件(如 word/header1.xml)中w:pStyle 和 w:pPr
直接解析 document.xml 容易漏内容、难维护。实际项目中应优先使用成熟库:
- Python 推荐
python-docx:自动处理命名空间、段落/表格/列表/页眉页脚,还能读写 - Node.js 推荐
mammoth:专注从 DOCX 提取语义 HTML 或纯文本,对复杂格式鲁棒性好 - Java 推荐
Apache POI:支持低层 XML 访问,也提供高阶 API
# python-docx 示例(比手撕 XML 稳定得多)
from docx import Document
<p>doc = Document('example.docx')
full_text = []
for para in doc.paragraphs:
full_text.append(para.text)
for table in doc.tables:
for row in table.rows:
for cell in row.cells:
for para in cell.paragraphs:
full_text.append(para.text)
print('\n'.join(full_text))</p>真正容易被忽略的是:DOCX 中的文本分散在至少 5 个位置——document.xml、header<em>.xml</em>、footer.xml、footnotes.xml、endnotes.xml。只读 document.xml 就像只看主菜不吃配菜,看起来完整,其实漏了关键部分。










