【问题标题】:Parsing a specific element from XML using Python/ET使用 Python/ET 从 XML 中解析特定元素
【发布时间】:2013-03-13 15:41:01
【问题描述】:

我的 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 获取“我感兴趣的一些文本”?

提前感谢您的帮助!

【问题讨论】:

    标签: python xml parsing elementtree


    【解决方案1】:

    您需要通过指定命名空间来查找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 映射在内部所做的。

    【讨论】:

    • 感谢您的帮助。
    • 顺便说一句,这个方法在导入 cElementTree 时不起作用;仅使用 ElementTree
    猜你喜欢
    • 2014-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-26
    • 1970-01-01
    • 2018-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多