XML validation: Difference between revisions

Added FreeBASIC
(Added FreeBASIC)
 
(5 intermediate revisions by 4 users not shown)
Line 8:
{{libheader|LibXML}}
At the time of writing, the XML and XSD files at the URLs used in the other examples were inaccessible. The files from the W3 Schools page were used for tests.
<syntaxhighlight lang="c">
<lang C>
#include <libxml/xmlschemastypes.h>
 
Line 69:
return 0;
}
</syntaxhighlight>
</lang>
Output, files used from the W3 Schools page :
<pre>
Line 77:
 
=={{header|C sharp}}==
<langsyntaxhighlight lang="csharp">
using System;
using System.Xml;
Line 107:
}
}
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
{{libheader|libxml2}}
<syntaxhighlight lang="vbnet">#include once "crt/stdio.bi"
#include once "crt/stdlib.bi"
#include once "libxml/tree.bi"
#include once "libxml/parser.bi"
 
'' Load the XML document
dim as xmlDocPtr doc = xmlReadFile("document.xml", NULL, 0)
if doc = NULL then
print "Error opening XML document."
end 1
end if
 
'' Load the XSD schema
dim as xmlSchemaParserCtxtPtr ctxt = xmlSchemaNewParserCtxt("schema.xsd")
if ctxt = NULL then
print "Error opening XSD schema."
xmlFreeDoc(doc)
end 1
end if
 
'' Parse the XSD schema
dim as xmlSchemaPtr schema = xmlSchemaParse(ctxt)
if schema = NULL then
print "Error parsing XSD schema."
xmlSchemaFreeParserCtxt(ctxt)
xmlFreeDoc(doc)
end 1
end if
 
'' Create a validation context
dim as xmlSchemaValidCtxtPtr vctxt = xmlSchemaNewValidCtxt(schema)
if vctxt = NULL then
print "Error creating validation context."
xmlSchemaFree(schema)
xmlSchemaFreeParserCtxt(ctxt)
xmlFreeDoc(doc)
end 1
end if
 
'' Validate the XML document against the XSD schema
if xmlSchemaValidateDoc(vctxt, doc) = 0 then
print "The XML document is valid according to the XSD schema."
else
print "The XML document is not valid according to the XSD schema."
end if
 
'' Free resources
xmlSchemaFreeValidCtxt(vctxt)
xmlSchemaFree(schema)
xmlSchemaFreeParserCtxt(ctxt)
xmlFreeDoc(doc)
xmlCleanupParser()</syntaxhighlight>
 
