German Chancellor Angela Merkel's candidate for president has finally secured victory after a dramatic three rounds of voting.
Rebel votes in the ruling centre-right coalition twice deprived Christian Wulff of an outright win against challenger Joachim Gauck.
But Mr Wulff won the third round with 625 votes to 494 for Mr Gauck.
Although the role of president is largely symbolic, the protracted vote is seen as embarrassing for Mrs Merkel.
The BBC's Steve Rosenberg in Berlin says Chancellor Merkel's popularity is falling and her government is riven by infighting.
Today her candidate won - but Angela Merkel remains under pressure, he adds.
After the final vote in the Bundestag chamber of the Reichstag building, Mrs Merkel expressed confidence in her candidate.
"Ladies and gentlemen, an eventful day has ended and Christian Wulff is the president of the Federal Republic of Germany," she said.
"This was our nomination, out of conviction, because we believe that he will represent this country as president in a wonderful way."
Mr Wulff, the Lower Saxony state governor and a deputy leader of Mrs Merkel's Christian Democratic Party, sounded an optimistic note after his election, saying: "I'm looking forward to this responsible position."
It was only the third time in German post-war history that a presidential election has gone to a third round.
Mr Wulff will succeed Horst Koehler, who resigned a month ago.
In the first round he was 23 ballots short. Then in the second round, he fell eight votes short of an absolute majority.
Mr Gauck, a non-partisan civil rights campaigner put forward by the centre left, appeared close to tears as his supporters applauded his result in the third ballot, which needed a simple majority.
But the biggest cheers came from Mrs Merkel's supporters when it was clear Mr Wulff had won.
In the special session of the parliament, 1,244 representatives could take part. Half were federal legislators and half state-parliament nominees.
Much of Germany's media saw the longest presidential vote in German history - stretching into around nine hours - as a setback for the chancellor.
The daily Handelsblatt called it a "debacle" and Die Zeit called the result a "humiliation" for the government.
Bild, the mass-circulation daily, said it was a "massive slap for the ruling coalition".
Susanne Hoell, political editor for Suddeutsche Zeitung, said: "One thing has become clear out of all this - support for Merkel in her own coalition has withered away dramatically.
"She will likely be able to carry on until the end of her term but these will be three lost years for our country."