bhylu.com

Advertisements

XML XSD Data Types

XSD datatypes describe permitted lexical values and their value spaces. Choose a type according to the meaning of the field rather than its appearance.

How it works

Use decimal for an exact base-ten measurement, an integer subtype for a count and date for a calendar date. Some date forms allow a timezone and others do not require one; a business contract may need a stricter policy. Boolean accepts true, false, 1 and 0 in XSD, which is broader than this exchange’s earlier true/false application flag. list creates whitespace-separated sequences, and anyURI validates a lexical form without fetching a resource.

Run the code

Use Python 3 with lxml 6.1.1 in a separate virtual environment. The complete listing embeds its own XML and any schema or stylesheet; run python datatype-values.py. It does not need Apache or MySQL. The shared restrictive parse function rejects declarations for untrusted input. The trusted DTD/entity and streaming lessons explicitly explain their separate fixed-input boundaries.

Download the complete datatype-values.py source. Keep each lab in its own folder. Sources are served as text, not as public executable server scripts. Review the starting setup.

Example

datatype-values.py

from lxml import etree as E

class DenyExternal(E.Resolver):
    def resolve(self, url, public_id, context):
        raise ValueError("External resources are disabled")

def parse(text):
    if "<!DOCTYPE" in text.upper() or "<!ENTITY" in text.upper():
        raise ValueError("Declarations are disabled for untrusted XML")
    parser = E.XMLParser(resolve_entities=False, load_dtd=False,
                         no_network=True, huge_tree=False)
    parser.resolvers.add(DenyExternal())
    return E.fromstring(text.encode("utf-8"), parser)

source = "<sample count=\"12\" collected=\"2026-10-31\" tags=\"dry local\"/>"
root = parse(source)
schema_source = "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" ><xs:simpleType name=\"Tags\"><xs:list itemType=\"xs:token\"/></xs:simpleType><xs:element name=\"sample\"><xs:complexType><xs:attribute name=\"count\" type=\"xs:nonNegativeInteger\" use=\"required\"/><xs:attribute name=\"collected\" type=\"xs:date\" use=\"required\"/><xs:attribute name=\"tags\" type=\"Tags\"/></xs:complexType></xs:element></xs:schema>"
contract = E.XMLSchema(parse(schema_source))
print(contract.validate(root))


Expected result

True

The record combines a non-negative count, a real calendar date and a token list. Change the count to -1 or the month to 19 and validation fails. These checks are about the value contract, not whether the collection happened in real life.

Check the exact contract in the XML specification, XPath 1.0, the XSD 1.0 primer, lxml validation documentation and Saxon’s processor documentation.