Changing feature class and field aliases in bulk using ArcPy?
With help from Mark Cederholm I have a working solution using python and arcobjects. It's rough around the edges, but it got the job done. After following the recipe on that page, create a new script which uses the GetLibPath, NewObj, CType, OpenFeatureClass
functions from snippets.py
. Also create the rename lookup tables in .csv format:
Field to Field Alias lookup (att_code-name_lookup.csv):
Attrib_Name,Alias_Name
CODE,Specification Code
VALDATE,Validity Date
...
Feature class to FC Alias lookup (fc_code-name_lookup.csv):
"FC_Name","AliasName"
"BS_1250009_0","Navigational Aid"
"BS_1370009_2","Residential Area"
...
and the script:
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()
As of version 10.1 AlterAliasName() can be used to re-alias tables:
table = r"C:\path\to\connection.sde\OWNER.TABLE"
arcpy.AlterAliasName(table, "table_alias")
As of version 10.3 Alter Field can be used to re-alias fields:
table = r"C:\path\to\connection.sde\OWNER.TABLE"
arcpy.AlterField_management(table, "FIELD_NAME", new_field_alias="field_alias")
This code works for me in 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;
}