microPython并没有官方的xml解析工具,我在pfalcon/pycopy-lib: Standard library of the Pycopy project, minimalist and light-weight Python language implementation (github.com)里找到了精简的elementTree库(可以解析xml文件或者字符串的节点文本,属性等,但是对比完整的ET库并不能生成xml),下载地址pycopy-lib/xml.etree.ElementTree at master · pfalcon/pycopy-lib (github.com);pycopy-lib/xmltok2 at master · pfalcon/pycopy-lib (github.com)
需要下载两个文件 xmltok2.py,ElementTree.py,
在vscode的扩展里搜索 vscode-m5stack-mpy,安装后就可以简单的添加文件,也可以在vscode里直接让m5s直接执行python文件
点击下边的 Add M5Stack添加设备,加号新建文件,上箭头上传文件到m5s上,把下载下来的两个py文件上传到设备。 执行
import ElementTree as ET
dir(ET)
如果能显示ET库的方法,证明导入库成功
关于ET库的使用方法 (11条消息) Python xml.etree.ElementTree解析XML文件_凯耐的博客-CSDN博客_xml.etree.elementtree
这是我个人写的一个例子
复制代码
from m5stack import *
from m5ui import *
from uiflow import *
import time
setScreenColor(0x222222)
xmlString = None
rootTag = None
rootText = None
root01tag = None
root01text = None
root01attrib = None
label0 = M5TextBox(23, 33, "Text", lcd.FONT_Default, 0xFFFFFF, rotate=0)
title0 = M5Title(title="Title", x=3, fgcolor=0xFFFFFF, bgcolor=0x0000FF)
label1 = M5TextBox(23, 61, "Text", lcd.FONT_Default, 0xFFFFFF, rotate=0)
label2 = M5TextBox(22, 87, "Text", lcd.FONT_Default, 0xFFFFFF, rotate=0)
label3 = M5TextBox(22, 116, "Text", lcd.FONT_Default, 0xFFFFFF, rotate=0)
label4 = M5TextBox(25, 151, "Text", lcd.FONT_Default, 0xFFFFFF, rotate=0)
lcd.clear()
import ElementTree as ET
xmlString = '<?xml version="1.0"?> <data> <country name="Liechtenstein"> <rank>1</rank> <year>2008</year> <gdppc>141100</gdppc> <neighbor name="Austria" direction="E"/> <neighbor name="Switzerland" direction="W"/> </country> <country name="Singapore"> <rank>4</rank> <year>2011</year> <gdppc>59900</gdppc> <neighbor name="Malaysia" direction="N"/> </country> <country name="Panama"> <rank>68</rank> <year>2011</year> <gdppc>13600</gdppc> <neighbor name="Costa Rica" direction="W"/> <neighbor name="Colombia" direction="E"/> </country> </data>'
lcd.clear()
lcd.print(xmlString, 0, 0, 0xffffff)
wait(2)
lcd.clear()
title0.setBgColor(0x000099)
title0.setTitle('parsing...')
root = ET.fromstring(xmlString)
title0.setTitle('parsing complete')
rootTag = 0
rootTag = root.tag
label0.setText(str((str('root.tag:') + str(rootTag))))
rootText = 0
rootText = root.text
label1.setText(str((str('root.text:') + str(rootText))))
root01tag = 0
root01tag = root[0][1].tag
label2.setText(str((str('root[0][1].tag:') + str(root01tag))))
root01text = 0
root01Text = root[0][1].text
label3.setText(str((str('root[0][1].text:') + str(root01text))))
root01attrib = 0
root01attrib = root[0][1].attrib
label4.setText(str((str('root[0][1].attrib:') + str(root01attrib))))
复制代码
实际运行效果 ,可以看出纯py在micropyhhon上运行还是比较慢的
4.69 FhB:/ m5stack添加第三方ET库来解析xml https://v.douyin.com/RRVMGCV/ 覆zhi此链接,打开Douyin搜索,直接观看视频!