我不确定我的循环结构有什么问题。也许这是一个命名问题,因为count变量和SubElement名称使用相同的变量。任何帮助表示赞赏。
from xml.etree import ElementTree as ET
root = ET.Element("painter")
root.set('version', '1.0')
linenum = 0
pointnum = 0
smpl_data = [[[20,40],(0,0,1,1)],[[10,50],(0,0,1,1)],[[78,89],(0,0,1,1)]]
while linenum <= len(smpl_data): #smpl_data change to self.lines
elem_line = ET.SubElement(root,"line" + str(linenum), attrib={"r": "1", "g": "2", "b": "3", "a": "4"})
elem_line.set("r", smpl_data[linenum][1][0])
print elem_line.attrib.get("r")
elem_line.set("g", smpl_data[linenum][1][1])
print elem_line.attrib.get("g")
elem_line.set("b", smpl_data[linenum][1][2])
print elem_line.attrib.get("b")
print elem_line.get("a")
elem_line.set("a", smpl_data[linenum][1][3])
print elem_line.attrib.get("a")
for pointnum in linenum:
elem_point = ET.SubElement("line" + str(linenum), "point" + str(pointnum), attrib={x: "10", y: "20"})
print elem_point
print elem_point.get("x")
elem_point.set("x", smpl_data[linenum][0][0])
print elem_point.attrib.get("x")
print elem_point.get("y")
elem_point.set("y", smpl_data[linenum][0][1])
print elem_point.attrib.get("y")
pointnum = pointnum + 1
linenum = linenum + 1
当我尝试开始迭代内部循环时,我得到了错误,因为在linenum中的pointnum。不确定为什么?
我为没有更清楚而道歉。
这是完整的错误:
Traceback (most recent call last):
File "C:\Users\joel\Desktop\open-autism-software\software\asd\pen\writexml.py", line 57, in <module>
for pointnum in linenum:
TypeError: 'int' object is not iterable
我在完整程序中的目标是能够将所有特定(x,y)点作为属性添加到它们各自的子元素(行)。每一行都附加到主根。但是,(x,y)点的数量随着我的持久数据而变化,因为每行可以是不同的长度。
XML文档应如下所示:
<root>
<line r="0", g="0", b="1", a="1">
<point x="20" y="30">
<point x="10" y="15">
<point x="15" y="25">
...
</line>
<line r="0", g"1", b="1", a="1">
...
</line>
...
</root>
答案 0 :(得分:3)
你可能想要
for pointnum in range(linenum):
即,所有数字从零到一小于亚麻
答案 1 :(得分:1)
linenum
不可迭代。很难说你在这里想做什么,但也许for pointnum in smpl_data[linenum]:
会是你想要的?