0
votes

I receive the following xml message (data_back in the code below) from host which I need to parse to fetch VersionRequest.

b'\x02
<H_VersionRequest>
<ClientId>Machine - 123</ClientId>
<VersionRequest>1.2.3</VersionRequest>
<H_VersionRequest>
\x03'

I wrote the following code;

import xml.etree.ElementTree as ET
# data received from host is saved to data_back
xml = str(data_back)
tree = ET.fromstring(xml)
root = tree.getroot()
print(root)

I get the following error;

Traceback (most recent call last): File "C:/Users/llovely/PycharmProjects/Test/Libraries/test4 msg inc.py", line 10, in tree = ET.fromstring(xml) File "C:\Users\llovely\AppData\Local\Programs\Python\Python38-32\lib\xml\etree\ElementTree.py", line 1320, in XML parser.feed(text) xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 1, column 1

Can someone suggest me how to extract the data from this format of xml?

1
@snakecharmerb It worked, I didnt know about the decoding. Thank you very much - LLovely

1 Answers

1
votes

If you are certain that there are only one byte outside the XML and each end, then just take the rest of the string as a slice:

import xml.etree.ElementTree as ET
# Decode from bytes to str, don;t call str on bytes
xml = data_back.decode()[1:-1]
tree = ET.fromstring(xml)
root = tree.getroot()
print(root)

Note that the xml in the question is not well-formed, but I assume that's a typo.