Example: Tree: XSD based validation

<?xml version="1.0" encoding="utf-8"?>
<books>
<book id="1">
<title>The Royal Game</title>
<author>Stefan Zweig</author>
</book>
<book id="2">
<title>The Stoker</title>
<author>Franz Kafka</author>
</book>
</books>

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="books">
<xs:complexType>
<xs:sequence>
<xs:element name="book" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="title" type="string"/>
<xs:element name="author" type="string"/>
</xs:sequence>
<xs:attribute name="id" type="xs:integer"/>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

public static int main (string[] args) {
// The document:
Xml.Doc* doc = Xml.Parser.parse_file ("books.xml");
if (doc == null) {
print ("File 'books.xml' not found or permissions missing\n");
return 0;
}

// The schema:
Xml.SchemaParserCtxt schema_parser = new Xml.SchemaParserCtxt ("books.xsd");
Xml.Schema schema = schema_parser.parse ();
if (schema == null) {
print ("Invalid/missing schema\n");
return 0;
}

Xml.SchemaValidCtxt valctxt = new Xml.SchemaValidCtxt (schema);
if (valctxt == null) {
print ("Unable to create a validation context\n");
return 0;
}


// Validation:
int is_valid = valctxt.validate_doc (doc);
if (is_valid == 0) {
print ("valid\n");
} else {
print ("invalid\n");
}

return 0;
}

 valac --pkg libxml-2.0 schemas.vala

See:




2022 vala-language.org