在Python中创建用于xml.etree.ElementTree.findall()的字典时,默认名称空间是否存在键? [英] Is there a key for the default namespace when creating dictionary for use with xml.etree.ElementTree.findall() in Python?

查看:164
本文介绍了在Python中创建用于xml.etree.ElementTree.findall()的字典时,默认名称空间是否存在键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用默认名称空间来解析XML文档,即根节点具有 xmlns 属性。如果要尝试在子节点中查找某些标记,这会很烦人,因为每个标记都有默认名称空间作为前缀。



xml.etree。 ElementTree.findall()允许传入命名空间字典,但我似乎找不到默认名称空间映射到的内容。我尝试使用'default',None和'xmlns'都没有成功。



似乎有效的一个选项是将传递给<$ c $的标记添加为前缀c> findall()和'xmlns:'(编辑:这实际上可以是任意唯一的名称),并在名称空间字典中有一个对应的条目,但是我想知道这是否有必要。 p>

编辑:我应该提到这是Python 3.3.2。我相信在较旧的Python版本中, findall()不接受 namespaces 参数。

解决方案

决定查看该方法的源代码。事实证明,xml.etree.ElementPath中的以下代码正在执行肮脏的工作:

  def xpath_tokenizer(pattern, namespaces = None):
用于xpath_tokenizer_re.findall(pattern)中的令牌:
tag = token [1]
if tag和tag [0]!= {和:标签:
尝试:
前缀,uri = tag.split(:,1)
如果不是名称空间:
引发KeyError
yield token [0], {%s}%s%(命名空间[前缀],uri)
,但KeyError:
引发SyntaxError(前缀%r在前缀映射中找不到%前缀)
其他:
收益令牌

模式是标记传递到 findall()中。如果在标记中未找到,则令牌生成器将返回标记而无需任何替换。


I'm trying to parse an XML document with a default namespace, i.e. the root node has an xmlns attribute. This is annoying if you want to try find certain tags in the child nodes because each tag is prefixed with the default namespace.

xml.etree.ElementTree.findall() allows for a namespaces dictionary to be passed in but I can't seem to find what the default namespace is mapped to. I have tried using 'default', None, 'xmlns' with no success.

One option that does seem to work is to prefix the tag passed to findall() with 'xmlns:' (EDIT: this can be any arbitrary unique name actually) and a corresponding entry in the namespaces dictionary but I'm wondering if that is even necessary.

EDIT: I should mention this is Python 3.3.2. I believe in older versions of Python, findall() does not accept a namespaces argument.

解决方案

Decided to take a look at the source code for the method. So as it turns out, the following code in xml.etree.ElementPath is doing the dirty work:

def xpath_tokenizer(pattern, namespaces=None):
    for token in xpath_tokenizer_re.findall(pattern):
        tag = token[1]
        if tag and tag[0] != "{" and ":" in tag:
            try:
                prefix, uri = tag.split(":", 1)
                if not namespaces:
                    raise KeyError
                yield token[0], "{%s}%s" % (namespaces[prefix], uri)
            except KeyError:
                raise SyntaxError("prefix %r not found in prefix map" % prefix)
        else:
            yield token

pattern is the tag passed into findall(). If there is no : found in the tag, the tokenizer simply returns the tag back without any substitutions.

这篇关于在Python中创建用于xml.etree.ElementTree.findall()的字典时,默认名称空间是否存在键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