Найти - Пользователи
Полная версия: Обработка xml файла
Начало » Python для новичков » Обработка xml файла
1
ampermetr
Есть xml файл с содержимым
<root>
  <child1/>
  <child2/>
  <child3/>
</root>
есть словарь, с ключами child1, child2 и child3
как присвоить элементам child1.text (и остальным) значения из словаря?
py.user.next
>>> 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>
>>>
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB