通过迭代一组值在python中创建XML文件

时间:2017-02-09 03:38:17

标签: python xml lxml

我必须使用根名称'结构'创建一个xml文件。它应该包含各种子元素"数据包",每个子元素都包含元素的树结构。单个数据包应如下所示:

<L2>
        <srcmac>value1</srcmac>
        <dstmac>value2</dstmac>
    </L2>

    <L3>
        <dscp>
            <timetolive>value3</timetolive>
        </dscp>
    </L3>

    <L4>
        <protocol>value4</protocol>
    </L4>

应该迭代数据包&#39; n&#39;次数。 它给出了一些错误说: 非绑定方法write()必须使用ElementTree实例调用(改为使用str实例)

这是我写的代码:

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()

虽然我得到了一个XML文件作为输出,但最后一个条目似乎覆盖了所有以前的条目,并且只覆盖了&#39;数据包的最后一次迭代。存储在我生成的xml文件中。

我需要修改什么才能获得完整的树迭代并纠正write()错误?

1 个答案:

答案 0 :(得分:0)

我在你的代码中做了一些修改,包括样式改进,并将你的值替换为像占位符一样的协议,因为我既没有你的lib,也没有逻辑。据我测试,它解决了这两个问题。

from xml.etree import cElementTree as et


n = 5
value1 = 'value1'
value2 = 'value2'
value3 = 'value3'
protocol = 'protocol'


def main():
    root = et.Element("structure")

    # creating xml layout
    eachpacket = et.SubElement(root, "packet")

    for count in range(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")

        subchild1.text = str(value1)
        subchild2.text = str(value2)
        s2.text = str(value3)
        schild1.text = str(protocol)

    et.ElementTree.write(et.ElementTree(root), "FileNew.xml")


if __name__ == "__main__":
    main()