尝试将XML从字符串解析成Python

2024-09-30 01:28:00 发布

您现在位置:Python中文网/ 问答频道 /正文

首先是绳子

'<?xml version="1.0" encoding="UTF-8"?><metalink version="3.0" xmlns="http://www.metalinker.org/" xmlns:lcgdm="LCGDM:" generator="lcgdm-dav" pubdate="Fri, 11 Oct 2013 12:46:10 GMT"><files><file name="/lhcb/L"><size>173272912</size><resources><url type="https">https://test-kit.test.de:2880/pnfs/test.file</url><url type="https">https://test.grid.sara.nl:2882/pnfs/test.file</url></resources></file></files></metalink>'

我要提取的是url文本。以下代码可以工作,但由于是硬编码,因此存在缺陷:

^{pr2}$

因此,只有在xml结构相同的情况下,这才有效。我尝试过使用xpath,但始终无法使用它或使用标记。我从来没有得到任何结果。在

是xml字符串的格式有问题还是我做错了什么?在


Tags: httpstesturlsizeversiontypefilesxml
2条回答

您使用了名称空间,因此需要在XPath中使用它们:

for entry in root.findall('.//{http://www.metalinker.org/}url'):
    print entry.text

您可以使用xpath(和Nodefindall函数)来获取url,但是由于根元素使用了xmlns="http://www.metalinker.org/",所以您还需要在xpath中使用{}。在

示例-

>>> root = fromstring(xml_string)
>>> urls = root.findall('.//{http://www.metalinker.org/}url')
>>> for url in urls:
...     print(url.text)
...
https://test-kit.test.de:2880/pnfs/test.file
https://test.grid.sara.nl:2882/pnfs/test.file

上面的xpath将找到xml中的所有url。在

相关问题 更多 >

    热门问题