[SalesForce] XML parsing in Apex

I want to get the task Id from the below response.

<?xml version="1.0" encoding="utf-8"?>
<response>
    <task id="56639c84-7f73-4ace-b7ab-a46683ff0e25" registrationTime="2017-06-07T13:46:11Z" statusChangeTime="2017-06-07T13:46:11Z" status="Queued" filesCount="1" credits="10" estimatedProcessingTime="5" />
</response>

Anyone help me how can i get the above task id in apex?

Best Answer

You can use the Document and XmlNode classes in the DOM namespace to parse XML.

String xml = '<?xml version="1.0" encoding="utf-8"?><response><task id="56639c84-7f73-4ace-b7ab-a46683ff0e25" registrationTime="2017-06-07T13:46:11Z" statusChangeTime="2017-06-07T13:46:11Z" status="Queued" filesCount="1" credits="10" estimatedProcessingTime="5" /></response>';
DOM.Document document = new DOM.Document();
document.load(xml);
String taskId = document.getRootElement()
    .getChildElement('task', null)
    .getAttribute('id', null);
system.debug(taskId);