XML validation: Difference between revisions

m (→‎{{header|Raku}}: updated repo reference)
Line 461:
shiporder.xml validates
</pre>
 
=={{header|Nim}}==
{{libheader|libxml2}}
As in the C version, we use “libxml2” for the validation. As there is no Nim binding for this library, we provide the necessary definitions in our program (three types and six procedures). There is nothing more to do. In Nim, interfacing with C is often very easy.
 
Our program is based on the C version with many differences. In particular, we use the function “xmlSchemaValidateFile” rather than the function “xmlSchemaValidateDoc”.
 
<lang Nim>import os, strformat
 
const LibXml = "libxml2.so"
 
type
XmlSchemaParserCtxtPtr = pointer
XmlSchemaPtr = pointer
XmlSchemaValidCtxtPtr = pointer
 
 
# Declaration of needed "libxml2" procedures.
 
proc xmlSchemaNewParserCtxt(url: cstring): XmlSchemaParserCtxtPtr
{.cdecl, dynlib: LibXml, importc: "xmlSchemaNewParserCtxt".}
 
proc xmlSchemaParse(ctxt: XmlSchemaParserCtxtPtr): XmlSchemaPtr
{.cdecl, dynlib: LibXml, importc: "xmlSchemaParse".}
 
proc xmlSchemaFreeParserCtxt(ctxt: XmlSchemaParserCtxtPtr)
{.cdecl, dynlib: LibXml, importc: "xmlSchemaFreeParserCtxt".}
 
proc xmlSchemaNewValidCtxt(schema: XmlSchemaPtr): XmlSchemaValidCtxtPtr
{.cdecl, dynlib: LibXml, importc: "xmlSchemaNewValidCtxt".}
 
proc xmlSchemaValidateFile(ctxt: XmlSchemaValidCtxtPtr; filename: cstring; options: cint): cint
{.cdecl, dynlib: LibXml, importc: "xmlSchemaValidateFile".}
 
proc xmlSchemaFreeValidCtxt(ctxt: XmlSchemaValidCtxtPtr)
{.cdecl, dynlib: LibXml, importc: "xmlSchemaFreeValidCtxt".}
 
 
if paramCount() != 2:
quit &"Usage: {getAppFilename().lastPathPart} <XML Document Name> <XSD Document Name", QuitFailure
 
let xmlFilename = paramStr(1)
let xsdFilename = paramStr(2)
 
# Parse XML schema file.
let parserCtxt = xmlSchemaNewParserCtxt(xsdFilename)
let schema = parserCtxt.xmlSchemaParse()
parserCtxt.xmlSchemaFreeParserCtxt()
 
# Validate XML file using XML schema.
let validCtxt = schema.xmlSchemaNewValidCtxt()
case validCtxt.xmlSchemaValidateFile(xmlFilename, 0)
of 0:
echo &"“{xmlFilename}” validates."
of -1:
echo &"“{xmlFilename}” validation generated an internal error."
else:
echo &"“{xmlFilename}” fails to validate."
validCtxt.xmlSchemaFreeValidCtxt()</lang>
 
{{out}}
Using command <code>./xml_validate shiporder.xml shiporder.xsd</code>:
<pre>“shiporder.xml” validates.</pre>
Using a modified file “shiporder1.xml” where tag “orderperson” has been replaced by “orderperson1”:
<pre>Entity: line 6: Schemas validity error : Element 'orderperson1': This element is not expected. Expected is ( orderperson ).
“shiporder1.xml” fails to validate.</pre>
 
=={{header|Perl}}==
Anonymous user