XML Quiz
Use a short diagnostic review to explain what syntax, types and application rules each prove. A correct answer should identify the failing layer, not just say invalid.
Your brief
Predict whether a negative quantity parses, whether an absent packet matches a query and whether a duplicate id is rejected automatically. The worked listing demonstrates the first two results. Duplicate identity needs a declared DTD ID, an XSD identity constraint or an application check; an ordinary id attribute does not supply that rule. Then compare XPath 1.0 and XQuery 3.1 environments before choosing where a query can run.
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 quiz.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 quiz.py source. Keep each lab in its own folder. Sources are served as text, not as public executable server scripts. Review the starting setup.
Worked solution
Show the worked solution
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 id=\"p1\"><quantity>-2</quantity></packet>"
root = parse(source)
print("Parsed:", root.tag)
print("Missing:", len(root.xpath("missing")))
print("Business rule:", int(root.findtext("quantity")) >= 0)
Expected result
Parsed: packet Missing: 0 Business rule: False
The tree exists, the missing selection is empty and the separate business rule rejects the negative quantity. Those facts can all be true at once. Good diagnostics report which layer failed so the sender can make the right correction.
Extend and test
Explain why a static NodeList can still contain a detached node, why a string saying false is truthy in JavaScript, and why a returned XQuery element is not a saved update.
Check the exact contract in the XML specification, XPath 1.0, the XSD 1.0 primer, lxml validation documentation and Saxon’s processor documentation.