我有一个眼动仪,它使用 TCP/IP 通信和 XML 在客户端(应用程序)和服务器(眼动仪)之间发送数据。以下是我在眼动仪开启时连续收到的 XML 数据字符串示例。我想做的是能够使用数据 FPOGX 和 FPOGY 作为我拥有的另一个函数的输入。问题是它们不是变量,你不能简单地调用它们。我如何解析这个数据流?这是我第一次使用 XML。示例将不胜感激。谢谢!
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"/>
以下是部分代码的片段:
import xml.etree.cElementTree as ET
import cv2
import cv
import socket
# Code to grab different data from eye-tracker
'...'
# Code to create window and initialize camera
'...'
def xmlParse():
rxdat = s.recv(1024) # Syntax from eye-tracker to grab XML data stream of <REC />
if(rxdat.find("ACK") == 1): # First two XML have the <ACK /> tag but I don't need those
pass
else: # Here is the part where it parses and converts the data to float
rxdat = '<data>' + rxdat + '</data>'
xml = ET.fromstring(rxdat)
for element in xml:
X = float(xml[0].attrib['FPOGX'])
Y = float(xml[0].attrib['FPOGY'])
return (X, Y)
# Def to average samples of incoming X and Y
'...'
# Def that uses xmlParse() and average() to return the averages of X and Y
'...'
# Def for mouse click events
'...'
# Some code that makes our window graphics
'...'
for i in range(0,2): # Round-about way to get rid of the first two "NoneType"
xmlParse()
while True:
Img = cv.QueryFrame(capture) # capture defined earlier
drawarrow(polyF, polyB, polyL, polyR) # Our window graphics definition
cv.ShowImage("window", Img)
(X, Y) = gazeCoordinates() # Def that uses xmlParse and average to return the averages of X and Y
if cv.WaitKey(20) & 0xFF == 27:
break
cv2.destroyAllWindows()
给出的错误是ParseError: not well-formed (invalid token)
并指向xml = ET.fromstring(rxdat)
代码的
定义 xmlParse() 本身并仅打印出结果即可。但是,一旦我开始添加窗口、图形并使用数据,它就会开始发出该错误。