因此,我试图升级代码以使ordernum数组包含每个单独的订单号(用分隔符分隔,但这并不是必须的,我太懒了,我复制粘贴了自己的代码)。
然后,当我添加最后一个代码块时,出现错误AttributeError: 'str' object has no attribute 'firstChild'
。我该如何解决?
import os
from xml.dom.minidom import parse
j=0
path = "C:/Users/User/Downloads"
quantity = []
# for every file in directory (path above)
for filename in os.listdir(path):
if not filename.endswith('.xml'): continue
fullname = os.path.join(path, filename) # add path and file together
data = parse(fullname) # parses XML
ordernum = data.getElementsByTagName('OrderNumber') # gets OrderNumber from XML
print(ordernum[0].firstChild.nodeValue) # prints OrderNumber from XML
quan = data.getElementsByTagName('OrderedQuantity') # same as above with OrderedQuantity
k=0
l=0
for k, q in enumerate(quan):
if q.firstChild.nodeValue != None:
quantity.append(quan[k].firstChild.nodeValue)
quantity.append("||separator||")
for l, p in enumerate(ordernum):
if p.firstChild.nodeValue != None:
ordernum.append(ordernum[l].firstChild.nodeValue)
ordernum.append("||separator||")
XML示例:
<OrderNumber>8762196_W0169</OrderNumber>
<OrderedQuantity>2.000</OrderedQuantity>
<OrderedQuantity>4.000</OrderedQuantity>
<OrderedQuantity>6.000</OrderedQuantity>
<OrderedQuantity>3.000</OrderedQuantity>
<OrderedQuantity>1.000</OrderedQuantity>
<OrderedQuantity>8.000</OrderedQuantity>
<OrderedQuantity>6.000</OrderedQuantity>
<OrderedQuantity>7.000</OrderedQuantity>
答案 0 :(得分:2)
因此在第二个循环中,您尝试枚举
for l, p in enumerate(ordernum):
在循环中,您还将元素添加到同一对象,即ordernum
因此,当您在循环本身内部进行填充时,对象长度也会增加。
尝试使用另一个对象/列表进行存储。