python3-将xml文件转成json

发布时间:2019-03-14 23:42:24编辑:auto阅读(1990)

    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循环来找子节点,先完成任务,得改进,还不知道怎么改。

关键字