Python 如何遍历etree.findall()中的列表
我想做下面的工作,但有一个困难的时间。如何在for循环中通过Python 如何遍历etree.findall()中的列表,python,lxml,python-3.3,Python,Lxml,Python 3.3,我想做下面的工作,但有一个困难的时间。如何在for循环中通过ns ns = ['one', 'two'] tree = etree.parse(file) for items in tree.findall('.//' + ns): print(items) 编辑: 正在寻找没有嵌套for循环的解决方案 编辑: 使用: 你用哪一个:lxml/xml.etree.ElementTree?我用的是lxml.etreegettinglxml.etree.xpathevaleror:Inv
ns
ns = ['one', 'two']
tree = etree.parse(file)
for items in tree.findall('.//' + ns):
print(items)
编辑:
正在寻找没有嵌套for循环的解决方案
编辑:
使用:
你用哪一个:
lxml
/xml.etree.ElementTree
?我用的是lxml.etreegettinglxml.etree.xpathevaleror:Invalid expression
@user1991424,你能发布(或上传)所用的xml吗?当然,它相当大。2.6mb@user1991424,将xml上传到某个地方,并告诉我url。@user1991424,ns
的实际值是多少?似乎不存在一个
或两个
标记。
ns = ['{http://purl.org/dc/elements/1.1/}identifier[@{http://www.w3.org/2001/XMLSchema-instance}type]',
'{http://purl.org/dc/elements/1.1/}title',
'{http://purl.org/dc/elements/1.1/}description',
'{http://purl.org/dc/elements/1.1/}subject',
'{http://purl.org/dc/elements/1.1/}type',
'{http://purl.org/dc/terms/}educationLevel']
tree = etree.parse(file)
for leaf in tree.xpath('//*[local-name()="record"]'):
for items in leaf.findall('.//' + ns[0]):
print(items)
from lxml import etree
nsmap = {
'xmlns': 'http://www.openarchives.org/OAI/2.0/',
'dc': 'http://purl.org/dc/elements/1.1/',
'dct': 'http://purl.org/dc/terms/',
'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
}
ns = [
'dc:identifier[@xsi:type]',
'dc:title',
'dc:description',
'dc:subject',
'dc:type',
'dct:educationLevel'
]
tree = etree.parse(file)
xpath = '|'.join('.//xmlns:record//{}'.format(n) for n in ns)
for items in tree.xpath(xpath, namespaces=nsmap):
print(items)