Shawn
python 3.7
from xml.dom.minidom import Document
# import xml.dom.minidom
class XmlMaker:
def __init__(self,txtpath,xmlpath):
self.txtPath = txtpath
self.xmlPath = xmlpath
self.txtList = []
def readtxt(self):
txtfile = open(self.txtPath,"r",encoding='gbk',errors='ignore')
self.txtList = txtfile.readlines()
for i in self.txtList:
oneline = i.strip().split(" ")
if len(oneline) != 5:
print("TxtError")
def makexml(self):
doc = Document()
orderpack = doc.createElement("OrderPack")
doc.appendChild(orderpack)
objecname = "Order"
for i in self.txtList:
oneline = i.strip().split(" ")
objectE = doc.createElement(objecname)
objectE.setAttribute("number",oneline[0])
objectcontent = doc.createElement("Content")
objectcontenttext = doc.createTextNode(oneline[1])
objectcontent.appendChild(objectcontenttext)
objectE.appendChild(objectcontent)
objectresult = doc.createElement("Result")
objectresulttext = doc.createTextNode(oneline[2])
objectresult.appendChild(objectresulttext)
objectE.appendChild(objectresult)
objectappname = doc.createElement("AppName")
objectappnametext = doc.createTextNode(oneline[3])
objectappname.appendChild(objectappnametext)
objectE.appendChild(objectappname)
objectdelay = doc.createElement("Delay")
objectdelaytext = doc.createTextNode(oneline[4])
objectdelay.appendChild(objectdelaytext)
objectE.appendChild(objectdelay)
orderpack.appendChild(objectE)
f = open(self.xmlPath, 'w')
doc.writexml(f, indent='\t', newl='\n', addindent='\t', encoding='gbk')
f.close()
if __name__ == "__main__":
read =XmlMaker("test.txt","test.xml")
read.readtxt()
read.makexml()
print(read.txtPath)
for i in read.txtList:
print(i)
0 命令0 结果0 app名0 延迟0
1 命令1 结果1 app名1 延迟1
2 命令2 结果2 app名2 延迟2
3 命令3 结果3 app名3 延迟3
4 命令4 结果4 app名4 延迟4
5 命令5 结果5 app名5 延迟5
<OrderPack>
<Order number="0">
<Content>命令0Content>
<Result>结果0Result>
<AppName>app名0AppName>
<Delay>延迟0Delay>
Order>
<Order number="1">
<Content>命令1Content>
<Result>结果1Result>
<AppName>app名1AppName>
<Delay>延迟1Delay>
Order>
<Order number="2">
<Content>命令2Content>
<Result>结果2Result>
<AppName>app名2AppName>
<Delay>延迟2Delay>
Order>
<Order number="3">
<Content>命令3Content>
<Result>结果3Result>
<AppName>app名3AppName>
<Delay>延迟3Delay>
Order>
<Order number="4">
<Content>命令4Content>
<Result>结果4Result>
<AppName>app名4AppName>
<Delay>延迟4Delay>
Order>
<Order number="5">
<Content>命令5Content>
<Result>结果5Result>
<AppName>app名5AppName>
<Delay>延迟5Delay>
Order>
OrderPack>