Python lxml库的objectify怎么用 简化XML访问

14次阅读

lxml.objectify 是 lxml 中用于简化 XML 访问的模块,将 XML 元素映射为 python 对象,支持点号访问子元素、属性和文本;重复元素转为列表;提供安全访问、动态修改与序列化功能,并自动类型转换

Python lxml库的objectify怎么用 简化XML访问

lxml.objectify 是 lxml 库中专为简化 XML 数据访问而设计的模块,它把 XML 元素自动映射成 Python 对象,支持用点号(.)直接访问子元素、属性和文本内容,比 etree 更直观,特别适合结构清晰、标签语义明确的 XML。

基本用法:解析并访问元素和属性

objectify 把 XML 标签转为对象,子元素变成属性,属性值通过 get()@attrname 语法获取,文本内容通过 text 属性读取。

示例:

from lxml import objectify 

xml_str = ''' Python Cookbook David Beazley 49.99 '''

root = objectify.fromstring(xml_str) print(root.title.text) # "Python Cookbook" print(root.author.text) # "David Beazley" print(root.price.text) # "49.99" print(root.get("id")) # "123" print(root.price.get("currency")) # "USD"

处理重复子元素(列表式访问)

当某个标签出现多次时(如多个 ),objectify 自动将其转为 Python 列表,可直接用索引或 for 循环遍历。

立即学习Python免费学习笔记(深入)”;

示例:

xml_str = '''    David Beazley   Brian Jones  ''' 

root = objectify.fromstring(xml_str) for author in root.author: print(author.text) # 输出两个作者名

或直接取第一个

print(root.author[0].text)

安全访问:避免 AttributeError

如果某子元素可能不存在,直接点取会抛出 AttributeError。可用 getattr()objectify.ObjectifiedElement.find() 安全访问。

  • getattr(root, 'missing', None) 提供默认值
  • root.find('optional_tag') 返回 Element 或 None
  • 对文本内容,建议先判断是否存在再取 .text,例如:if hasattr(root, 'note'): print(root.note.text)

修改与序列化

objectify 对象支持动态赋值(新增/修改元素或属性),修改后调用 objectify.deannotate()etree.tostring() 输出标准 XML。

示例:

from lxml import objectify, etree 

root = objectify.fromstring('1') root.count = 42 # 修改文本 root.count.set('unit', 'items') # 添加属性 root.new_field = 'hello' # 新增子元素

清理命名空间注解(可选),然后转回字符串

objectify.deannotate(root, cleanup_namespaces=True) print(etree.tostring(root, encoding='unicode', pretty_print=True))

不复杂但容易忽略:objectify 默认会把数字、布尔等文本尝试转成对应 Python 类型(如 42root.val == 42),若需保持字符串,可用 objectify.PyType(int) 等显式控制,或统一用 str(root.val) 转换。

text=ZqhQzanResources