0

只需要一些快速帮助。假设我有以下 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.01, 2576.29" />
         <hole cost="102.12" />
       </hole>
    ........

编辑:这是我用来创建孔领的代码..等。

for row in reader:
    if i > 0:
        x1,y1,z1,x2,y2,z2,cost = row
        if current_group is None or i != current_group.text:
            current_group = SubElement(description, 'hole',{'hole_id':"%s"%i})

            collar = SubElement (current_group, 'hole',{'collar':', '.join((x1,y1,z1))}),
            toe = SubElement (current_group, 'hole',{'toe':', '.join((x2,y2,z2))})
            cost = SubElement(current_group, 'hole',{'cost':cost})
    i+=1

等等,我如何获得孔领、孔趾和孔成本数据。到目前为止,这是我的一段代码,我想我真的很接近。

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 文件是空的,这就是为什么我认为这段代码由于一些搜索和查找错误而无法获取数据的原因。任何人都可以帮忙吗?

4

1 回答 1

0

您没有指定,但我假设您使用的是 xml.etree.ElementTree。这里有几个问题:

1) XML 区分大小写。“钻孔”与“钻孔”不同。

2) 您的路径缺少在您的 XML 中找到的“描述”元素。

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 循环中的语句中列出属性,那么我个人只会取消 zip 并执行以下操作:

for a in root.findall("DrillHoles/description/hole"):
  writer.writerow([a.find("hole[@"+attr+"]").get(attr) for attr in ("collar", "toe", "cost")])
于 2013-07-04T16:40:43.613 回答