=={{header|F_Sharp|F#}}==
<p>Using an inline stylesheet:</p>
<langsyntaxhighlight lang="fsharp">open System.Xml
open System.Xml.Schema
open System.IO
Line 174 ⟶ 229:
printfn "%A" (Seq.toList (vData None).Value)
0
</syntaxhighlight>
</lang>
{{out}}
<pre style="white-space:pre-wrap">>RosettaCode
Line 187 ⟶ 242:
</pre>
<p>Changing <code>wrong</code> to a boolean, e. g. <code>true</code>, The result (without -w) is <pre>[[Error, 0]]</pre>
 
=={{header|FutureBasic}}==
FB has native XML validators.
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
include "Tlbx XML.incl"
 
// Sample XML courtesy https://www.w3schools.com/xml/schema_example.asp
local fn Sample1XMLDocument as CFStringRef
CFStringRef xmlDoc = @"<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n¬
<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n¬
<xs:element name=\"shiporder\">\n¬
<xs:complexType>\n¬
<xs:sequence>\n¬
<xs:element name=\"orderperson\" type=\"xs:string\"/>\n¬
<xs:element name=\"shipto\">\n¬
<xs:complexType>\n¬
<xs:sequence>\n¬
<xs:element name=\"name\" type=\"xs:string\"/>\n¬
<xs:element name=\"address\" type=\"xs:string\"/>\n¬
<xs:element name=\"city\" type=\"xs:string\"/>\n¬
<xs:element name=\"country\" type=\"xs:string\"/>\n¬
</xs:sequence>\n¬
</xs:complexType>\n¬
</xs:element>\n¬
<xs:element name=\"item\" maxOccurs=\"unbounded\">\n¬
<xs:complexType>\n¬
<xs:sequence>\n¬
<xs:element name=\"title\" type=\"xs:string\"/>\n¬
<xs:element name=\"note\" type=\"xs:string\" minOccurs=\"0\"/>\n¬
<xs:element name=\"quantity\" type=\"xs:positiveInteger\"/>\n¬
<xs:element name=\"price\" type=\"xs:decimal\"/>\n¬
</xs:sequence>\n¬
</xs:complexType>\n¬
</xs:element>\n¬
</xs:sequence>\n¬
<xs:attribute name=\"orderid\" type=\"xs:string\" use=\"required\"/>\n¬
</xs:complexType>\n¬
</xs:element>\n¬
</xs:schema>"
end fn = xmlDoc
 
local fn ValidateXML( string as CFStringRef ) as BOOL
ErrorRef err = NULL
XMLDocumentRef xmlDoc = fn XMLDocumentWithXMLString( string, NSXMLDocumentValidate + NSXMLNodePreserveAll, err )
if err then NSLog( @"Error: %@", fn ErrorLocalizedDescription( err ) ) : exit fn
BOOL validXML = fn XMLDocumentValidate( xmlDoc, err )
if err then NSLog( @"Error: %@", fn ErrorLocalizedDescription( err ) ) else exit fn = validXML
end fn = NO
 
CFStringRef xmlDoc, xmlName
BOOL success
 
xmlDoc = fn Sample1XMLDocument
success = fn ValidateXML( xmlDoc )
xmlName = @"XML Sample No. 1"
if success then NSLog( @"%@: XML document is valid.\n", xmlName ) else NSLog( @"%@ XML document is invalid.\n", xmlName )
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
XML Sample No. 1: XML document is valid.
</pre>
 
=={{header|Go}}==
Line 192 ⟶ 311:
<br>
This uses the w3schools test data linked to above.
<langsyntaxhighlight lang="go">package main
 
import (
Line 241 ⟶ 360:
 
fmt.Println("Validation of", xmlfile, "against", xsdfile, "successful!")
}</langsyntaxhighlight>
 
{{out}}
Line 252 ⟶ 371:
 
Solution:
<langsyntaxhighlight lang="groovy">import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI
import javax.xml.transform.stream.StreamSource
import javax.xml.validation.SchemaFactory
Line 265 ⟶ 384:
false
}
}</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="groovy">def schemaLoc = "http://venus.eas.asu.edu/WSRepository/xml/Courses.xsd"
def docLoc = "http://venus.eas.asu.edu/WSRepository/xml/Courses.xml"
println "Document is ${validate(schemaLoc, docLoc)? 'valid' : 'invalid'}"</langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI;
 
import java.net.MalformedURLException;
Line 345 ⟶ 464:
}
}
}</langsyntaxhighlight>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">using LightXML
 
const Xptr = LightXML.Xptr
Line 375 ⟶ 494:
 
xsdvalidatexml()
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
Line 389 ⟶ 508:
</pre>
Next, you need to compile the following Kotlin program, linking against libxml_schemas.klib.
<langsyntaxhighlight lang="scala">// Kotlin Native v0.6
 
import kotlinx.cinterop.*
Line 455 ⟶ 574:
xmlCleanupParser()
xmlMemoryDump()
}</langsyntaxhighlight>
Finally, the resulting .kexe file should be executed passing it similar command line arguments to the C entry to produce the following output.
<pre>
Line 468 ⟶ 587:
Our program is based on the C version with many differences. In particular, we use the function “xmlSchemaValidateFile” rather than the function “xmlSchemaValidateDoc”.
 
<langsyntaxhighlight Nimlang="nim">import os, strformat
 
const LibXml = "libxml2.so"
Line 519 ⟶ 638:
else:
echo &"“{xmlFilename}” fails to validate."
validCtxt.xmlSchemaFreeValidCtxt()</langsyntaxhighlight>
 
