XML XSD Namespaces
targetNamespace assigns global declarations to a vocabulary. elementFormDefault controls whether local element declarations require qualification in instances.
How it works
The schema prefix, target vocabulary and instance prefixes have different jobs. A schema can use xs for its own instructions while declaring urn:bhylu:seed:v1 as the target namespace. Include combines compatible schema documents; import brings in declarations from another namespace. Production schema resolution should use approved local files or a fixed catalog. This single-file lab avoids network retrieval and makes the namespace boundary visible.
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 schema-namespaces.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 schema-namespaces.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
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 = "<packet xmlns=\"urn:bhylu:seed:v1\"><name>Marigold</name></packet>"
root = parse(source)
schema_source = "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" targetNamespace=\"urn:bhylu:seed:v1\" elementFormDefault=\"qualified\"><xs:element name=\"packet\"><xs:complexType><xs:sequence><xs:element name=\"name\" type=\"xs:string\"/></xs:sequence></xs:complexType></xs:element></xs:schema>"
contract = E.XMLSchema(parse(schema_source))
print(contract.validate(root))
Expected result
True
Both packet and name belong to the target namespace through the default declaration. Removing the instance namespace causes validation to fail. Changing prefixes alone does not change the expanded names.
Check the exact contract in the XML specification, XPath 1.0, the XSD 1.0 primer, lxml validation documentation and Saxon’s processor documentation.