使用python写xml

该博客主要介绍了如何将PPOCRLabel的标注格式转换为XML格式,以及在使用minidom写入XML时遇到的顺序问题。作者通过修改minidom源码,避免了属性排序,实现了保留原始顺序的XML写入。代码示例展示了从JSON转换到XML的具体步骤,包括创建DOM树、添加元素节点和设置属性。
摘要由CSDN通过智能技术生成

工作中需要把PPOCRLabel标注格式转化成需要的xml格式。

遇到的问题:1、之前只使用过使用minidom读xml,还没有使用过minidom写xml。2、minidom写xml顺序与写入的顺序不一致问题。

minidom源码在我本地路径:D:\Anaconda3\Lib\xml\dom\minidom.py

参考:Python3.7写入xml文件 保持节点属性顺序不变

首先导入模块 from xml.dom.minidom import Document,然后按下ctrl 使用鼠标点击minidom进入源码

ctrl+F 搜索 a_names = sorted(attrs.keys())。然后注释掉

添加 a_names = attrs.keys()  不使用排序

 

下面是我的PPOCRLabel标注格式转化成需要的xml格式的代码。

# -*- coding : UTF-8 -*-
# @file   : conver_json_icdar.py
# @Time   : 2021/4/9 11:24
# @Author : wmz

import os
import json
import xml.dom.minidom as minidom


def json_2_icdar(js_path, ic_path):
    with open(js_path, 'r', encoding='utf-8') as f:
        for line in f.readlines():
            print(line)
            content = line.split('\t')
            print(content[0])
            txt_file = str(content[0]).replace('jpg', 'txt')
            dst_file = os.path.join(ic_path, txt_file)
            # write file
            file_lineinfo = open(dst_file, 'w', encoding='utf-8')
            list_dict = json.loads(content[1])
            nsize = len(list_dict)
            print(nsize)
            for i in range(nsize):
                print(list_dict[i])
                lin = list_dict[i]
                info = lin['transcription']
                points = lin['points']
                points = [int(y) for x in points for y in x]
                pts = ','.join(map(str, points))
                lineinfo = pts + ',' + info + '\n'
                file_lineinfo.write(lineinfo)
            file_lineinfo.close()


def json_2_xml(js_path, xml_path):
    with open(js_path, 'r', encoding='utf-8') as f:
        for line in f.readlines():
            print(line)
            content = line.split('\t')
            print(content[0])
            xml_file = str(content[0]).replace('jpg', 'xml')
            dst_xml_file = os.path.join(xml_path, xml_file)
            # txt_file = str(content[0]).replace('jpg', 'txt')
            # dst_file = os.path.join(xml_path, txt_file)
            # write file
            # 1.创建DOM树对象
            dom = minidom.Document()
            # 2.创建根节点。每次都要用DOM对象来创建任何节点。
            root_node = dom.createElement('ImageInfo')
            # 3.用DOM对象添加根节点
            dom.appendChild(root_node)
            # 设置该节点的属性
            root_node.setAttribute('bModify', '3')

            # file_lineinfo = open(dst_file, 'w', encoding='utf-8')
            list_dict = json.loads(content[1])
            nsize = len(list_dict)
            print(nsize)
            for i in range(nsize):
                print(list_dict[i])
                lin = list_dict[i]
                info = lin['transcription']
                points = lin['points']
                points = [int(y) for x in points for y in x]
                # 用DOM对象创建元素子节点
                info_node = dom.createElement('LineInfo')
                # 用父节点对象添加元素子节点
                root_node.appendChild(info_node)
                # 设置该节点的属性
                info_node.setAttribute('ptLTX', str(points[0]))
                info_node.setAttribute('ptLTY', str(points[1]))
                info_node.setAttribute('ptRTX', str(points[2]))
                info_node.setAttribute('ptRTY', str(points[3]))
                info_node.setAttribute('ptRBX', str(points[4]))
                info_node.setAttribute('ptRBY', str(points[5]))
                info_node.setAttribute('ptLBX', str(points[6]))
                info_node.setAttribute('ptLBY', str(points[7]))
                info_node.setAttribute('Chars', info)
                info_node.setAttribute('bModify', '3')

                pts = ','.join(map(str, points))
                # lineinfo = pts + ',' + info + '\n'
                # file_lineinfo.write(lineinfo)
            # file_lineinfo.close()
            with open(dst_xml_file, 'w', encoding='UTF-8') as fh:
                dom.writexml(fh, indent='', addindent='\t', newl='\n', encoding='UTF-8')


