2012-11-10

Python: ElementTree to String

Виявив проблему при роботі із ElementTree.
I've met the problem with ElementTree usage.

import import xml.etree.cElementTree as etree
tree = etree.parse('example.xml')
spam = etree.tostring(tree)

Фрагмент коду, наведений вище, завжди буде давати помилку:
The code above will always give an error
"AttributeError: 'ElementTree' object has no attribute 'tag'"
Щоб уникнути цього, потрібно спочатку знайти кореневий тег і саме його конвертувати в string, а не цілий ElementTree
To fix this you should convert to string root, not ElementTree instance:

import import xml.etree.cElementTree as etree
tree = etree.parse('example.xml')
root = tree.getroot()
spam = etree.tostring(root)


4 comments:

  1. Hi I had the same problem and came across your blog via Google. Thanks for putting this, it helped me.

    ReplyDelete
  2. This was very helpful! Thanks so much!

    ReplyDelete
  3. Sweet, just what I was looking for! Thank brotendo

    ReplyDelete