How to validate an XML File in Python

File validation is a good way to ensure that the rest of your day remains running smoothly. Today we will be focusing on XML files. I will show you an effortless solution that will forever remove broken XML from your life. Let’s begin.

Using this Cloudmersive API, we can slim down the work required from us today to almost nothing:

pip install cloudmersive-convert-api-client

Calling validate_document_xml_validation comes next. This will require an API instance to work. Here’s how to go about creating that and using it:

from __future__ import print_functionimport timeimport cloudmersive_convert_api_clientfrom cloudmersive_convert_api_client.rest import ApiExceptionfrom pprint import pprint# Configure API key authorization: Apikeyconfiguration = cloudmersive_convert_api_client.Configuration()configuration.api_key['Apikey'] = 'YOUR_API_KEY'# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed# configuration.api_key_prefix['Apikey'] = 'Bearer'# create an instance of the API classapi_instance = cloudmersive_convert_api_client.ValidateDocumentApi(cloudmersive_convert_api_client.ApiClient(configuration))input_file = '/path/to/file' # file | Input file to perform the operation on.try:# Validate an XML fileapi_response = api_instance.validate_document_xml_validation(input_file)pprint(api_response)except ApiException as e:print("Exception when calling ValidateDocumentApi->validate_document_xml_validation: %s\n" % e)

Now we just need a file path and we have officially hit pay dirt! That’s right, all finished.

Image for post
Image for post
Victory!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store