if __name__ == "__main__":
    # src_path = r"C:\Users\WT\Desktop\hkb-bz\Label.txt"
    src_path = r"C:\Users\WT\Desktop\hkb\Cache.cach"
    dst_path = r"C:\Users\WT\Desktop"
    # src_path = r"C:\Users\WT\Desktop\户口本\Cache.cach"
    # dst_path = r"C:\Users\WT\Desktop"
    json_2_xml(src_path, dst_path)

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
### 回答1: PythonXML文件的常用模块有xml.etree.ElementTree和xml.dom.minidom。 1. 使用xml.etree.ElementTree模块读取XML文件: 首先需要导入xml.etree.ElementTree模块,然后使用ElementTree.parse()方法解析XML文件,返回一个ElementTree对象。接着可以使用该对象的getroot()方法获取XML文件的根元素。可以通过遍历根元素及其子元素的方式来获取XML文件中的数据。 示例代码如下: ```python import xml.etree.ElementTree as ET # 读取XML文件 tree = ET.parse('example.xml') # 获取根元素 root = tree.getroot() # 遍历根元素及其子元素 for child in root: print(child.tag, child.attrib) ``` 2. 使用xml.etree.ElementTree模块XML文件: 要XML文件,可以创建ElementTree对象,然后使用ElementTree.Element()方法创建根元素。通过调用根元素的Element()方法来创建子元素,以及调用子元素的text属性来设置元素的文本内容。最后使用ElementTree.ElementTree()方法将ElementTree对象XML文件。 示例代码如下: ```python import xml.etree.ElementTree as ET # 创建根元素 root = ET.Element('root') # 创建子元素 child1 = ET.Element('child1') child1.text = 'Content of child1' root.append(child1) # 创建ElementTree对象 tree = ET.ElementTree(root) # XML文件 tree.write('example.xml') ``` 以上就是PythonXML文件的简单示例。xml.dom.minidom模块与xml.etree.ElementTree模块类似,提供了操作XML文件的方法,但使用方式略有不同。 ### 回答2: 在Python中,我们可以使用`xml`模块来读XML文件。 要读取XML文件,我们可以使用`xml.etree.ElementTree`模块的`parse`函数。具体步骤如下: 1. 导入`xml.etree.ElementTree`模块。 2. 使用`parse`函数打开XML文件,并返回一个`ElementTree`对象。 3. 使用`getroot`方法获取XML文件的根元素。 4. 使用`find`、`findall`等方法定位到需要读取的元素,然后使用`text`属性获取其文本内容。 以下是一个读取XML文件的示例代码: ```python import xml.etree.ElementTree as ET # 打开XML文件并解析 tree = ET.parse('example.xml') # 获取根元素 root = tree.getroot() # 定位到需要读取的元素,获取其文本内容 for child in root.findall('book'): title = child.find('title').text author = child.find('author').text year = child.find('year').text print(f'Title: {title}, Author: {author}, Year: {year}') ``` 要XML文件,我们可以使用`xml.etree.ElementTree`模块的相关方法来创建XML元素,并使用`ElementTree`对象的`write`函数将元素XML文件。 以下是一个XML文件的示例代码: ```python import xml.etree.ElementTree as ET # 创建根元素 root = ET.Element('books') # 创建子元素 book1 = ET.SubElement(root, 'book') title1 = ET.SubElement(book1, 'title') title1.text = 'Book Title 1' author1 = ET.SubElement(book1, 'author') author1.text = 'Author 1' year1 = ET.SubElement(book1, 'year') year1.text = '2021' book2 = ET.SubElement(root, 'book') title2 = ET.SubElement(book2, 'title') title2.text = 'Book Title 2' author2 = ET.SubElement(book2, 'author') author2.text = 'Author 2' year2 = ET.SubElement(book2, 'year') year2.text = '2022' # 创建ElementTree对象 tree = ET.ElementTree(root) # XML文件 tree.write('example.xml', encoding='utf-8', xml_declaration=True) ``` 以上是使用PythonXML文件的基本操作,根据具体需求,我们可以进一步学习和使用XML相关的操作方法。 ### 回答3: PythonXML文件可以使用内置的xml模块。首先,我们需要导入xml.etree.ElementTree模块来处理XML数据。 要读取XML文件,我们可以使用ElementTree的parse函数。例如,如果我们有一个名为"example.xml"的XML文件,我们可以这样读取它: ```python import xml.etree.ElementTree as ET tree = ET.parse("example.xml") root = tree.getroot() ``` 这将解析XML文件并将其存储在ElementTree对象中。我们可以使用getroot()方法获取XML的根元素。 要访问XML元素的内容,可以使用标签名称和迭代器的方式。例如,要打印出XML文件中所有元素的标签和文本内容,可以使用以下代码: ```python for element in root.iter(): print(element.tag, element.text) ``` 要XML文件,我们可以创建一个新的ElementTree对象,并添加元素和属性。然后,我们可以使用ElementTree的write函数将其入文件。 以下是一个将数据XML文件的示例代码: ```python import xml.etree.ElementTree as ET root = ET.Element("root") child1 = ET.SubElement(root, "child1") child1.text = "这是child1的文本内容" child2 = ET.SubElement(root, "child2") child2.text = "这是child2的文本内容" tree = ET.ElementTree(root) tree.write("output.xml") ``` 这将创建一个名为"output.xml"的新XML文件,并在其中入我们创建的XML结构。 综上所述,我们可以使用xml.etree.ElementTree模块读XML文件。读取时使用parse函数解析XML文件并获取根元素,入时创建ElementTree对象,添加元素和属性,并利用write函数将其入文件。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

落花逐流水

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

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

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

打赏作者

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

抵扣说明:

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

余额充值