Python 查找XML数据并将其转换为CSV
只是需要一些快速的帮助。假设我将以下xml格式化为:Python 查找XML数据并将其转换为CSV,python,xml,csv,Python,Xml,Csv,只是需要一些快速的帮助。假设我将以下xml格式化为: <Solution version="1.0"> <DrillHoles total_holes="238"> <description> <hole hole_id="1"> <hole collar="5720.44, 3070.94, 2642.19" /> <hole toe="5797.82, 3061
<Solution version="1.0">
<DrillHoles total_holes="238">
<description>
<hole hole_id="1">
<hole collar="5720.44, 3070.94, 2642.19" />
<hole toe="5797.82, 3061.01, 2576.29" />
<hole cost="102.12" />
</hole>
........
依此类推,我如何获得孔领、孔趾和孔成本数据。这是我到目前为止的一段代码,我想我真的很接近了
with open(outfile, 'w') as file_:
writer = csv.writer(file_, delimiter="\t")
for a in zip(root.findall("drillholes/hole/hole collar"),
root.findall("drillholes/hole/hole toe"),
root.findall("drillholes/hole/hole cost")):
writer.writerow([x.text for x in a])
虽然我的程序生成了一个csv文件,但csv文件是空的,这就是为什么我认为这段代码由于一些搜索和查找错误而无法获取数据的原因。有人能帮忙吗?您没有指定,但我假设您使用的是xml.etree.ElementTree。这里有几个问题: 1) XML区分大小写。“钻孔”和“钻孔”不是一回事 2) 您的路径缺少XML中的“description”元素 3) 若要引用属性,您不使用空格,而是使用另一个前缀为“@”的路径元素,如“hole/@collar” 考虑到这些因素,答案应该是:
for a in zip(root.findall("DrillHoles/description/hole/hole/@collar"),
root.findall("DrillHoles/description/hole/hole/@toe"),
root.findall("DrillHoles/description/hole/hole/@cost")):
writer.writerow([x.text for x in a])
但事实并非如此。通过测试,findall似乎真的不喜欢返回属性节点,可能是因为它们在etree的API中并不存在。所以你可以这样做:
for a in zip(root.findall("DrillHoles/description/hole/hole[@collar]"),
root.findall("DrillHoles/description/hole/hole[@toe]"),
root.findall("DrillHoles/description/hole/hole[@cost]")):
writer.writerow([x[0].get('collar'), x[1].get('toe'), x[2].get('cost')])
for a in root.findall("DrillHoles/description/hole"):
writer.writerow([a.find("hole[@"+attr+"]").get(attr) for attr in ("collar", "toe", "cost")])
但是,如果您必须在for循环中列出语句中的属性,我个人只想取消zip并这样做:
for a in zip(root.findall("DrillHoles/description/hole/hole[@collar]"),
root.findall("DrillHoles/description/hole/hole[@toe]"),
root.findall("DrillHoles/description/hole/hole[@cost]")):
writer.writerow([x[0].get('collar'), x[1].get('toe'), x[2].get('cost')])
for a in root.findall("DrillHoles/description/hole"):
writer.writerow([a.find("hole[@"+attr+"]").get(attr) for attr in ("collar", "toe", "cost")])
所以,假设我在衣领、鞋头、鞋头前面没有“洞”,它只会是一个拉链(root.findall(“钻孔/描述/孔/领”)、root.findall(“钻孔/描述/孔/鞋头”)、root.findall(“钻孔/描述/孔/成本”)):writer.writerow([x.text代表a中的x])