1 XML文件读取
测试文件 test.xml 内容如下:
<?xml version="1.0" encoding="utf-8"?>
<root>
<time>
<years>2022</years>
<month>04</month>
<day>24</day>
</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文件根节点
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
nodetime = root.find('time')
print(nodetime.text )
node_years = root.find('time/years')
print(node_years.text )
nodecom3 = root.findall(".//*[@Name='COM3']")
print(nodecom3, type(nodecom3))
print(nodecom3[0].attrib['Baund'])
在这里插入代码片
2 写XML文件
import xml.etree.ElementTree as ET
import xml.dom.minidom as minidom
'''
中文这个是转换前的,现在是打算把
<type>r</type>
<format>bin</format>
格式的转换到yx组
其他<type>r</type>
转换到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)
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'] )
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:
flag = 0
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__':
XmlConvert('PCS调试串口通信点表.xml')
pass
import xml.etree.ElementTree as ET
import xml.dom.minidom as minidom
'''
中文这个是转换前的,现在是打算把
<type>r</type>
<format>bin</format>
格式的转换到yx组
其他<type>r</type>
转换到yc组
'''
class Xmlwrite(object):
def __init__(self, xml):
self.xml_name = xml
self.dom = minidom.getDOMImplementation().createDocument(None, 'dmp', None)
root_attrib = {'station': 'PCS塔机测试','name': 'PCS_TOWER', 'kind':'PCS_TOWER' }
self.xmlroot = self.dom.documentElement
for i in range(5):
node = self.new_node('tag_name', "goodjob", None )
self.set_node_attrib(node, root_attrib )
def set_node_attrib(self, node , nodeinfo ):
for key,value in nodeinfo.items():
node.setAttribute(key,value)
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)
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'] )
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:
flag = 0
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__':
newxml = Xmlwrite("convert.xml")
newxml.save_xml("转化后文件.xml")
pass
|