我有一百多个FC,每个FC具有10或20个属性,每年添加或更改其别名两次或多次。不用说,这不是我要抱怨的事情。我如何使这个过程自动化?
首选Python解决方案,但会使用任何可行的方法。
我可以访问Arcgis 9.3.1和10(ArcInfo许可级别)。
我有一百多个FC,每个FC具有10或20个属性,每年添加或更改其别名两次或多次。不用说,这不是我要抱怨的事情。我如何使这个过程自动化?
首选Python解决方案,但会使用任何可行的方法。
我可以访问Arcgis 9.3.1和10(ArcInfo许可级别)。
Answers:
从10.1版开始,AlterAliasName() 可用于重新别名表:
table = r"C:\path\to\connection.sde\OWNER.TABLE"
arcpy.AlterAliasName(table, "table_alias")
从10.3版开始,Alter Field可用于重新别名字段:
table = r"C:\path\to\connection.sde\OWNER.TABLE"
arcpy.AlterField_management(table, "FIELD_NAME", new_field_alias="field_alias")
在Mark Cederholm的帮助下,我有了使用python和arcobjects的有效解决方案。它的边缘很粗糙,但是完成了工作。在遵循该页面上的配方之后,创建一个新脚本,该脚本使用中的GetLibPath, NewObj, CType, OpenFeatureClass
功能snippets.py
。还以.csv格式创建重命名查找表:
字段到字段别名查找(att_code-name_lookup.csv):
Attrib_Name,Alias_Name
CODE,Specification Code
VALDATE,Validity Date
...
FC Alias查找的要素类(fc_code-name_lookup.csv):
"FC_Name","AliasName"
"BS_1250009_0","Navigational Aid"
"BS_1370009_2","Residential Area"
...
和脚本:
import sys
sys.path.append('k:/code')
from snippets import GetLibPath, NewObj, CType, OpenFeatureClass
sWorkingDir = "k:/code/"
sFileGDB = sWorkingDir + "blank_canvec.gdb"
sResourceDir = "k:/code/"
sFCAliasFile = sResourceDir + "fc_code-name_lookup.csv"
sAttAliasFile = sResourceDir + "att_code-name_lookup.csv"
sProduct = "ArcEditor"
def BuildFieldAliasLookup():
lookup = {}
f = open(sAttAliasFile, "r")
bFirst = True
for line in f:
# Skip first line
if bFirst:
bFirst = False
continue
sTokens = line.replace('"','').split(',')
sFieldName = sTokens[0]
sAlias = sTokens[1]
lookup[sFieldName] = sAlias
return lookup
def AlterAlias():
# Initialize
from comtypes.client import GetModule
import arcgisscripting
sLibPath = GetLibPath()
GetModule(sLibPath + "esriGeoDatabase.olb")
GetModule(sLibPath + "esriDataSourcesGDB.olb")
import comtypes.gen.esriGeoDatabase as esriGeoDatabase
gp = arcgisscripting.create(9.3)
try:
gp.setproduct(sProduct)
except:
gp.AddMessage(gp.GetMessages(2))
# Build field alias lookup table
AttrLookup = BuildFieldAliasLookup()
# Open alias file and loop through lines
f = open(sFCAliasFile, "r")
bFirst = True
for line in f:
# Skip first line
if bFirst:
bFirst = False
continue
sTokens = line.replace('"','').split(',')
sFCName = sTokens[0]
sAlias = sTokens[1]
print "Processing: ", sFCName
# Open feature class
try:
pFC = OpenFeatureClass(sFCName)
except:
print "Could not open ", sFCName
continue
# Alter feature class alias
try:
pSE = CType(pFC, esriGeoDatabase.IClassSchemaEdit)
pSE.AlterAliasName(sAlias)
except:
print "Error altering class alias"
continue
# Alter field aliases
try:
for sKey in AttrLookup.keys():
i = pFC.FindField(sKey)
if i == -1:
continue
sAlias = AttrLookup[sKey]
pSE.AlterFieldAliasName(sKey, sAlias)
except:
print "Error altering field aliases"
print "Done."
print 'Field <--> Alias lookup table is:', BuildFieldAliasLookup()
print AlterAlias()
此代码在9.3.1中对我有用...
public static void TestAlterAlias(IApplication app)
{
// make a dictionary of old/new names
Dictionary<string, string> nameDict = new Dictionary<string, string>(StringComparer.CurrentCultureIgnoreCase);
nameDict.Add("qsectionalias", "qsectionalias2");
nameDict.Add("sursysalias", "sursysalias2");
string[] directories = System.IO.Directory.GetDirectories(@"D:\Projects\EmpireOil\data",@"*.gdb",
System.IO.SearchOption.TopDirectoryOnly);
foreach(string dir in directories)
{
List<IName> fcnames = GetFCNames(dir);
foreach (IName fcName in fcnames)
{
ChangeFieldAliases(fcName, nameDict);
}
}
}
public static void ChangeFieldAliases(IName fcName, Dictionary<string, string> aliasDict)
{
IFeatureClass fc = (IFeatureClass)fcName.Open();
IClassSchemaEdit3 cse = (IClassSchemaEdit3)fc;
((ISchemaLock)fc).ChangeSchemaLock(esriSchemaLock.esriExclusiveSchemaLock);
SortedList<string, string> changeList = new SortedList<string, string>();
for (int i = 0; i < fc.Fields.FieldCount; i++)
{
string fldName = fc.Fields.get_Field(i).Name;
string alias = fc.Fields.get_Field(i).AliasName;
if (aliasDict.ContainsKey(alias))
{
changeList.Add(fldName, aliasDict[alias]);
// set it blank for now, to avoid problems if two fields have same aliasname.
cse.AlterFieldAliasName(fldName, "");
}
}
// change the alias
foreach (KeyValuePair<string, string> kvp in changeList)
cse.AlterFieldAliasName(kvp.Key, kvp.Value);
((ISchemaLock)fc).ChangeSchemaLock(esriSchemaLock.esriSharedSchemaLock);
}
public static List<IName> GetFCNames(string wsPath)
{
List<IName> names = new List<IName>();
IWorkspaceFactory wsf = new ESRI.ArcGIS.DataSourcesGDB.FileGDBWorkspaceFactoryClass();
IWorkspace ws = wsf.OpenFromFile(wsPath, 0);
IEnumDatasetName enumName = ws.get_DatasetNames(esriDatasetType.esriDTAny);
enumName.Reset();
IDatasetName dsName = null;
while ((dsName = enumName.Next()) != null)
{
if(dsName is IFeatureClassName)
names.Add((IName)dsName);
else if(dsName is IFeatureDatasetName)
{
IEnumDatasetName enumName2 = dsName.SubsetNames;
enumName2.Reset();
IDatasetName dsName2;
while((dsName2=enumName2.Next())!= null)
{
if(dsName2 is IFeatureClassName)
names.Add((IName)dsName2);
}
}
}
return names;
}
另一个解决方案由Rob Clark提供:
您可以将featureclass_to_featureclass与字段映射一起使用。是的,它创建了另一个要素类,但是您可以在它执行操作的同时拥有一个输出区域来复制数据和更改别名。
在python中,该field_map
部分的语法很棘手,因此请以交互方式遍历一下,以将参数设置为直线,然后使其运行。然后转到结果窗口,右键单击并复制python snippet。这是一个重新组合为更易于扩展和重复使用的代码段(可以做更多工作来分解字段图和属性的各个部分):
inFC = 'e:/Canvec/fix.gdb/HD_1480009_2'
outFC = 'HD_with_aliases'
out_wspace = 'e:/canvec/fix.gdb'
where_clause = '#' # use default
config_keyword = '#' # "
# build field map
fmap_out_att = 'CODE /\Specification code/\ ' # field and alias name
fmap_properties = 'true true false 4 Long 0 0 ,First,#,' # field properties
fmap_in_att = 'e:/Canvec/fix.gdb/HD_1480009_2,CODE,-1,-1' # input FC and field
# construct the complete field map
field_map = fmap_out_att + fmap_properties + fmap_in_att
# results in:
# "CODE /\Specification code/\ true true false 4 Long 0 0 ,First,#,e:/Canvec/fix.gdb/HD_1480009_2,CODE,-1,-1"
arcpy.FeatureClassToFeatureClass_conversion(inFC, out_wspace, outFC,
where_clause, field_map, config_keyword)
# the template command copied from Results window, used for building above
# arcpy.FeatureClassToFeatureClass_conversion("e:/Canvec/fix.gdb/HD_1480009_2","e:/canvec/fix.gdb","HD_with_aliases3","#","CODE /\Specification code/\ true true false 4 Long 0 0 ,First,#,e:/Canvec/fix.gdb/HD_1480009_2,CODE,-1,-1","#")
该解决方案适用于使用SQL Server作为地理数据库的用户。您可以通过SQL更新命令手动更改它。所有功能的名称均保存在[sde]。[GDB_OBJECTCLASSES]表中。仅在更改别名列值时才设置别名。
UPDATE [sde].[sde].[GDB_OBJECTCLASSES]
SET AliasName = 'an alias name'
WHERE Name='your feature class name'
编辑:此方法是更改别名的快速方法。但是使用IClassSchemaEdit更好,因为在sql更新方法中,直到重置功能工作区之前,您才能使用别名。
Public Sub SetAliasName(FeatureClass As IFeatureClass, AliasName As String)
Dim abjTable As ITable = FeatureClass
Dim objClass As IObjectClass = abjTable
Dim edit As IClassSchemaEdit = objClass
edit.AlterAliasName(AliasName)
End Sub