0
我必須創建一個具有根名「結構」的xml文件,它應該由各種子元素「包」組成,每個子包含元素的樹結構。一個數據包應該如下所示:通過遍歷一組值來在python中創建XML文件
<L2>
<srcmac>value1</srcmac>
<dstmac>value2</dstmac>
</L2>
<L3>
<dscp>
<timetolive>value3</timetolive>
</dscp>
</L3>
<L4>
<protocol>value4</protocol>
</L4>
Th數據包應重複「n」次。 它給出了一些錯誤說:
import xml.etree.cElementTree as et
import pcapy
import sys
from struct import*
def main():
count=1
root=et.Element("structure")
#creating xml layout
eachpacket=et.SubElement(root,"packet")
while count<n:
child1=et.SubElement(eachpacket,"L2")
subchild1=et.SubElement(child1,"smac")
subchild2=et.SubElement(child1,"dmac")
child2=et.SubElement(eachpacket,"L3")
sub1=et.SubElement(child2,"sip")
sub2=et.SubElement(child2,"dip")
sub3=et.SubElement(child2,"dscp")
s2=et.SubElement(sub3,"timetolive")
child3=et.SubElement(eachpacket,"L4")
schild1=et.SubElement(child3,"protocol")
try:
count=count+1
subchild1.text=str(value1)
subchild2.text=str(value2)
s2.text=str(value3)
schild1.text=str(protocol)
except:
break
else:
tree=et.ElementTree(root)
tree.write("FileNew.xml")
pass
if __name__== "__main__":
main()
雖然我:不受約束的方法寫()必須與ElementTree的實例(而不是得到了海峽實例)
這是我所編寫的代碼被稱爲得到了一個XML文件作爲輸出,但最後一個條目似乎覆蓋了所有以前的條目,並且只有'數據包'的最後一次迭代存儲在我生成的xml文件中。
我需要修改什麼來獲得完整的樹迭代並糾正write()錯誤?
x,value1,value2,value3和protocol的值是多少?顯示你的所有代碼。 – swatchai
@swatchai它實際上讀取.pcap(數據包)文件,並從中獲取源mac,目標mac地址,並使用packet.next()將其移至pcap文件中的下一個數據包。我已經檢查過,沒有問題。然而,由於我是etree概念以及python的新手,我無法得到我需要做的來獲得正確的輸出。現在,你可以嘗試打印value1,value2等值到「包」的每一個迭代.....你能建議某種方式來解決我的問題嗎? –