I was being a bit flippant, by the way. But let's be honest, it really is the players who get the XP, when all's said and done.
No, it's not. Players don't exist. Characters earn XP, by doing things that are worth XP. There is in-game causality involved, even if it's sometimes weird to look at.
At the simplest level, characters get better at killing stuff whenever they kill stuff. The difference between a level 10 fighter and a level 1 fighter is that the level 10 fighter is much better at killing stuff. How did it get that way? By killing a lot of stuff. Causality. The concept of experience has in-game meaning, which closely aligns to its real-world meaning.
It gets kind of weird when you have characters earn XP for doing other things, or when they improve at non-killing abilities as a result of killing stuff. You have to make justifying assumptions, like saying that your fighter has been using this other skill all along, and that's why it improves when your combat level goes up. You take character level as an abstraction of combat level and skill level, and lump all of your XP together so that they progress at the same rate. It still works along the same concept, though. The character still gets better at doing whatever through practice and experience.
The XP is tied to the character, though. If you hand the character to another player, or if it becomes an NPC, then it retains all of its XP. If that character dies irrecoverably, then the XP goes with it. Sometimes a DMG will give advice on how to bring a new character into an existing campaign, but even then the new character doesn't start with the exact same XP as the old one; the advice is usually along the lines of "average party level" or "average party level - 1". And the details of how the
character earned that XP is left to discussion between the player and the DM.
To contrast, there are other games where XP
is explicitly given to the players. In these games, a character death (or retirement) means that the new character comes in with
exactly the same XP total as the old one. In the specific example I'm thinking of, the GM
also earns XP as a
reward for being the GM, to be put toward character advancement next time he or she gets to be a player.
That's a Storytelling game, though. It's not D&D.