我需要获取特定属性的所有值。该属性的标记名称可能不同,属性可能位于xml树中的任何级别(根级别/子级别/等)。 请考虑以下xml
<?xml version="1.0" encoding="utf-8"?>
<college name ="xyz"/>
<university>
<college name = "abc1" id = "a"/>
<college name = "abc2" id = "b"/>
<sub-univ>
<sub-univ-col name = "sfd"/>
</sub-univ>
</university>
<school name = "asdf"/>enter code here
我如何获得&#34; name&#34;的价值?来自所有xml标签的属性。? XML文件,我有比上述例子更多的级别。有没有办法在没有解析每个级别的情况下获取值?
答案 0 :(得分:1)
在任何支持XPath
的解析器中都很简单。例如,lxml
:
doc = lxml.etree.fromstring(that_xml_you_gave)
doc.xpath('//@name')
Out[208]: ['xyz', 'abc1', 'abc2', 'sfd', 'asdf']
答案 1 :(得分:0)
如果您使用Beautiful Soup,这将变得非常简单:
from bs4 import BeautifulSoup
xml = '''
<?xml version="1.0" encoding="utf-8"?>
<college name ="xyz"/>
<university>
<college name = "abc1" id = "a"/>
<college name = "abc2" id = "b"/>
<sub-univ>
<sub-univ-col name = "sfd"/>
</sub-univ>
</university>
<school name = "asdf"/>
'''
soup = BeautifulSoup(xml)
names = [tag.get('name') for tag in soup.find_all()]
print(names)
结果:
['xyz', None, 'abc1', 'abc2', None, 'sfd', 'asdf']
请注意,我们使用tag.get(...)
,因为某些代码没有name
属性。或者,您可以改为:
names = [tag['name'] for tag in soup.find_all() if tag.has_attr('name')]
结果:
['xyz', 'abc1', 'abc2', 'sfd', 'asdf']