8 – Validate XML content

We have one REST API for getting the XML from users. Sometimes users enter XML data with a wrong format, for example with missing tags.

The following code only checks the used content type.

$contentTypes = $allHeaders('Content-Type');
$requestmethod = Drupal::request()->server->get('REQUEST_METHOD');
$contentTypes = isset($_SERVER("CONTENT_TYPE")) ? trim($_SERVER("CONTENT_TYPE")) : '';

if (strcasecmp($contentTypes, 'application/xml') != 0) {
  return new ModifiedResourceResponse('Content type must be: application/xml');

How do I check the XML format is correct?