{{out}}
Line 530 ⟶ 649:
=={{header|Perl}}==
 
<langsyntaxhighlight lang="perl">#!/usr/bin/env perl -T
use 5.018_002;
use warnings;
Line 563 ⟶ 682:
}
};
}</langsyntaxhighlight>
 
{{out}}
Line 578 ⟶ 697:
The libxml.e wrapper was penned specifically for this task and is just about as
bare-bones as it could ever possibly be, and win32-only, for now.
<!--<langsyntaxhighlight Phixlang="phix">(notonline)-->
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\Validate_XML.exw
Line 619 ⟶ 738:
<span style="color: #000000;">xmlCleanupParser</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">xmlMemoryDump</span><span style="color: #0000FF;">()</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 633 ⟶ 752:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">
libxml_use_internal_errors(true);
 
Line 644 ⟶ 763:
echo 'success';
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 674 ⟶ 793:
=={{header|Python}}==
 
<langsyntaxhighlight lang="python">#!/bin/python
from __future__ import print_function
import lxml
Line 702 ⟶ 821:
root = etree.fromstring("<a>5<b>foobar</b></a>", parser)
except lxml.etree.XMLSyntaxError as err:
print (err)</langsyntaxhighlight>
 
{{out}}
Line 711 ⟶ 830:
(formerly Perl 6)
{{trans|Perl}}
<syntaxhighlight lang="raku" line>
<lang perl6>
# Reference: https://github.com/libxml-raku/LibXML-raku
 
Line 733 ⟶ 852:
try { LibXML::Schema.new( string => $xsdschema ).validate( $x ) }
!$! ?? say "Valid." !! say $!.message() ;
}</langsyntaxhighlight>
{{out}}
<pre>Valid.
Line 740 ⟶ 859:
 
=={{header|Scala}}==
<langsyntaxhighlight Scalalang="scala">import java.net.URL
 
import javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI
Line 786 ⟶ 905:
}
}
}</langsyntaxhighlight>
 
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">require('XML::LibXML')
 
