Skip to content

Instantly share code, notes, and snippets.

@Blacksmoke16
Created June 16, 2022 01:29
Show Gist options
  • Save Blacksmoke16/98baeb545d9ff5af70fe3966edb2d858 to your computer and use it in GitHub Desktop.
Save Blacksmoke16/98baeb545d9ff5af70fe3966edb2d858 to your computer and use it in GitHub Desktop.
XML2 XSD Schema validation
require "xml"
lib LibXML
type XMLSchemaParserCtxtPtr = Void*
type XMLSchemaValidCtxtPtr = Void*
struct XMLError
domain : Int
code : Int
message : UInt8*
end
type XMLErrorPtr = XMLError*
type XMLSchemaPtr = Void*
alias XMLStructuredErrorFunc = Proc(Void*, XMLErrorPtr, Nil)
fun xmlSchemaNewValidCtxt(schema : XMLSchemaPtr) : XMLSchemaValidCtxtPtr
fun xmlSchemaNewParserCtxt(url : UInt8*) : XMLSchemaParserCtxtPtr
fun xmlSchemaParse(ctxt : XMLSchemaParserCtxtPtr) : XMLSchemaPtr
fun xmlSchemaFreeParserCtxt(ctxt : XMLSchemaParserCtxtPtr) : Void
fun xmlCleanupParser : Void
fun xmlReaderForFile(filename : UInt8*, encoding : UInt8*, options : Int) : XMLTextReader
fun xmlTextReaderSchemaValidateCtxt(reader : XMLTextReader, ctxt : XMLSchemaValidCtxtPtr, options : Int) : Int
fun xmlSchemaSetValidStructuredErrors(ctxt : XMLSchemaValidCtxtPtr, serror : XMLStructuredErrorFunc, ctx : Int*) : Void
fun xmlFreeTextReader(reader : XMLTextReader)
fun xmlInitParser : Void
end
ERROR_HANDLER = LibXML::XMLStructuredErrorFunc.new do |_, err|
pp String.new err.value.message
end
LibXML.xmlInitParser
parser_ctx = LibXML.xmlSchemaNewParserCtxt "./shiporder.xsd"
schema = LibXML.xmlSchemaParse parser_ctx
LibXML.xmlSchemaFreeParserCtxt parser_ctx
valid_ctx = LibXML.xmlSchemaNewValidCtxt schema
reader = LibXML.xmlReaderForFile "./shiporder.xml", nil, 0
LibXML.xmlTextReaderSchemaValidateCtxt reader, valid_ctx, 0
LibXML.xmlSchemaSetValidStructuredErrors valid_ctx, ERROR_HANDLER, out has_errors
ret = LibXML.xmlTextReaderRead reader
while ret == 1 && !has_errors.zero?
ret = LibXML.xmlTextReaderRead reader
end
if ret != 0
raise XML::Error.new LibXML.xmlGetLastError
end
LibXML.xmlFreeTextReader reader
LibXML.xmlCleanupParser
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment