繁体   English   中英

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

[英]getting at namespace data when Parsing Xml on Python 2.6.6 with ElementTree 1.2.6

我有一些需要解析的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:Value:

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中访问这些元素?

您将需要完整指定名称空间,因此应该使用root.find("./Set/Key/{titan:arm:params:xml:ns}Data/{titan:arm:params:xml:ns}Tag/{titan:arm:params:xml:ns}Value")来代替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")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM