gpt4 book ai didi

python - 让 lxml.objectify 忽略 xml namespace ?

转载 作者:数据小太阳 更新时间:2023-10-29 02:01:19 24 4
gpt4 key购买 nike

所以我必须处理一些如下所示的 xml:

<ns2:foobarResponse xmlns:ns2="http://api.example.com">
<duration>206</duration>
<artist>
<tracks>...</tracks>
</artist>
</ns2:foobarResponse>

我找到了 lxml,它是 objectify模块,让您以 pythonic 方式遍历 xml 文档,如字典。
问题是:每次您尝试访问元素时,它都在使用伪造的 xml 命名空间,如下所示:

from lxml import objectify

tree = objectify.fromstring(xml)
print tree.artist
# ERROR: no such child: {http://api.example.com}artist

它正在尝试访问 <artist>使用父 namespace ,但标签不使用 ns。

有什么办法解决这个问题吗?谢谢

最佳答案

根据 lxml.objectify documentation ,属性查找默认使用其父元素的命名空间。

您可能想要工作的是:

print tree["{}artist"]

如果您的 child 有一个非空命名空间(例如“{ http://foo/ }artist”),这样的 QName 语法就可以工作,但不幸的是,目前的源代码似乎将一个空命名空间视为 没有 命名空间,所以 objectify 的所有查找优点都将有助于用父命名空间替换空命名空间,而你运气不好。

这要么是错误(“{}artist”应该有效),要么是提交给 lxml 人员的增强请求。

目前,最好的做法可能是:

print tree.xpath("artist")

我不清楚在这里使用 xpath 会对性能造成多大影响,但这确实有效。

关于python - 让 lxml.objectify 忽略 xml namespace ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3103661/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com