使用lxm从xml中提取数据的最有效方法

2024-05-23 14:32:13 发布

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

下面是一个大型xml文件的片段。我想提取特定的名称空间,例如xmlns:dc="http://purl.org/dc/elements/1.1/"。目前我可以这样做:

tree = etree.parse(file)
    for element in tree.getiterator('{http://www.openarchives.org/OAI/2.0/}record'):
        for leaf in element.getiterator('{http://purl.org/dc/elements/1.1/}subject'):
            print(leaf)

问题是我希望为{http://purl.org/dc/elements/1.1/}命名空间中的多个标记获取数据。我还想简化一些事情,并一直在研究如何使用xpath,但似乎无法解决。我可以使用xpath吗?如果可以的话,如何使用?更重要的是,它对我的目标是否更好?在

以下是xml:

^{pr2}$

Tags: 文件inorgtreehttpfor空间xml
2条回答

不清楚您到底想访问什么,但请尝试以下方法:

from lxml import etree
doc=etree.parse( xmlfile )
ns={'dc': 'http://purl.org/dc/elements/1.1/', 
  'oai': 'http://www.openarchives.org/OAI/2.0/'}
doc.xpath( '//dc:subject' , namespaces=ns ) # get all of the dc:subjects
doc.xpath( '//dc:*', namespaces=ns )  # get all elements in dc: namespace
# more specific path 
doc.xpath( '/oai:OAI-PMH/oai:ListRecords/oai:record/oai:metadata/*/dc:*', namespaces=ns )
x=doc.xpath( '/oai:OAI-PMH/oai:ListRecords/oai:record/oai:metadata/*' )
x[0].xpath( '*[contains(.,"Geo")]' )  # you can also call xpath from non document nodes
x[0].xpath( 'dc:subject/text()' , namespaces=ns ) # get the text of dc:subjects

在python或lxml文档之外阅读一些关于xpath的文档。 它们告诉您如何在python中使用xpath,但实际上并不是xpath教程。在

注意find()、findall()方法采用ElementPaths,这是一种 类xpath表达式的有限子集。在

for element in tree.findall(".//{http://purl.org/dc/elements/1.1/}subject"):
    print element

相关问题 更多 >