使用Python/ET从XML解析特定元素

2024-04-25 01:06:25 发布

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

我有以下几行XML:

<?xml version="xxx"?>
<doc:document xmlns:doc="some value 1...">
    <rdf:RDF xmlns:rdf="some value 2...">
        <rdf:Description rdf:about="some value...">
            <dct:format xmlns:dct="http://someurl/">some value 3</dct:format>
            <dct:title xmlns:dct="http://someurl/">some text of interest to me</dct:title>
        </rdf:Description>
    </rdf:RDF>
</doc:document>

如何使用Python/ETree获取“我感兴趣的一些文本”?你知道吗

提前感谢您的帮助!你知道吗


Tags: formathttpdoctitlevaluesomerdfdescription
1条回答
网友
1楼 · 发布于 2024-04-25 01:06:25

您需要通过指定命名空间来查找title元素:

tree.find('.//dct:title', namespaces={'dct': 'http://purl.org/dc/terms/'})

必须在每次搜索时传递namespaces映射,因此您也可以预先指定并重用:

nsmap = {
    'dct': 'http://purl.org/dc/terms/',
    'doc': 'http://www.witbd.org/xmlns/common/document/',
    'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
}

tree.find('.//dct:title', namespaces=nsmap)

对于示例文档(恢复了名称空间),它提供了:

>>> tree.find('.//dct:title', namespaces=nsmap)
<Element '{http://purl.org/dc/terms/}title' at 0x105ec4690>
>>> tree.find('.//dct:title', namespaces=nsmap).text
'some text of interest to me'

也可以在XPath表达式中使用命名空间:

tree.find('.//{http://purl.org/dc/terms/}title')

这就是使用前缀和namespaces映射在内部所做的。你知道吗

相关问题 更多 >