我已經解析了這個XML文件。也許我只是沒有抄好,但它的確定,所以,在這裏它是:xml列表的Python函數
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE raml SYSTEM 'raml20.dtd'>
<raml version="2.0" xmlns="raml20.xsd">
<cmData type="actual">
<managedObject class="LN" distName="PTR" id="2425">
<p name="aak">220</p>
<p name="orp">05</p>
<p name="name">Portro</p>
<p name="optres">false</p>
<p name="optblu">false</p>
<p name="aoptdet">false</p>
<p name="advcell">false</p>
<list name="sibList">
<item>
<p name="sibcity">177</p>
<p name="sibrep">2</p>
</item>
<item>
<p name="sibcity">177</p>
<p name="sibrep">1</p>
</item>
</list>
</managedObject>
<managedObject class="LN" distName="KRNS" id="93886">
<p name="aak">150</p>
<p name="orp">05</p>
<p name="name">Portro</p>
<p name="optres">false</p>
<p name="optblu">tru</p>
<p name="aoptdet">false</p>
<p name="advcell">true</p>
<list name="sibList">
<item>
<p name="sibcity">177</p>
<p name="sibrep">1</p>
</item>
<item>
<p name="sibcity">180</p>
<p name="sibrep">2</p>
</item>
</list>
</managedObject>
....
<managedObject>
...
</managedObject>
...
</cmData>
</raml>
我需要從第一managedObject經過的所有「managedObject」,並比較各參數(P名)與參數(AAK ,orp等)從另一個managedObjects獲取,並獲取它們的不同參數和值的輸出,如果沒有不同的參數值,則什麼也不做。我編寫了比較代碼,但我不知道如何通過列表(它被命名爲「sibList」)並比較參數。我寫了這個功能,其中關鍵是「P名」和值「P名」的價值:
temp = []
for i in temp_ln:
for j, k in zip(i.getchildren(), i):
temp.append([i.get('distName'), j.get('name'), j.text])
tempdict = {}
for i in temp_ln:
td = {}
for j in i.getchildren():
td.update({j.get('name'): j.text})
tempdict.update({i.get('distName'): td})
elements_list = {}
if j.get('name') == 'sibList':
for item in j.getchildren():
for w in item.getchildren():
elements_list.update({ w.get('name'): w.text})
main_dif = {}
for key, value in tempdict.iteritems():
dif_k = {}
for k, v in value.iteritems():
try:
a = ref[k]
except:
a = None
if v != a:
if k == 'name':
pass
else:
dif_k.update({k:(v, a)})
main_dif.update({key:dif_k})
你的問題很難理解。嗯,基本上你想遍歷XML並在所有'managedObject'節點上工作?你嘗試過'lxml'或'BeautifulSoup'嗎? – techouse
是的,我試過了。 我已更新我的代碼。 但現在我無法將sibList聲明爲特定的managedObject。 最後,我需要帶有managedObjects的excel文件作爲列,參數作爲行。值將是文本,例如:220,05,Portro等 – jovicbg
而且我需要提及的是,我使用了etree解析器。 @techouse – jovicbg