Уведомления

Группа в Telegram: @pythonsu

#1 Фев. 16, 2016 13:22:43

ampermetr
Зарегистрирован: 2016-01-27
Сообщения: 34
Репутация: +  1  -
Профиль   Отправить e-mail  

Обработка xml файла

Есть xml файл с содержимым

<root>
  <child1/>
  <child2/>
  <child3/>
</root>
есть словарь, с ключами child1, child2 и child3
как присвоить элементам child1.text (и остальным) значения из словаря?

Офлайн

#2 Фев. 17, 2016 02:09:07

py.user.next
От:
Зарегистрирован: 2010-04-29
Сообщения: 10016
Репутация: +  857  -
Профиль   Отправить e-mail  

Обработка xml файла

>>> import lxml.html
>>> 
>>> s = """
... <root>
...   <child1/>
...   <child2/>
...   <child3/>
... </root>
... """
>>> 
>>> d = {'child1': 'text1',
...      'child2': 'text2',
...      'child3': 'text3',}
>>> 
>>> doc = lxml.html.fromstring(s)
>>> for node in doc:
...     node.text = d[node.tag]
... 
>>> out = lxml.html.tostring(doc, encoding='unicode')
>>> print(out, end='')
<root>
  <child1>text1</child1>
  <child2>text2</child2>
  <child3>text3</child3>
</root>
>>>



Офлайн

Board footer

Модераторировать

Powered by DjangoBB

Lo-Fi Version