python 读写.xml文件

python 读写.xml文件,第1张

文章目录
  • 1 XML文件读取
    • 1 获得 .xml文件根节点
    • 2 获得节点的属性
    • 3 获得节点的子节点
    • 4 Supported XPath syntax
  • 2 写XML文件

1 XML文件读取

测试文件 test.xml 内容如下:



<root>
    <time>
        <years>2022years>
        <month>04month>
        <day>24day>
    time>
    <PORT_LIST>
		<COM Name="COM3" Remarks="" Baund="9600" Parity="0" StopBit="0" DataBit="0" FlowCtrl="0" TransMode="0" CharType="0" BreakTime="10" />
		<COM Name="COM4" Remarks="" Baund="9600" Parity="0" StopBit="0" DataBit="0" FlowCtrl="0" TransMode="0" CharType="0" BreakTime="10" />
		<NET Name="NET000" Remarks="" DesIP="127.0.0.1" LocalPortID="54125" DesPortID="502" />
		<NET Name="NET001" Remarks="" DesIP="127.0.0.1" LocalPortID="502" DesPortID="502" />
	PORT_LIST>
root>
1 获得 .xml文件根节点
#!/usr/bin/python
# -*- coding: GBK -*-
import xml.etree.ElementTree as ET
import xml.dom.minidom as minidom

tree = ET.parse('test.xml')
root = tree.getroot()  #获得根节点
2 获得节点的属性
# 
# 获得节点
month = node.attrib['name']
addr  = node.attrib['addr']
3 获得节点的子节点 4 Supported XPath syntax

  • 1 路径查找:
#查找到root子节点 time
nodetime = root.find('time')
print(nodetime.text )
#查找到root子节点 time的子节点years
node_years = root.find('time/years')
print(node_years.text )
  • 2 查找含有某一属性的节点
# 查找到 属性="COM3"的所有节点
nodecom3 = root.findall(".//*[@Name='COM3']")
print(nodecom3, type(nodecom3)) #nodecom3 list
print(nodecom3[0].attrib['Baund'])
  • 3 查找属性等于某一值得节点
在这里插入代码片
2 写XML文件
#!/usr/bin/python
# -*- coding: UTF-8 -*-

import xml.etree.ElementTree as ET
import xml.dom.minidom as minidom


#tree = ET.parse('01.xml')
'''
中文这个是转换前的,现在是打算把
r
bin
格式的转换到yx组
其他r
转换到yc组
'''

class  XmlConvert(object):
    def __init__(self, xmlfile):
        self.tree = ET.parse(xmlfile)
        self.root = self.tree.getroot()
        self.node_param_list = []
        for node in list(self.root):
            if node.tag == 'params':
                for node_param in node:
                    self.node_param_list.append(node_param)  #node param  -> 
        #  遥信信息
        self.match_nodes = self.get_yx_info()
        print(self.match_nodes)

        for node in self.match_nodes:
            print(node.findtext('name'), node.attrib['groupid'], node.attrib['addr'] )
        #写 .xml
        #dom= minidom.Document()
        self.new_xml("新文件.xml")

    def new_xml(self,xmlfile):
        dom = minidom.getDOMImplementation().createDocument(None, 'Root', None)
        root = dom.documentElement
        for i in range(5):
            element = dom.createElement('Name')
            element.appendChild(dom.createTextNode('default'))
            element.setAttribute('age', str(i))
            root.appendChild(element)
        # 保存文件
        with open(xmlfile, 'w', encoding='utf-8') as f:
            dom.writexml(f, addindent='\t', newl='\n', encoding='utf-8')


    def get_yx_info(self):
        self.match_nodes = []
        for node_param in self.node_param_list:
            #判断子节点  rw bin
            flag = 0
            #if node_param.findtext("type") == 'rw' or node_param.findtext("format") == 'bin':
            if node_param.findtext("type") == 'rw':
                flag += 1
            if node_param.findtext("format") == 'bin':
                flag += 1
            if 2 == flag: self.match_nodes.append(node_param)
        return  self.match_nodes


