你可以使用XPath表达式来查找XML中的元素并判断它们是否存在。以下是一个示例代码,可以判断body元素、sectPr元素和pgBorders元素是否存在:

from lxml import etree

# 解析XML文档
doc = etree.parse('your_xml_file.xml')

# 使用XPath查找元素
body = doc.xpath('//w:body', namespaces={'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'})
sectPr = doc.xpath('//w:sectPr', namespaces={'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'})
pgBorders = doc.xpath('//w:pgBorders', namespaces={'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'})

# 判断元素是否存在
if body:
    print('body exists')
else:
    print('body does not exist')

if sectPr:
    print('sectPr exists')
else:
    print('sectPr does not exist')

if pgBorders:
    print('pgBorders exists')
else:
    print('pgBorders does not exist')

在上面的代码中,我们使用XPath表达式//w:body//w:sectPr//w:pgBorders查找XML文档中的元素。注意,我们在XPath表达式中使用了namespaces参数来指定命名空间,这是因为XML文档中的元素都有一个命名空间前缀w。最后,我们检查变量bodysectPrpgBorders是否存在来判断相应的元素是否存在

python lxml 判断 body sectPr pgBorders 是否存在

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

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