16

I have an lxml Element object:

>>> from lxml import etree
>>> xml_str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<state type=\"before_battle\">\n</state>"
>>> etree.fromstring(xml_str.encode('utf-8'))
<Element state at 0x7fd04b957e48>

How to get the string dump of Element?

2 Answers 2

21

first store the element object in a variable

>>> d = etree.fromstring(xml_str.encode('utf-8'))

Then use the tostring function from the lxml.etree module:

>>> etree.tostring(d)
'<state type="before_battle">\n</state>'

For additional use cases, you can check out the lxml.etree Tutorial.

Sign up to request clarification or add additional context in comments.

Comments

1

One nuance I noticed, to be able to actually print the dump (with modern Python), one has to specify encoding=str:

print(etree.tostring(node, encoding=str))

Also, with_tail=False might be of use.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.