1. 程式人生 > >python->解析xml檔案

python->解析xml檔案

'''
"D:\three_test\gpn_InternetGatewayDevice_v2.xml"

<SOAP-ENV:Envelope>
<SOAP-ENV:Header>
<cwmp:ID SOAP-ENV:mustUnderstand="1">1</cwmp:ID>
</SOAP-ENV:Header>
<SOAP-ENV:Body>
<cwmp:GetParameterNamesResponse>
<ParameterList xsi:type="SOAP-ENC:Array" SOAP-ENC:arrayType="cwmp:ParameterInfoStruct[6570]">
<ParameterInfoStruct>
<Name>InternetGatewayDevice.WANDeviceNumberOfEntries</Name>
<Writable>0</Writable>
</ParameterInfoStruct>
<ParameterInfoStruct>
<Name>InternetGatewayDevice.WANDevice.</Name>
<Writable>0</Writable>
</ParameterInfoStruct>
<ParameterInfoStruct>
</cwmp:GetParameterNamesResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
'''
import xmltodict

#將xml中的資料讀入記憶體並整個轉換成一個字典,放入doc
with open(r"D:\three_test\gpn_InternetGatewayDevice_v2.xml") as fd:
doc = xmltodict.parse(fd.read())

#取字典中的資料也很簡單,按照xml檔案中的格式依次往下即可
#e.g:取結點屬性
print(doc["SOAP-ENV:Envelope"]["SOAP-ENV:Header"]["cwmp:ID"]['@SOAP-ENV:mustUnderstand']) #1
print(doc['SOAP-ENV:Envelope']['SOAP-ENV:Body']['cwmp:GetParameterNamesResponse']['ParameterList']['@xsi:type']) #SOAP-ENC:Array
#e.g.取結點值
print(doc["SOAP-ENV:Envelope"]["SOAP-ENV:Header"]["cwmp:ID"]['#text']) #1
print(doc['SOAP-ENV:Envelope']['SOAP-ENV:Body']['cwmp:GetParameterNamesResponse']['ParameterList']['ParameterInfoStruct'][0]['Name']) #InternetGatewayDevice.WANDeviceNumberOfEntries

#e.g.如果是multiobject,將返回一個列表,列表中每一個元素都是一個物件OrderedDict([('Name', 'XXX'), ('Writable', 'X')])
list = doc["SOAP-ENV:Envelope"]["SOAP-ENV:Body"]["cwmp:GetParameterNamesResponse"]["ParameterList"]["ParameterInfoStruct"]
#遍歷列表中的每一個子字典,i為列表下標
for i,obj in enumerate(list):
print(obj['Name'])
print(obj['Writable'])
break;

#加入下面這兩條指令,程式碼執行到此處就相當於打了一個斷點,這中方式確定下路徑是否正確效率更高。
import pdb
pdb.set_trace()