Salesforce Apex Schema Describe

I found the need to develop a quick means of discovering custom fields that were added to standard objects.

The code block listed below is pasted into the Salesforce Developer console as an Anonymous Apex block.

A few key concepts covered in the code include: Using Schema Describe to get a map of all fields for a given object; and basic iteration.

// **********************
// Anonymous Apex Code -- Generates a list of all custom fields for sObjects (both Standard and Custom) to be used with package.xml metadata retrieval.
// ***********************
List<String> objectsToInventory = new List<String>();
objectsToInventory.add('Account');
objectsToInventory.add('Activity');
objectsToInventory.add('Contact');
//add more sObjects to the above as needed...

//System.debug('objectsToInventory = ' + objectsToInventory);

String customFieldResultForObject = '';
List<String> sortedKeyset;

//Iterate through our set of objectsToInventory, and for each, obtain the fields:
for (String objectToInventory: objectsToInventory) {

    if (Schema.getGlobalDescribe().get(objectToInventory) != null) {
        Map<String, Schema.SObjectField> mapFields = Schema.getGlobalDescribe().get(objectToInventory).getDescribe().fields.getMap();
           sortedKeyset = new List<String>();
        for (String fieldName: mapFields.keyset()){
            if (fieldName.contains('__c')) {
                sortedKeyset.add(objectToInventory + '.' + fieldName);
            }
        }

        //so we have these in alphabetical order, by custom object name for each sObject
        sortedKeyset.sort();
        for (String fieldName: sortedKeyset){
            customFieldResultForObject = customFieldResultForObject + '<members>' + fieldName + '</members>';

        }

    }

} //end for

   System.debug('<types>' + customFieldResultForObject + '<name>CustomField</name></types>');
//After this Apex code has run: grab the output, format the XML, and place in package.xml.
//If you're using Sublime Text 3, you can use 'Cmd+Shift+P' to select the Indent XML plugin.

The output of this is then pasted into my Org's package.xml (which I created using the Mavensmate plugin in Sublime Text 3), after a little XML formatting is applied.

If you have suggestions to improve the above code block, please drop me a line!