You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

对接XML格式RESTful接口:lxml.objectify无法修改子元素值求助

搞定lxml.objectify中凭证子元素的访问与修改

嘿,我完全懂你的纠结——xmltodict虽然顺手但写起来确实有点啰嗦,lxml.objectify的Pythonic写法才是真的香!别着急,我来给你捋清楚怎么用它访问和修改credentials的子元素。

首先先假设你的目标XML结构大概是这样的(如果和你的实际结构有出入,调整属性名就行):

<api_request>
  <credentials>
    <username>default_user</username>
    <password>default_pass</password>
  </credentials>
  <other_data>some_value</other_data>
</api_request>

1. 解析XML到objectify对象

先把XML字符串或者文件解析成lxml的objectify对象:

from lxml import objectify

# 假设xml_str是你的XML内容
xml_str = """<api_request>
  <credentials>
    <username>default_user</username>
    <password>default_pass</password>
  </credentials>
</api_request>"""

# 解析XML
root = objectify.fromstring(xml_str)

2. 访问credentials的子元素

lxml.objectify最爽的点就是直接用属性访问,不用像字典那样写['key'],直接点就行:

# 获取credentials下的username和password
username = root.credentials.username
password = root.credentials.password

print(f"当前用户名: {username}")
print(f"当前密码: {password}")

输出会是:

当前用户名: default_user
当前密码: default_pass

3. 修改子元素的值

修改也同样直接,给属性赋值就行:

# 修改用户名和密码
root.credentials.username = "new_admin"
root.credentials.password = "super_secure_pass"

# 如果要新增一个子元素(比如token),直接赋值就行
root.credentials.token = "abc123xyz"

4. 把修改后的对象转回XML字符串

修改完之后,要转回XML的话,可以这样做:

# 先清理objectify的命名空间(避免生成多余的ns0前缀)
objectify.deannotate(root, cleanup_namespaces=True)
# 转回XML字符串
updated_xml = objectify.tostring(root, pretty_print=True, encoding='utf-8').decode('utf-8')

print(updated_xml)

输出的XML会是:

<api_request>
  <credentials>
    <username>new_admin</username>
    <password>super_secure_pass</password>
    <token>abc123xyz</token>
  </credentials>
</api_request>

可能踩坑的地方

如果你的XML里有同名的子元素(比如多个<credential>),那你需要用索引来访问,比如root.credentials[0].username;另外如果元素名里有特殊字符(比如连字符),那你得用getattr()来访问,比如getattr(root.credentials, 'user-name')。

对比xmltodict的嵌套字典写法,lxml.objectify直接点属性的方式是不是清爽多了?

内容的提问来源于stack exchange,提问作者Dkellygb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:27:17