func is_valid_xml(str, schema) {
Line 816 ⟶ 935:
[good_xml, bad_xml].each { |xml|
say "is_valid_xml(#{xml.dump}) : #{is_valid_xml(xml, xmlschema_markup)}"
}</langsyntaxhighlight>
{{out}}
<pre>
Line 822 ⟶ 941:
is_valid_xml("<a>5<b>foobar</b></a>") : false
</pre>
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
Option explicit
 
Function fileexists(fn)
fileexists= CreateObject("Scripting.FileSystemObject").FileExists(fn)
End Function
 
Function xmlvalid(strfilename)
Dim xmldoc,xmldoc2,objSchemas
Set xmlDoc = CreateObject("Msxml2.DOMDocument.6.0")
If fileexists(Replace(strfilename,".xml",".dtd")) Then
xmlDoc.setProperty "ProhibitDTD", False
xmlDoc.setProperty "ResolveExternals", True
xmlDoc.validateOnParse = True
xmlDoc.async = False
xmlDoc.load(strFileName)
ElseIf fileexists(Replace(strfilename,".xml",".xsd")) Then
xmlDoc.setProperty "ProhibitDTD", True
xmlDoc.setProperty "ResolveExternals", True
xmlDoc.validateOnParse = True
xmlDoc.async = False
xmlDoc.load(strFileName)
'import xsd
Set xmlDoc2 = CreateObject("Msxml2.DOMDocument.6.0")
xmlDoc2.validateOnParse = True
xmlDoc2.async = False
xmlDoc2.load(Replace (strfilename,".xml",".xsd"))
'cache xsd
Set objSchemas = CreateObject("MSXML2.XMLSchemaCache.6.0")
objSchemas.Add "", xmlDoc2
Else
Set xmlvalid= Nothing:Exit Function
End If
Set xmlvalid=xmldoc.parseError
End Function
 
 
 
Sub displayerror (parserr) 'display the info returned by Msxml2
Dim strresult
If parserr is Nothing Then
strresult= "could not find dtd or xsd for " & strFileName
Else
With parserr
Select Case .errorcode
Case 0
strResult = "Valid: " & strFileName & vbCr
Case Else
strResult = vbCrLf & "ERROR! Failed to validate " & _
strFileName & vbCrLf &.reason & vbCr & _
"Error code: " & .errorCode & ", Line: " & _
.line & ", Character: " & _
.linepos & ", Source: """ & _
.srcText & """ - " & vbCrLf
End Select
End With
End If
WScript.Echo strresult
End Sub
 
'main
Dim strfilename
 
'testing validation with dtd
'strfilename="books.xml"
'displayerror xmlvalid (strfilename)
 
'testing validation with xsd
strfilename="shiporder.xml"
displayerror xmlvalid (strfilename)
</syntaxhighlight>
{{out}}
<small>
<pre>
Valid: shiporder.xml
</pre>
</small>
 
=={{header|Visual Basic .NET}}==
Line 827 ⟶ 1,030:
{{works with|.NET Core|2.1}}
 
<langsyntaxhighlight lang="vbnet">Option Compare Binary
Option Explicit On
Option Infer On
Line 856 ⟶ 1,059:
If errors.Count = 0 Then Console.WriteLine("The document is valid.")
End Sub
End Module</langsyntaxhighlight>
 
{{out}}
Line 864 ⟶ 1,067:
An alternative is to use XmlReader (like the C# and F# examples [as of 2019-08-06]).
 
<langsyntaxhighlight lang="vbnet"> Function GetValidationErrorsXmlReader(doc As XDocument, schemaSet As XmlSchemaSet, warnings As Boolean) As IList(Of ValidationEventArgs)
GetValidationErrorsReader = New List(Of ValidationEventArgs)
 
Line 879 ⟶ 1,082:
Do While reader.Read() : Loop
End Using
End Function</langsyntaxhighlight>
 
Creating the documents (same as F#) from strings (does not handle syntax errors):
 
<langsyntaxhighlight lang="vbnet">Module Constants
Const SCHEMA As String =
"<?xml version='1.0'?>
Line 918 ⟶ 1,121:
Return XDocument.Parse(DOCUMENT)
End Function
End Module</langsyntaxhighlight>
 
Alternatively, we can be cheeky and use VB's XML literals...
 
<langsyntaxhighlight lang="vbnet">Module Constants
Function GetDocument() As XDocument
Return _
Line 953 ⟶ 1,156:
</xs:schema>
End Function
End Module</langsyntaxhighlight>
 
=={{header|Wren}}==
{{trans|Nim}}
{{libheader|libxml2}}
Although Wren has nothird XMLparty support whateverfor XML, eitherit built-indoes ornot (AFAIK)support viavalidation thirdagainst an XSD partiesschema. We therefore use an
embedded program so we can ask the C host to communicate with Libxml2 for us.
<langsyntaxhighlight ecmascriptlang="wren">/* xml_validationXML_validation.wren */
 
class Args {
Line 1,007 ⟶ 1,210:
System.print("'%(xmlFilename)' fails to validate.")
}
validCtxt.freeValidCtxt()</langsyntaxhighlight>
<br>
We now embed this in the following C program, compile and run it.
<langsyntaxhighlight lang="c">/* built with: gcc xml_validationXML_validation.c -o xml_validationXML_validation -I/usr/include/libxml2 -lxml2 -lwren -lm */
 
#include <stdio.h>
Line 1,152 ⟶ 1,355:
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "xml_validationXML_validation.wren";
char *script = readFile(fileName);
WrenInterpretResult result = wrenInterpret(vm, module, script);
Line 1,168 ⟶ 1,371:
free(script);
return 0;
}</langsyntaxhighlight>
 
{{out}}
Using command <code>./xml_validationXML_validation shiporder.xml shiporder.xsd</code>:
<pre>'shiporder.xml' validates.</pre>
Using a modified file “shiporder1.xml” where tag “orderperson” has been replaced by “orderperson1”:
2,123

edits