1 回答
TA贡献1779条经验 获得超6个赞
尝试这个。
from simplified_scrapy import SimplifiedDoc, utils
def getKeyValues(nodeCols, dic, header):
for nodeCol in nodeCols:
childCols = nodeCol.children
if childCols:
getKeyValues(childCols, dic, header)
else:
tag = nodeCol.tag
v = dic.get(tag)
if v: # Cases with multiple values
dic[tag] = v + '|' + nodeCol.text # Splicing into 1 column
# i = 1
# while True:
# tag = tag + str(i)
# v = dic.get(tag)
# if v == None:
# dic[tag] = nodeCol.text
# break
# i = i + 1
else:
dic[tag] = nodeCol.text
if tag not in header:
header.append(tag)
xml = utils.getFileContent('OMGroups.xml')
doc = SimplifiedDoc(xml) # create doc
header = ['longName','shortName','nodeType'] # add column
dicRow = []
# nodes = doc.faults.children.child
parentNodes = doc.faults.children.children # add
for nodes in parentNodes: # add
for node in nodes: # logs,alarms...
if not node:
continue
family = node.parent
longName = family['longName'] # get the value
shortName = family['shortName']
nodeRows = node.children
for nodeRow in nodeRows: # log,log...
dicCol = {'longName': longName, 'shortName': shortName, 'nodeType': nodeRow.tag}
nodeCols = nodeRow.children # eventType,number
getKeyValues(nodeCols, dicCol, header)
dicRow.append(dicCol)
# Prepare the data and store it in the csv file
rows = [header]
for dic in dicRow:
rows.append([dic.get(k) for k in header])
utils.save2csv('test.csv', rows, newline='')
添加回答
举报