if __name__ == '__main__':
    # tree = ET.parse('PCS调试串口通信点表.xml')
    XmlConvert('PCS调试串口通信点表.xml')
    pass
#!/usr/bin/python
# -*- coding: UTF-8 -*-

import xml.etree.ElementTree as ET
import xml.dom.minidom as minidom


#tree = ET.parse('01.xml')
'''
中文这个是转换前的,现在是打算把
r
bin
格式的转换到yx组
其他r
转换到yc组
'''

class Xmlwrite(object):
    def __init__(self, xml):
        self.xml_name = xml
        self.dom = minidom.getDOMImplementation().createDocument(None, 'dmp', None)
        #设置root节点属性
        root_attrib = {'station': 'PCS塔机测试','name': 'PCS_TOWER', 'kind':'PCS_TOWER' }
        #self.set_node_attrib(self.xmlroot, root_attrib )
        self.xmlroot = self.dom.documentElement
        for i in range(5):
            # element = self.dom.createElement('Name')
            # element.appendChild(self.dom.createTextNode('default'))
            # element.setAttribute('age', str(i))
            # #element.setAttribute("station", "PCS塔机测试")
            # self.set_node_attrib(element , root_attrib )
            node = self.new_node('tag_name', "goodjob", None )
            self.set_node_attrib(node, root_attrib )
            #self.xmlroot.appendChild(element)

    
    #设置node属性
    def set_node_attrib(self, node , nodeinfo ):
        for key,value in  nodeinfo.items():
            node.setAttribute(key,value)

    #新建node
    def new_node(self, tag_name , text , parent_node=None ):
        node = self.dom.createElement(tag_name)
        node.appendChild(self.dom.createTextNode(text))
        if parent_node:
            parent_node.appendChild(node)
        else:
            self.xmlroot.appendChild(node)
        return node
    #保存文件
    def save_xml(self, name=None):
        if name:
        # 保存文件
            with open( name, 'w', encoding='utf-8') as f:
                self.dom.writexml(f, addindent='\t', newl='\n', encoding='utf-8')
        else:
            with open( self.xml_name, 'w', encoding='utf-8') as f:
                self.dom.writexml(f, addindent='\t', newl='\n', encoding='utf-8')






class  XmlConvert(object):
    def __init__(self, xmlfile):
        self.tree = ET.parse(xmlfile)
        self.root = self.tree.getroot()
        self.node_param_list = []
        for node in list(self.root):
            if node.tag == 'params':
                for node_param in node:
                    self.node_param_list.append(node_param)  #node param  -> 
        #  遥信信息
        self.match_nodes = self.get_yx_info()
        print(self.match_nodes)

        for node in self.match_nodes:
            print(node.findtext('name'), node.attrib['groupid'], node.attrib['addr'] )
        #写 .xml
        #dom= minidom.Document()
        #self.new_xml("新文件.xml")

    def new_xml(self,xmlfile):
        dom = minidom.getDOMImplementation().createDocument(None, 'Root', None)
        root = dom.documentElement
        for i in range(5):
            element = dom.createElement('Name')
            element.appendChild(dom.createTextNode('default'))
            element.setAttribute('age', str(i))
            root.appendChild(element)
        # 保存文件
        with open(xmlfile, 'w', encoding='utf-8') as f:
            dom.writexml(f, addindent='\t', newl='\n', encoding='utf-8')


    def get_yx_info(self):
        self.match_nodes = []
        for node_param in self.node_param_list:
            #判断子节点  rw bin
            flag = 0
            #if node_param.findtext("type") == 'rw' or node_param.findtext("format") == 'bin':
            if node_param.findtext("type") == 'rw':
                flag += 1
            if node_param.findtext("format") == 'bin':
                flag += 1
            if 2 == flag: self.match_nodes.append(node_param)
        return  self.match_nodes


if __name__ == '__main__':
    # tree = ET.parse('PCS调试串口通信点表.xml')
    #XmlConvert('PCS调试串口通信点表.xml')
    newxml =  Xmlwrite("convert.xml")
    newxml.save_xml("转化后文件.xml")
    pass

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/738381.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-28
下一篇 2022-04-28

发表评论

登录后才能评论

评论列表(0条)

保存