对于使用lxml.etree导航具有名称空间的xml文档,我有点困惑。我在这个主题(1,2)和lxml文档上见过几个线程,但仍然没有找到答案。
xml = """<?xml version='1.0' encoding='UTF-8' standalone='no'?>
<sbml xmlns="http://www.sbml.org/sbml/level2" level="2" metaid="metaid_0000001" version="1">
<model id="Teusink2000_Glycolysis" metaid="metaid_0000002" name="Teusink2000_Glycolysis">
<annotation>
</annotation>
</model>
</sbml>"""
from lxml import etree
utf8_parser = etree.XMLParser(encoding='utf-8')
xml = etree.fromstring(xml.encode('utf-8'), parser=utf8_parser)搜索根元素似乎不起作用,但我想这是因为它是根元素,因此不需要搜索它。
print(xml.nsmap)
print(xml.findall('sbml'))
print(xml.findall('sbml', namespaces=xml.nsmap))
print(xml.findall('sbml', namespaces={'': 'http://www.sbml.org/sbml/level2'}))产生
{None: 'http://www.sbml.org/sbml/level2'}
[]
[]
[]但是,搜索model元素是否有效,前提是为它提供一个命名空间。
print(xml.findall('model'))
print(xml.findall('model', namespaces=xml.nsmap))
print(xml.findall('model', namespaces={'': 'http://www.sbml.org/sbml/level2'}))产生
[]
[<Element {http://www.sbml.org/sbml/level2}model at 0x2125d7c0888>]
[<Element {http://www.sbml.org/sbml/level2}model at 0x2125d7c0448>]但是,搜索annotation元素并不像我预期的那样有效。
print(xml.findall('annotation'))
print(xml.findall('annotation', namespaces=xml.nsmap))
print(xml.findall('annotation', namespaces={'': 'http://www.sbml.org/sbml/level2'}))产生
[]
[]
[]有人能指出我在这里错过了什么吗?
发布于 2020-02-15 21:23:10
你的语法错了。您只能使用annotation搜索当前级别。如果要搜索整个树,则需要使用print(xml.findall('.//annotation', namespaces=xml.nsmap))。
print(xml.findall('.//annotation', namespaces=xml.nsmap))
# [<Element {http://www.sbml.org/sbml/level2}annotation at 0x7fbcb9a14308>]https://stackoverflow.com/questions/60243018
复制相似问题