Federico Valverde scored the decisive goal in extra time after Ansu Fati had equalised with seven minutes of normal time remaining.
Vinicius Junior had earlier put Los Blancos ahead but Luuk de Jong restored parity before the interval, the Netherlands international scoring in three straight games for the first time since arriving in Spain.
Karim Benzema restored Madrid's lead before Fati brought Barca back on level terms.
Barca had 20 shots in the defeat, with six on target – its highest tally in an El Clasico since April 2006, when it had 35 under Frank Rijkaard.
Xavi was pleased with his side's display and said his players could be proud of their efforts.
"I think we were better than Madrid in terms of play, dominance, and we had the game under control," he told Movistar.
"We took a lot of risks and we knew how to control transitions, and this is the way to compete.
"In the end we had the match and if you toss a coin and it comes up heads, nobody would have said anything, but tails came up.
"We can go away proud because we have competed against them and it is a step forward despite the result.
"We are on the right track and while it was not a turning point in terms of the result, it was in terms of how we played and how we felt."
The result was Madrid's fifth consecutive win over Barca in all competitions – only the second time they have achieved this after a run of seven straight wins between 1962 and 1965.
Despite that, Gerard Pique was pleased with Barca's performance and predicts there are brighter days ahead for the Catalan giants.
"I think we competed very well," he said. "It is not the result we expected; losing against Madrid hurts but we are closer to winning. We need to win; we need that definitive step.
"We played well. We took risks and we have gone for the game. They arrived in the area with many players and they scored a goal but playing like this we are going to win.
"We should leave with our heads held high after competing like that against Madrid."