Summary:
A unit gains XPs for surviving a round of combat. The unit doesn't have to win the combat or destroy the enemy to get the experience; it accrues each round that the unit lives through.
The amount of XPs the unit gets depends upon the circumstances of the combat. Generally, units get more XPs for attacking than defending, and more for engaging in melee combat than for other types. Here are some numbers (see the Charts and Tables section for a complete list):
An Attacking Melee Unit: 5 XPs
Defending Against a Melee Attack: 4 XPs
An Attacking Ranged Unit: 2 XPs
Being Attacked by a Ranged Unit: 2 XPs
Barbarian Limitations: Once a unit has gotten 30 XPs, it no longer gets any additional XPs for fighting Barbarians.