[
"<product><sku>ABC-1234</sku><price>19.99</price></product>",
"<product><sku>abc-1234</sku><price>19.99</price></product>",
"<product><sku>XYZ-0001</sku><price>-5.00</price></product>",
"<product><sku>QRS-9999</sku><price>250.00</price></product>"
]
schema_languageXSD
from lxml import etree
_SCHEMA_XML = '<?xml version="1.0"?>\n<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">\n <xs:element name="product">\n <xs:complexType>\n <xs:sequence>\n <xs:element name="sku">\n <xs:simpleType>\n <xs:restriction base="xs:string">\n <xs:pattern value="[A-Z]{3}-[0-9]{4}"/>\n </xs:restriction>\n </xs:simpleType>\n </xs:element>\n <xs:element name="price">\n <xs:simpleType>\n <xs:restriction base="xs:decimal">\n <xs:minExclusive value="0"/>\n </xs:restriction>\n </xs:simpleType>\n </xs:element>\n </xs:sequence>\n </xs:complexType>\n </xs:element>\n</xs:schema>'
_SCHEMA = etree.XMLSchema(etree.fromstring(_SCHEMA_XML.encode("utf-8")))
def validate(payload_text: str) -> bool:
try:
doc = etree.fromstring(payload_text.encode("utf-8"))
except etree.XMLSyntaxError:
return False
return bool(_SCHEMA.validate(doc))
Validate a product-catalog XML document against a schema requiring a SKU matching a fixed alphanumeric pattern and a strictly positive price.
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="product">
<xs:complexType>
<xs:sequence>
<xs:element name="sku">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="[A-Z]{3}-[0-9]{4}"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="price">
<xs:simpleType>
<xs:restriction base="xs:decimal">
<xs:minExclusive value="0"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>