Python Forum
Python - joining xmls together invalid token error - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Python - joining xmls together invalid token error (/thread-17856.html)



Python - joining xmls together invalid token error - jan86 - Apr-26-2019

I have a function which makes get request, parse xml file and returns:

def get_object(object_name):
...
    encoded_text = response.text.encode('utf-8', 'replace')
    root = ET.fromstring(encoded_text)
    tree = ET.ElementTree(root)
    return tree
Then I loop through tasks with this function and want to put it inside one variable:

jx_task_tree = ''
for jx in jx_tasks_lst:
    jx_task_tree += str(get_object(jx))
    jx_task_tree += ('\n')
Then I want to parse jx_task_tree:

root = ET.fromstring(jx_task_tree).encode('utf-8')
tree_out = ET.tostring(root)
print(tree_out)
But it throws me an error:

File "import_uac_wf.py", line 51, in <module>
   root = ET.fromstring(jx_task_tree).encode('utf-8')
File "/usr/lib64/python2.7/xml/etree/ElementTree.py", line 1300, in XML
   parser.feed(text)
File "/usr/lib64/python2.7/xml/etree/ElementTree.py", line 1642, in feed
   self._raiseerror(v)
File "/usr/lib64/python2.7/xml/etree/ElementTree.py", line 1506, in 
   _raiseerror
raise err
xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 1, 
column 42
When using this:

parser = ET.XMLParser(encoding="utf-8")
tree = ET.parse(jx_tasks_lst, parser=parser)
print(ET.tostring(tree.getroot()))
There is error:

Traceback (most recent call last):
  File "import_uac_wf.py", line 57, in <module>
    tree = ET.parse(jx_tasks_lst, parser=parser)
  File "/usr/lib64/python2.7/xml/etree/ElementTree.py", line 1182, in parse
    tree.parse(source, parser)
 File "/usr/lib64/python2.7/xml/etree/ElementTree.py", line 647, in parse
    source = open(source, "rb")
TypeError: coercing to Unicode: need string or buffer, list found
Can anybody help what am I doing wrong or how to fix it?