前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python3-将xml文件转成json

python3-将xml文件转成json

作者头像
py3study
发布2020-01-19 15:21:55
1.1K0
发布2020-01-19 15:21:55
举报
文章被收录于专栏:python3python3
代码语言:javascript
复制
from xml.etree import ElementTree as et
import json
def readxml_et():
    tree = et.ElementTree(file="D:\\vscode\\xml2json\\Annotations\\timg.xml")
    root = tree.getroot()
    A = dict()
    listbigoption=[]
    for child_root in root:
        if child_root.tag == 'filename':
            imagePath = child_root.text
        if child_root.tag == 'object':
            listobject=dict()
            for xylabel in child_root:
                if xylabel.tag == 'name':
                    label = xylabel.text                    
                if xylabel.tag == 'polygon':
                    listpoints=[]
                    for pt in xylabel:
                        if pt.tag == 'pt':
                            listxy = []
                            for i in pt:                                
                                if i.tag == 'x':
                                    listxy.append(int(i.text))
                                if i.tag == 'y':
                                    listxy.append(int(i.text))
                                listpoints.append(listxy)
                    listobject['points'] = listpoints
                    listobject['line_color'] = 'null'
                    listobject['label'] = label
                    listobject['fill_color'] = 'null'
                    listbigoption.append(listobject)
                # print(listbigoption)
    A['lineColor'] = [0,255,0,128]
    A['imageData'] = 'imageData'
    A['fillColor'] = [255,0,0,128]
    A['imagePath'] = imagePath
    A['shapes'] = listbigoption
    A['flags'] = {}
    with open('1.json','w') as f:
        json.dump(A,f)

readxml_et()

  同事给了我一个xml文件让我转成他想要的json格式

代码用了好多for和if,用for循环来找子节点,先完成任务,得改进,还不知道怎么改。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-03-14 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档