如何检索ShapeFile要素字段的字段名称?

时间:2013-07-16 10:47:53

标签: ruby gdal esri ogr

我正在使用gdal-ruby来解析此ESRI ShapeFiles中的demo。我想迭代所有功能,以便将字段值推送到数据库中。但是,我无法找到如何检索数据库列所需的每个字段的名称。到目前为止,我只能使用字段的字段索引,例如:

dataset = Gdal::Ogr.open(filename)
number_of_layers = dataset.get_layer_count
number_of_layers.times do |layer_index|
  layer = dataset.get_layer(layer_index)
  layer.get_feature_count.times do |feature_index|
    feature = layer.get_feature(feature_index)
    feature.get_field_count.times do |field_index|
      field_value = feature.get_field(field_index)
      # How can I find out the name of the field?
      puts "Value = #{field_value} for unknown field name"
    end
  end
end

我使用 irb 检查了可用的方法并查看了API documentation。好像我在寻找错误的条款。

1 个答案:

答案 0 :(得分:1)

查看OGR API本身,我认为您需要通过feature.GetDefnRef获取功能定义,然后.GetFieldDefn获取相关字段,最后.GetNameRef ... ?

...
feature.get_field_count.times do |field_index|
  defn_ref = feature.get_defn_ref
  field_defn = defn_ref.get_field_defn(field_index)
  field_name = field_defn.get_name
  field_value = feature.get_field(field_index)
  puts "Value = #{field_value} for field named #{field_name}"
end
...