使用ElementTree 1.2.6在Python 2.6.6上解析Xml时获取命名空间数据

时间:2015-07-22 12:27:13

标签: python elementtree

我有一些我需要解析的xml,它以下列格式提供:

<Pres xmlns:abset="titan:arm:params:xml:ns:keyprov:abset">
<Set>
    <Key>
        <Id>c91e3882-e6f3-41f9-af52-3473a2c4615a</Id>
        <abset:Data>
            <abset:Tag>
                <abset:Value>i need this</abset:Value>
            </abset:Tag>
        </abset:Data>
    </Key>
</Set>
</Pres>

使用Python 2.7,我可以得到abset:值如下:

xmlstr          = '...'
root            = ElementTree.fromstring(xmlstr)

ns              = {'abset' : 'titan:arm:params:xml:ns:abset'}

keyElement      = root.find("./Set/Key")
value           = keyElement.find("./abset:Data/abset:Tag/abset:Value", ns).text

但是在python 2.6中,find命令不支持ns参数。

我试过了     ValElement = root.find(“./ Set / Key / abset:Data / abset:Tag / abset:Value”)     value = ValElement.text

但我得到的错误是

 keyelement      = root.find("./Set/Key/abset:Data/abset:Tag/abset:Value")
  File "/usr/lib64/python2.6/xml/etree/ElementTree.py", line 330, in find
    return ElementPath.find(self, path)
  File "/usr/lib64/python2.6/xml/etree/ElementPath.py", line 186, in find
    return _compile(path).find(element)
  File "/usr/lib64/python2.6/xml/etree/ElementPath.py", line 176, in _compile
    p = Path(path)
  File "/usr/lib64/python2.6/xml/etree/ElementPath.py", line 93, in __init__
    "expected path separator (%s)" % (op or tag)
SyntaxError: expected path separator (:)

如何在python 2.6.6中访问这些元素?

1 个答案:

答案 0 :(得分:2)

您需要完整指定命名空间,因此应使用root.find("./Set/Key/abset:Data/abset:Tag/abset:Value")而不是root.find("./Set/Key/{titan:arm:params:xml:ns}Data/{titan:arm:params:xml:ns}Tag/{titan:arm:params:xml:ns}Value")