通过python生成xml

先上代码,代码运行需要一定的环境,请自行适配:

#xmlTest_write.py
# -*- coding: utf-8 -*-
import sys
import os
import subprocess
import zlib
import xml.dom.minidom



def pre_ota_img(otaDirPath):
    #记录镜像与分区之间的关系 键-镜像   值-分区
    global soc_img_partiton
    global mcu_img_partiton
    global camera_img_partiton
    soc_img_partiton={"uboot.img":"uboot", "boot.img":"boot", "system.img":"system", "vbmeta.img":"vbmeta"}
    mcu_img_partiton={}
    camera_img_partiton={}

    #先确定soc的部署是否配置
    flag="exist"
    os.environ.get('TARGET_DEPLOY_DIR')
    try:
        print("TARGET_DEPLOY_DIR", os.environ['TARGET_DEPLOY_DIR'])
    except KeyError:
        print("TARGET_DEPLOY_DIR does not exist")
        flag=""
    #确定soc有部署
    if flag:
        #获取SOC部署路径
        soc_dir_path=os.environ['TARGET_DEPLOY_DIR']
        #如果SOC有部署路径
        if soc_dir_path:
            print(soc_dir_path)
            #将SOC部署路径下的目标镜像拷贝到ota目录
            for img in soc_img_partiton:
                subprocess.call("cp " + soc_dir_path+"/"+img + " " + otaDirPath+"/soc/"+img, shell=True)
        else:
            print("TARGET_DEPLOY_DIR is NULL")

    flag="exist"
    os.environ.get('MCU_PATH')
    try:
        print("MCU_PATH", os.environ['MCU_PATH'])
    except KeyError:
        print("MCU_PATH does not exist")
        flag=""
    if flag:
        mcu_dir_path=os.environ['MCU_PATH']
        if mcu_dir_path:
            print(mcu_dir_path)
            for img in mcu_img_partiton:
                subprocess.call("cp " + mcu_dir_path+"/"+img + " " +  otaDirPath+"/mcu/"+img, shell=True)
        else:
            print("MCU_PATH is NULL")

    flag="exist"
    os.environ.get('CAMERA_PATH')
    try:
        print("CAMERA_PATH", os.environ['CAMERA_PATH'])
    except KeyError:
        print("CAMERA_PATH does not exist")
        flag=""
    if flag:
        camera_dir_path=os.environ['CAMERA_PATH']
        if camera_dir_path:
            print(camera_dir_path)
            for img in camera_img_partiton:
                subprocess.call("cp " + camera_dir_path+"/"+img + " " +  otaDirPath+"/camera/"+img, shell=True)
        else:
            print("CAMERA_PATH is NULL")


def addFileInfo(dom, node, crc32, fileNmae, sha256sum, mode):
    fileinfo=dom.createElement('fileinfo')
    fileinfo.setAttribute("filename", fileNmae)
    fileinfo.setAttribute("crc32", crc32)
    fileinfo.setAttribute("sha256", sha256sum)
    if mode == "soc":
        for img in soc_img_partiton:
            if img == fileNmae:
                fileinfo.setAttribute("partition", soc_img_partiton[img])
    if mode == "mcu":
        for img in soc_img_partiton:
            if img == fileNmae:
                fileinfo.setAttribute("partition", soc_img_partiton[img])
    if mode == "camera":
        for img in soc_img_partiton:
            if img == fileNmae:
                fileinfo.setAttribute("partition", soc_img_partiton[img])
    node.appendChild(fileinfo)


def addVersionInfo(dom, node, name, version):
    versioninfo=dom.createElement('version')
    versioninfo.setAttribute("name", name)
    versioninfo.setAttribute("version", version)
    node.appendChild(versioninfo)

def cal_crc(fileName):
    prev = 0
    for eachLine in open(fileName,"rb"):
        prev = zlib.crc32(eachLine, prev)
    return "%X"%(prev & 0xFFFFFFFF)

