user1234440
user1234440

Reputation: 23587

Getting Actual String from Python XML parsing

I have a string that when parsed with tostring gives me a bunch of xml. Is there a way to get that fixed?

For example, when i run ET.tostring(elementObject,,encoding='us-ascii', method='xml'), i get <string>11&gt;2</string>. I am expecting: "11>2". Is there a way to get what I am expecting or do I need to do some regex on that return value?

I am using import xml.etree.ElementTree as ET

thanks

Upvotes: 0

Views: 40

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123620

ET.tostring() is meant to produce a XML string for a given element, not the contained string value. Use the Element.text attribute instead:

elementObject.text

Demo:

>>> from xml.etree import ElementTree as ET
>>> root = ET.fromstring('''\
... <root><string>11&gt;2</string></root>''')
>>> root.find('string')
<Element 'string' at 0x103332990>
>>> root.find('string').text
'11>2'

Upvotes: 2

Related Questions