You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何序列化整数?Python程序中无法实现整数序列化求解决方法

Python整数序列化到XML的问题修复

错误原因

  • XML元素的text属性仅支持接收字符串类型的内容,你当前代码中直接将整数类型的超时数值1,以及pyserial库返回的整数类型串口常量赋值给text属性,触发类型校验错误,导致序列化失败。
  • 代码中存在冗余导入的Serialcomm模块,未实际使用,运行时可能触发无关警告。

修复后代码

import serial
import xml.etree.ElementTree as xml

def GenerateXML(serialcomm):
    root = xml.Element("SerialParameter")
    
    child1 = xml.Element("Portname")
    child1.text = "COM5"
    root.append(child1)
    
    child2 = xml.Element("Baudrate")
    child2.text = "9600"
    root.append(child2)
    
    child3 = xml.Element("serial.Parity")
    # 非字符串值转字符串再赋值给text
    child3.text = str(serial.PARITY_NONE)
    root.append(child3)
    
    child4 = xml.Element("Stopbits")
    child4.text = str(serial.STOPBITS_ONE)
    root.append(child4)
    
    child5 = xml.Element("Bytesize")
    child5.text = str(serial.EIGHTBITS)
    root.append(child5)
    
    child6 = xml.Element("Timeout")
    # 整数1转字符串
    child6.text = str(1)
    root.append(child6)
    
    tree = xml.ElementTree(root)
    with open(serialcomm, "wb") as files:
        tree.write(files)

if __name__ == "__main__":
    GenerateXML("SerialSettings.xml")

补充说明

如果后续需要从生成的XML中读取数值转回整数,读取text属性后用int()方法转换即可。

内容的提问来源于stack exchange,提问作者Abhijeet singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 15:15:03