Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have an eye-tracker uses TCP/IP communication and XML to send data between client (application) and server (eye-tracker). The following is an example of the XML data string I receive continuously while the eye-tracker is on. What I would like to do is be able to use the data, FPOGX and FPOGY, as an input to another function I have. The problem is they are not variables and you can't just simply call upon them. How do I parse this data stream? This is the first time I've worked with XML. Examples would be greatly appreciated. Thanks!

CLIENT SEND: <SET ID="ENABLE_SEND_COUNTER" STATE="1" />
SERVER SEND: <ACK ID="ENABLE_SEND_COUNTER" STATE="1" />
CLIENT SEND: <SET ID="ENABLE_SEND_POG_FIX" STATE="1" />
SERVER SEND: <ACK ID="ENABLE_SEND_POG_FIX" STATE="1" />
CLIENT SEND: <SET ID="ENABLE_SEND_DATA" STATE="1" />
SERVER SEND: <ACK ID="ENABLE_SEND_DATA" STATE="1" />
SERVER SEND: <REC CNT="72" FPOGX="0.5065" FPOGY="0.4390"
FPOGD="0.078" FPOGID="468" FPOGV="1"/>
SERVER SEND: <REC CNT="73" FPOGX="0.5071" FPOGY="0.4409"
FPOGD="0.094" FPOGID="468" FPOGV="1"/>
SERVER SEND: <REC CNT="74" FPOGX="0.5077" FPOGY="0.4428"
FPOGD="0.109" FPOGID="468" FPOGV="1"/>
share|improve this question
add comment

1 Answer

Assuming you don't need to parse all of the text above (which is not properly xml when taken all together) but rather just a single xml element at a time, I would suggest trying something like the following. You will end up with a dictionary of attributes, which contain the key/value pairs you are after.

>>> import xml.etree.cElementTree as ET
>>> xml_string = '<REC CNT="72" FPOGX="0.5065" FPOGY="0.4390" FPOGD="0.078" FPOGID="468" FPOGV="1"/>'
>>> xml = ET.fromstring(xml_string)
>>> xml.attrib  # a dict
{'CNT': '72', 'FPOGV': '1', 'FPOGY': '0.4390', 'FPOGX': '0.5065', 'FPOGD': '0.078', 'FPOGID': '468'}
>>> xml.attrib['FPOGX'], xml.attrib['FPOGY']
('0.5065', '0.4390')

You can check out the documentation for xml.etree.ElementTree here.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.