Why is etree.tostring() not working for different methods?

1k views Asked by At

I'm learning XML and am trying the following exercise code:

root = etree.XML('<html><head/><body><p>Hello<br/>World</p></body></html>')
etree.tostring(root, method='xml')
print(etree.tostring(root))
etree.tostring(root, method='html') 
print(etree.tostring(root))
etree.tostring(root, method='text') 
print(etree.tostring(root))

In the exercise, it says if I do this, I should be getting 3 differently formatted output strings for root: xml, html and text. However, I'm just getting 3 XML-formatted outputs.

What am I missing here? Was I supposed to import something? My suspicion is that something is amiss with the etree.XML assignment part, but as I say: I'm just following directions here. What do people think is amiss?

1

There are 1 answers

1
kjhughes On BEST ANSWER

The results of the tostring() calls are indeed different but are lost each time, and you're instead printing the same expression three times. (Be aware that tostring() is returning a result, not modifying its arguments in place.)

If you instead run this script:

from lxml import etree

root = etree.XML('<html><head/><body><p>Hello<br/>World</p></body></html>')
print(etree.tostring(root, method='xml'))
print(etree.tostring(root, method='html'))
print(etree.tostring(root, method='text'))

You'll get the output you expect:

<html><head/><body><p>Hello<br/>World</p></body></html>
<html><head></head><body><p>Hello<br>World</p></body></html>
HelloWorld