gpt4 book ai didi

python - 使用 ElementTree 解析带有命名空间的 XML 字符串

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

我用谷歌搜索了我的裤子,但无济于事。我想做的很简单:我想使用 ElementTree 访问字符串中包含的以下 XML 中的 UniqueID 值。

from xml.etree.ElementTree import fromstring

xml_string = """<ListObjectsResponse xmlns='http://www.example.com/dir/'>
<Item>
<UniqueID>abcdefghijklmnopqrstuvwxyz0123456789</UniqueID>
</Item>
</ListObjectsResponse>"""

NS = "http://www.example.com/dir/"

tree = fromstring(xml_string)

我知道我应该使用 fromstring 方法来解析 XML 字符串,但我似乎无法确定如何访问 UniqueID。我不确定如何针对命名空间使用 findfindallfindtext 方法。

非常感谢任何帮助。

最佳答案

以下应该让你继续:

>>> tree.findall('*/*')
[<Element '{http://www.example.com/dir/}UniqueID' at 0x10899e450>]

这列出了比树的根低两层的所有元素(在您的例子中是 UniqueID 元素)。或者,您可以使用 tree.find() 在此级别仅查找 first 元素。然后可以直接获取UniqueID元素的文本内容:

>>> unique_id_elmt = tree.find('*/*')  # First (and only) element two levels below the root
>>> unique_id_elmt
<Element '{http://www.example.com/dir/}UniqueID' at 0x105ec9450>
>>> unique_id_elmt.text # Text contained in UniqueID
'abcdefghijklmnopqrstuvwxyz0123456789'

或者,您可以通过指定其 full path 直接找到一些精确的元素:

>>> tree.find('{{{0}}}Item/{{{0}}}UniqueID'.format(NS))  # Tags are prefixed with NS
<Element '{http://www.example.com/dir/}UniqueID' at 0x10899ead0>

正如 Tomalak 指出的那样,Fredrik Lundh's site 可能包含有用的信息;你想检查如何处理 prefixes:实际上可能有一种更简单的方法来处理它们,而不是在上面的方法中显式指定 NS 路径。

关于python - 使用 ElementTree 解析带有命名空间的 XML 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8511208/

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