Updated

Gunmen attacked a prisoner convoy north of Baghdad on Thursday, setting off a gun battle with troops in which 52 prisoners and eight soldiers were killed, officials said.

The attack came as Iraq's parliament was set to elect a president, part of a troubled political transition that has seen repeated delays despite the lightning advance of Sunni militants across much of northern and western Iraq last month.

U.N. chief Ban Ki-moon arrived in Baghdad earlier Thursday to encourage lawmakers to form a more inclusive government that can address the crisis.

The dawn attack began with militants firing mortar rounds on Iraqi army bases in the town of Taji, where suspects were being held on terrorism charges, prompting officials to evacuate the facilities, fearing a jailbreak.

As the convoy traveled through a remote area, roadside bombs went off and militants opened fire. The ensuing battle left 52 prisoners and eight soldiers dead, with another eight soldiers and seven prisoners wounded, they added. It was not immediately clear if the prisoners were killed by soldiers or militants, or if the extremist Islamic State group was involved.

The town of Taji is located some 20 kilometers (12 miles) north of the capital.

The officials -- two policemen, an army officer and a medical official -- spoke on condition of anonymity as they were not authorized to release information.

Militants affiliated with the Islamic State group -- which seized much of northern and western Iraq last month -- have staged several jailbreaks, including a complex, military-style assault on two Baghdad-area prisons in July 2013 that freed more than 500 inmates.

Apparently fearing a repeat of the incident, Shiite militiamen killed nearly four dozen Sunni detainees last month in the town of Baqouba northwest of Baghdad when the facility where they were being held came under attack, according to a report by Amnesty International.

The report documented a "pattern of extrajudicial executions" of mainly Sunni detainees by forces loyal to the Shiite-led government in Baqouba and in the north, basing its conclusions on interviews with survivors and relatives of those killed.

The rapid advance of the Islamic State group, which captured Iraq's second largest city of Mosul and declared a self-styled Islamic Caliphate straddling the Iraq-Syria border, has plunged Iraq into its worst crisis since U.S. troops withdrew in 2011.

Prime Minister Nouri al-Maliki has come under increasing pressure to step aside, with critics accusing him of monopolizing power and alienating the country's Sunni and Kurdish minorities. He has vowed to remain in his post, however, which he has held since 2006, and his bloc won the most votes in April elections.

The vote for president -- a largely ceremonial post currently held by Kurdish leader Jalal Talabani -- was to take place later Thursday after being delayed the day before.