可以使用lxml中的XPath表达式来判断body、sectPr和pgBorders是否存在。具体方法如下:

  1. 导入lxml库
from lxml import etree
  1. 构造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)
  1. 使用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
``
python lxml 如何判断 body sectPr pgBorders是否存在

原文地址: https://www.cveoy.top/t/topic/g7JK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录