Python lxml 判断 body sectPr pgBorders 元素是否存在
你可以使用 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。最后,我们检查变量 body、sectPr 和 pgBorders 是否存在来判断相应的元素是否存在。
原文地址: https://www.cveoy.top/t/topic/oso3 著作权归作者所有。请勿转载和采集!