Python lxml 判断 Word 文档中 body、sectPr、pgBorders 节点是否存在
使用 lxml 中的 XPath 表达式可以判断 body、sectPr 和 pgBorders 是否存在。具体方法如下:
- 导入 lxml 库
from lxml import etree
- 构造 XML 文档
xml_str = '''
<w:document xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'>
<w:body>
<w:p>
<w:r>
<w:t>Hello World!</w:t>
</w:r>
</w:p>
</w:body>
<w:sectPr>
<w:pgBorders>
<w:top w:val='single' w:sz='4' w:space='0' w:color='auto'/>
<w:left w:val='single' w:sz='4' w:space='0' w:color='auto'/>
<w:bottom w:val='single' w:sz='4' w:space='0' w:color='auto'/>
<w:right w:val='single' w:sz='4' w:space='0' w:color='auto'/>
</w:pgBorders>
</w:sectPr>
</w:document>
'''
doc = etree.fromstring(xml_str)
- 使用 XPath 表达式判断节点是否存在
body = doc.xpath('//w:body', namespaces={'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'})
if body:
print('body exists')
else:
print('body not exists')
sectPr = doc.xpath('//w:sectPr', namespaces={'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'})
if sectPr:
print('sectPr exists')
else:
print('sectPr not exists')
pgBorders = doc.xpath('//w:pgBorders', namespaces={'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'})
if pgBorders:
print('pgBorders exists')
else:
print('pgBorders not exists')
输出结果为:
body exists
sectPr exists
pgBorders exists
注意:
- 在 XPath 表达式中使用命名空间
namespaces={'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'},以确保能够正确解析 Word 文档的 XML 结构。 - 以上示例使用了简单的 XML 字符串,实际应用中需要读取 Word 文档的 XML 内容。
原文地址: https://www.cveoy.top/t/topic/oBhN 著作权归作者所有。请勿转载和采集!