@Danil38
Python разработчик

Lxm как добраться к элементу документа?

Как добраться до элементов Cube такой xml-ки
<gesmes:Envelope xmlns:gesmes="http://www.gesmes.org/xml/2002-08-01" xmlns="http://www.ecb.int/vocabulary/2002-08-01/eurofxref">
<gesmes:subject>Reference rates</gesmes:subject>
<gesmes:Sender>
<gesmes:name>European Central Bank</gesmes:name>
</gesmes:Sender>
<Cube>
<Cube time="2015-01-06">
<Cube currency="USD" rate="1.1914"/>
<Cube currency="JPY" rate="141.69"/>
<Cube currency="BGN" rate="1.9558"/>
<Cube currency="CZK" rate="27.695"/>
<Cube currency="DKK" rate="7.4414"/>
<Cube currency="GBP" rate="0.78420"/>
<Cube currency="HUF" rate="319.32"/>
<Cube currency="PLN" rate="4.3075"/>
....

когда пытаюсь добраться да нее таким обзом
tree = objectify.fromstring(xml_str)
date = tree.find('gesmes:Envelope/Cube/Cube',
                          namespaces={"gesmes": 'http://www.gesmes.org/xml/2002-08-01'})

мне возвращается None
  • Вопрос задан
  • 2343 просмотра
Решения вопроса 1
winordie
@winordie
Лучшая документация -- исходники
Можно так попробовать:
from xml.dom.minidom import parse
dom = parse("xml.xml")

for node in dom.getElementsByTagName('Cube'):
    if node.getAttribute('time'):
        print('date = {}'.format(node.getAttribute('time')))
        for item in node.getElementsByTagName('Cube'):
            if item.getAttribute('currency'):
                print('currency = {0}, rate = {1}'.format(item.getAttribute('currency'),
                                                          item.getAttribute('rate')))


Вывод:
date = 2015-01-06
currency = USD, rate = 1.1914
currency = JPY, rate = 141.69
currency = BGN, rate = 1.9558
currency = CZK, rate = 27.695
currency = DKK, rate = 7.4414
currency = GBP, rate = 0.78420
currency = HUF, rate = 319.32
currency = PLN, rate = 4.3075
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы