【问题标题】:ElementTree and finding with NameSpacesElementTree 和使用 NameSpaces 查找
【发布时间】:2014-03-31 14:45:34
【问题描述】:

我有一个有效的 XHTML 文件。当我这样做时

import xml.etree.ElementTree as ET
print ET._namespace_map

它列出:

'http://www.w3.org/1999/xhtml': 'html'

当我这样做时:

root.find('{http://www.w3.org/1999/xhtml}head')

它找到了:

<Element '{http://www.w3.org/1999/xhtml}head' at 0x104647168>

但是当我这样做时:

root.find('html:head')

它抱怨:

SyntaxError: prefix 'html' not found in prefix map

是否可以使用 ns:element 语法找到带有 find 的名称空间元素?

【问题讨论】:

    标签: python xml elementtree


    【解决方案1】:

    您应该指定namespaces 参数:

    namespaces = {'html': 'http://www.w3.org/1999/xhtml'}
    root.find('html:head', namespaces=namespaces)
    

    另见:

    【讨论】:

    • 好的,可以了,谢谢!但是,register_namespace_namespace_map 有什么用处?
    • @EcirHana register_namespace() 本质上是一种操纵_namespace_map 的新方法(元素树>=1.3),看看它们对here 有什么好处。希望对您有所帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-17
    • 2014-09-15
    • 1970-01-01
    相关资源
    最近更新 更多