Created
November 12, 2024 08:29
-
-
Save mhf-ir/d645e813044a98a8b05fe5dcb7837491 to your computer and use it in GitHub Desktop.
python server xml validator via xsd
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask, request, jsonify | |
from lxml import etree | |
app = Flask(__name__) | |
def validate_xml_against_xsd(xml_content, xsd_content): | |
# Attempt to parse the XML content | |
try: | |
xml_doc = etree.fromstring(xml_content) | |
except etree.XMLSyntaxError as e: | |
return { | |
"ok": False, | |
"generalError": f"XML parsing error: {str(e)}", | |
"validationErrors": [] | |
} | |
# Attempt to parse and validate against the XSD content | |
try: | |
schema_root = etree.XML(xsd_content) | |
schema = etree.XMLSchema(schema_root) | |
schema.assertValid(xml_doc) | |
# No validation errors | |
return { | |
"ok": True, | |
"generalError": "", | |
"validationErrors": [] | |
} | |
except etree.XMLSyntaxError as e: | |
# Handle XSD parsing errors | |
return { | |
"ok": False, | |
"generalError": f"XSD parsing error: {str(e)}", | |
"validationErrors": [] | |
} | |
except etree.DocumentInvalid as e: | |
# Capture validation errors | |
validation_errors = [ | |
{ | |
"id": f"line{error.line}_col{error.column}", | |
"type": error.type, | |
"line": error.line, | |
"column": error.column, | |
"message": error.message, | |
"domain": error.domain_name, | |
"level": error.level_name | |
} | |
for error in e.error_log | |
] | |
return { | |
"ok": False, | |
"generalError": "", | |
"validationErrors": validation_errors | |
} | |
@app.route('/validate', methods=['POST']) | |
def validate(): | |
# Check if files are provided in the request | |
if 'xml' not in request.files or 'xsd' not in request.files: | |
return jsonify({ | |
"ok": False, | |
"generalError": "Please provide one XML file and one XSD file under the keys 'xml' and 'xsd'.", | |
"validationErrors": [] | |
}), 400 | |
# Read XML and XSD file contents | |
xml_file = request.files['xml'] | |
xsd_file = request.files['xsd'] | |
xml_content = xml_file.read() | |
xsd_content = xsd_file.read() | |
# Perform validation and structure the result | |
result = validate_xml_against_xsd(xml_content, xsd_content) | |
# Return JSON result with consistent structure | |
return jsonify(result) | |
if __name__ == '__main__': | |
app.run(debug=False) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment