xml文件格式:
<?xml version="1.0" encoding="utf-8"?>
<TrainingImages Version="1.0">
<Items number="37778">
<Item imageName="00016450.jpg" vehicleID="0001" cameraID="c001" colorID="1" typeID="4" />
<Item imageName="00016460.jpg" vehicleID="0001" cameraID="c001" colorID="1" typeID="4" />
<Item imageName="00016470.jpg" vehicleID="0001" cameraID="c001" colorID="1" typeID="4" />
<Item imageName="00016480.jpg" vehicleID="0001" cameraID="c001" colorID="1" typeID="4" />
</Items>
</TrainingImages>
可以看到呈現三級目錄:TrainingImages-Items-Item
現在要完成的任務是:
將imageName和colorID中的內容提取出來放在一個txt文件中;
我們事先準備好一個value.txt文件和py文件在同一目錄下;
涉及的知識點有:
- 讀取xml格式文件
- 通過循環語句向txt文件中寫入內容
上代碼:
import os
import sys
import xml.dom.minidom
dom=xml.dom.minidom.parse('train_label.xml') #獲取xml文件的dom樹
root=dom.documentElement #獲取根節點,也就是TrainingImages中的內容
Items=root.getElementsByTagName('Items') #獲取Items的內容
Item=Items[0] #第一個元素中保存在其中的內容,這一步要注意
its=Item.getElementsByTagName('Item') #獲取具體的Item
print(len(its)) #打印出長度,如示例中有4個數據,就有四個
filename = 'value.txt' #要寫入的txt文件名
with open(filename,'w') as f: #將txt寫入操作放在循環之前,實現循環寫入
for it in its:
name=it.getAttribute("imageName") #獲取xml子標題的屬性值
color=it.getAttribute("colorID")
f.write(name)
f.write(" ")
f.write(color)
f.write("\n")
print("ok")
如上代碼+註釋,可以通過dir()、len()、type()等操作進行嘗試探尋變量類型及屬性