使用python为XML中的节点设置数据

2024-07-03 07:59:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用Python从XML文件中读入数据结构,方法是克隆不同的节点(和节点组),然后更改节点中的一些数据并将其粘贴到新的.XML文件中。在

我现在有这段代码-当我试图从一个克隆节点创建多个节点时,它被封装在for循环中。每个新节点与克隆的数据略有不同:

i = 1

for alias in newchannels[:]:

    #split'alias' at commas and assign to content - this bit is just to retrieve the    correct data to be pasted into the nodes later
    content = alias.split(',')
    #extract data from array
    channelname = content[0]
    #ditto
    ip = content[2]
    port = content[3]

    #get channel info
    root_sChannel = root_sChannelList.getElementsByTagName("servermain:Channel")[0]
    #blank channel node
    root_sChannelClone = root_sChannel.cloneNode(False)

    #root_sChannelClone.firstChild.data = "SimulationChannel " + str(i)

    #clone servermain:Name attribute from previous xml file

    servermainName = root_sChannel.getElementsByTagName("servermain:Name")[0]

    #clone it
    servermainNameClone = servermainName.cloneNode(True)

    servermainNameClone.data = "SimulationChannel" + str(i)
    #this bit prints the data fine 
    print servermainNameClone.data
    #servermainNameClone.setAttributeNode("Simulation Channel" + str(i)) 

    #append to channel clone
    root_sChannelClone.appendChild(servermainNameClone)
    #this bit still prints the data fine
    print servermainNameClone.data

    #append other data here

    root_sChannelListClone.appendChild(root_sChannelClone)

    i+=1

我遇到的问题是,虽然在末尾附加节点之前数据似乎设置得很好(通过print语句检查),但当我实际检查输出的文件时,它实际上只是获取了“.cloneNode(True)”节点的“更深层”数据,然后直接复制而不做任何更改,这对我来说完全没有意义。我是否使用了错误的数据更改函数?在

编辑:请查收附件中的完整代码:

^{pr2}$

Tags: 文件theto数据data节点channelbit