#生成xml文件
def GenerateXml(otaDirPath):
    print(otaDirPath)
    impl = xml.dom.minidom.getDOMImplementation()
    #设置根结点update
    dom = impl.createDocument(None, 'update', None)
    update = dom.documentElement

    #在update下创建project子节点
    project = dom.createElement('project')
    update.appendChild(project)
    project_list = dom.createElement('project')
    project.appendChild(project_list)
    project_list.setAttribute("name", "j3")

    #在update下创建version_list子节点
    version_list = dom.createElement('version_list')
    update.appendChild(version_list)

    #判断是否有soc相关镜像
    if os.listdir(otaDirPath+"/soc"):
        #这里的版本信息还需要优化。目前还不确定怎么获取版本信息
        addVersionInfo(dom, version_list, "bsp", "v1.0.0")
        addVersionInfo(dom, version_list, "zros", "v1.0.0")
        #在update下创建soc子节点
        soc = dom.createElement('soc')
        update.appendChild(soc)

        soc_install=dom.createElement('install')
        soc_install.setAttribute("type", "full")
        soc.appendChild(soc_install)

        soc_file_list=dom.createElement('FILE_LIST')
        soc.appendChild(soc_file_list)

        for img in os.listdir(otaDirPath+"/soc"):
            crc32Value=cal_crc(otaDirPath+"/soc/"+img)
            sha256sum=os.popen("sha256sum " + otaDirPath+"/soc/"+img + " | awk \'{print $1}\'")
            addFileInfo(dom, soc_file_list, str(crc32Value), img, sha256sum.read(), "soc")

    #判断是否有mcu相关镜像
    if os.listdir(otaDirPath+"/mcu"):
        #这里的版本信息还需要优化。目前还不确定怎么获取版本信息
        addVersionInfo(dom, version_list, "mcu", "v1.0.0")
        #在update下创建mcu子节点
        mcu = dom.createElement('mcu')
        update.appendChild(mcu)

        mcu_install=dom.createElement('install')
        mcu_install.setAttribute("type", "full")
        mcu.appendChild(mcu_install)

        mcu_file_list=dom.createElement('FILE_LIST')
        mcu.appendChild(mcu_file_list)

        for img in os.listdir(otaDirPath+"/mcu"):
            crc32Value=cal_crc(otaDirPath+"/mcu/"+img)
            sha256sum=os.popen("sha256sum " + otaDirPath+"/mcu/"+img + " | awk \'{print $1}\'")
            print(img + " sha256sum:"+ sha256sum)
            addFileInfo(dom, mcu_file_list, str(crc32Value), img, sha256sum.read(), "mcu")

    #判断是否有camera相关镜像
    if os.listdir(otaDirPath+"/camera"):
        #这里的版本信息还需要优化。目前还不确定怎么获取版本信息
        addVersionInfo(dom, version_list, "camera", "v1.0.0")
        #在update下创建camera子节点
        camera = dom.createElement('camera')
        update.appendChild(camera)

        camera_install=dom.createElement('install')
        camera_install.setAttribute("type", "full")
        camera.appendChild(camera_install)

        camera_file_list=dom.createElement('FILE_LIST')
        camera.appendChild(camera_file_list)

        for img in os.listdir(otaDirPath+"/camera"):
            crc32Value=cal_crc(otaDirPath+"/camera/"+img)
            sha256sum=os.popen("sha256sum " + otaDirPath+"/camera/"+img + " | awk \'{print $1}\'")
            print(img + " sha256sum:"+ sha256sum)
            addFileInfo(dom, camera_file_list, str(crc32Value), img, sha256sum.read(), "camera")


    f= open(otaDirPath + "/ota_config.xml", 'w') #w替换为a,追加
    dom.writexml(f, addindent=' ', newl='\n')
    f.close()
    print("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")




def main(argv):
    print("start pre_ota_img:")
    pre_ota_img(otaDirPath=argv)
    print("start GenerateXml:")
    GenerateXml(otaDirPath=argv)

if __name__ == '__main__':
        main(sys.argv[1])

在python里面调用Linux命令并获取其输出:

sha256sum=os.popen("sha256sum " + otaDirPath+"/camera/"+img + " | awk \'{print $1}\'")

在python里面遍历某个目录:

for img in os.listdir(otaDirPath+"/soc"):
            crc32Value=cal_crc(otaDirPath+"/soc/"+img)
            sha256sum=os.popen("sha256sum " + otaDirPath+"/soc/"+img + " | awk \'{print $1}\'")
            addFileInfo(dom, soc_file_list, str(crc32Value), img, sha256sum.read(), "soc")

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要使用Python生成XML文件,可以使用xml.dom.minidom模块或xml.etree.ElementTree模块。 在xml.dom.minidom模块中,可以使用Document类来创建XML文档对象,然后使用createElement()、appendChild()和createTextNode()等方法来创建元素和文本节点,并将它们添加到文档中。最后,可以使用toprettyxml()方法将文档格式化为字符串或将其写入文件。以下是一个使用xml.dom.minidom模块创建XML文件的示例代码: ```python from xml.dom.minidom import Document doc = Document() root = doc.createElement("root") doc.appendChild(root) element = doc.createElement("element") text = doc.createTextNode("This is a test!") element.appendChild(text) root.appendChild(element) xml_str = doc.toprettyxml(indent=" ") with open("output.xml", "w") as f: f.write(xml_str) ``` 在xml.etree.ElementTree模块中,可以使用ElementTree类来创建XML文档对象,然后使用Element()和SubElement()等方法来创建元素,并使用text属性设置元素的文本内容。最后,可以使用ElementTree的write()方法将文档写入文件。以下是一个使用xml.etree.ElementTree模块创建XML文件的示例代码: ```python import xml.etree.ElementTree as ET root = ET.Element("root") element = ET.SubElement(root, "element") element.text = "This is a test!" tree = ET.ElementTree(root) tree.write("output.xml") ``` 以上是两种常用的方法来生成XML文件的示例代码。你可以根据自己的需求选择其中一种方法来使用。 #### 引用[.reference_title] - *1* [怎么用python创建文件-如何用Python创建生成xml文档文件的方法](https://blog.csdn.net/weixin_37988176/article/details/109417617)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [Python学习(十四):Python如何创建一个xml文件](https://blog.csdn.net/weixin_43580890/article/details/129343510)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

monkey_lqd

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值