### Install xmlschema Library Source: https://github.com/sissaschool/xmlschema/blob/master/doc/intro.md Install the xmlschema library using pip. This library requires the 'elementpath' package. ```default pip install xmlschema ``` -------------------------------- ### XML Schema Export Transformation Example Source: https://github.com/sissaschool/xmlschema/blob/master/doc/usage.md Illustrates how `schemaLocation` attributes in XSD imports are transformed from remote URLs to local paths during the export process. ```xml ``` ```xml ``` -------------------------------- ### Convert XML to Dictionary with xmlschema Source: https://github.com/sissaschool/xmlschema/blob/master/tests/test_cases/issues/issue_022/README.md Use the `to_dict` method to convert XML strings to Python dictionaries. This example shows inconsistent sequence handling in older versions. ```python import xmlschema xsd_schema = xmlschema.XMLSchema(xsd_string) xml_data_1 = xsd_schema.to_dict(xml_string_1) xml_data_2 = xsd_schema.to_dict(xml_string_2) print(xml_data_1) {'bar': {'@name': 'bar_1', 'subject_name': 'Bar #1'}} print(xml_data_2) {'bar': [{'@name': 'bar_1', 'subject_name': 'Bar #1'}, {'@name': 'bar_2', 'subject_name': 'Bar #2'}]} ``` -------------------------------- ### Initialize an XML Schema instance Source: https://github.com/sissaschool/xmlschema/blob/master/README.rst Create a schema object by providing the path to an XSD file. ```pycon >>> import xmlschema >>> my_schema = xmlschema.XMLSchema('tests/test_cases/examples/vehicles/vehicles.xsd') ``` -------------------------------- ### Run W3C XML Schema 1.1 test suite Source: https://github.com/sissaschool/xmlschema/blob/master/doc/testing.md Clone the W3C test repository and execute the test suite using the provided script. ```text git clone https://github.com/w3c/xsdtests.git python xmlschema/xmlschema/tests/test_w3c_suite.py ``` -------------------------------- ### Create XML Schema Instance from File Path Source: https://github.com/sissaschool/xmlschema/blob/master/doc/usage.md Instantiate an XML schema by providing the path to the XSD file. Ensure the file exists at the specified location. ```python import xmlschema schema = xmlschema.XMLSchema("path/to/your/schema.xsd") ``` -------------------------------- ### Test XML Schemas with test_files.py Source: https://github.com/sissaschool/xmlschema/blob/master/doc/testing.md Execute the test_files.py script from the tests/ directory to test XML schema files. Pass the paths to the .xsd files as arguments. The script will add tests for each schema and report the results. ```bash $ cd tests/ $ python test_files.py test_cases/examples/vehicles/*.xsd Add test 'TestSchema001' for file 'test_cases/examples/vehicles/bikes.xsd' ... Add test 'TestSchema002' for file 'test_cases/examples/vehicles/cars.xsd' ... Add test 'TestSchema003' for file 'test_cases/examples/vehicles/types.xsd' ... Add test 'TestSchema004' for file 'test_cases/examples/vehicles/vehicles-max.xsd' ... Add test 'TestSchema005' for file 'test_cases/examples/vehicles/vehicles.xsd' ... ..... ---------------------------------------------------------------------- Ran 5 tests in 0.147s OK ``` -------------------------------- ### Create XML Schema Instance from Multiple Sources Source: https://github.com/sissaschool/xmlschema/blob/master/doc/usage.md Provide a list of schema sources to the constructor, which is particularly useful when sources lack associated locations. The schemas will be built in the order provided. ```python import xmlschema schema = xmlschema.XMLSchema(["schema1.xsd", "schema2.xsd"]) ``` -------------------------------- ### Create XML Schema Instance with Delayed Build Source: https://github.com/sissaschool/xmlschema/blob/master/doc/usage.md Use the `build` option to delay schema building until all resources are loaded. This is useful for complex schemas or when managing dependencies manually. ```python import xmlschema schema = xmlschema.XMLSchema("schema.xsd", build=False) schema.build_schema() ``` -------------------------------- ### Create XML Schema Instance with Base URL for Includes Source: https://github.com/sissaschool/xmlschema/blob/master/doc/usage.md When a schema includes other local subschemas, provide a `base_url` to specify the reference directory path for resolving these includes and imports. ```python import xmlschema schema = xmlschema.XMLSchema("schema.xsd", base_url="http://example.com/schemas/") ``` -------------------------------- ### Run tests with custom testfile index Source: https://github.com/sissaschool/xmlschema/blob/master/doc/testing.md Execute test scripts while providing a path to a custom testfile index. ```text python xmlschema/tests/test_all.py ../extra-schemas/testfiles ``` -------------------------------- ### Create XMLSchema Instances Source: https://context7.com/sissaschool/xmlschema/llms.txt Instantiate XMLSchema objects from XSD files, URLs, or string definitions. Use XMLSchema11 for XSD 1.1 schemas. Specify base_url for relative imports and locations for imported namespaces. ```python import xmlschema # Create schema from a file path schema = xmlschema.XMLSchema('path/to/schema.xsd') # Create schema from a URL schema = xmlschema.XMLSchema('https://example.com/schema.xsd') # Create schema from a string schema = xmlschema.XMLSchema(''' ''') # Create XSD 1.1 schema (use XMLSchema11 class) schema_11 = xmlschema.XMLSchema11('path/to/xsd11-schema.xsd') # Create schema with base_url for resolving relative imports schema = xmlschema.XMLSchema( schema_string, base_url='/path/to/schema/directory/' ) # Create schema with custom locations for imported namespaces schema = xmlschema.XMLSchema( 'main.xsd', locations={'http://example.com/ns': 'local/path/to/imported.xsd'} ) ``` -------------------------------- ### Create XML Schema Instance from File-like Object or String Source: https://github.com/sissaschool/xmlschema/blob/master/doc/usage.md Instantiate an XML schema using a file-like object or a string containing the schema definition. Note that this may not work for schemas with local includes. ```python import xmlschema with open("path/to/your/schema.xsd", "rb") as f: schema = xmlschema.XMLSchema(f) schema_string = "" schema = xmlschema.XMLSchema(schema_string) ``` -------------------------------- ### Convert XML and JSON via CLI Source: https://context7.com/sissaschool/xmlschema/llms.txt Use these commands to transform XML to JSON or vice versa, with options for schema validation, output directories, and custom converters. ```bash xmlschema-xml2json document.xml --schema schema.xsd xmlschema-xml2json *.xml --schema schema.xsd -o output_dir/ ``` ```bash xmlschema-xml2json document.xml --schema schema.xsd --indent 2 ``` ```bash xmlschema-xml2json document.xml --schema schema.xsd --converter badgerfish ``` ```bash xmlschema-json2xml data.json --schema schema.xsd xmlschema-json2xml *.json --schema schema.xsd -o xml_output/ ``` ```bash xmlschema-validate doc.xml -L "http://example.com/ns" "local/schema.xsd" ``` -------------------------------- ### Exporting and Downloading XML Schemas Source: https://context7.com/sissaschool/xmlschema/llms.txt Manage schemas by exporting them to local directories for offline use or downloading remote schemas. This includes building schemas from URLs and using location maps for offline access. ```python import xmlschema # Build schema from remote URL schema = xmlschema.XMLSchema("https://www.example.org/schemas/main.xsd") # Export schema and dependencies to local directory schema.export(target='local_schemas/', save_remote=True) # Use exported schema offline offline_schema = xmlschema.XMLSchema("local_schemas/main.xsd") # Alternative: download schemas directly from xmlschema import download_schemas # Download with location mapping location_map = download_schemas( "https://www.example.org/schemas/main.xsd", target='downloaded_schemas/' ) # Build schema using location map schema = xmlschema.XMLSchema( "https://www.example.org/schemas/main.xsd", locations=location_map ) # Export specific components schema.export( target='export_dir/', save_remote=True ) ``` -------------------------------- ### Manage XML with XMLResource Source: https://context7.com/sissaschool/xmlschema/llms.txt Use XMLResource for advanced loading, lazy processing, and security configurations when handling XML files. ```python import xmlschema from xmlschema import XMLResource # Create XMLResource from file resource = XMLResource('document.xml') # Access root element print(resource.root.tag) # Get namespace declarations namespaces = resource.get_namespaces() # Create lazy resource for large files resource = XMLResource('large_document.xml', lazy=True) # Create resource with defuse protection resource = XMLResource('document.xml', defuse='always') # Create resource with timeout for remote URLs resource = XMLResource('https://example.com/data.xml', timeout=30) # Validate using XMLResource schema = xmlschema.XMLSchema('schema.xsd') schema.validate(resource) # Decode using XMLResource data = schema.decode(resource) # Fetch schema locations from XML document schema_url, locations = xmlschema.fetch_schema_locations('document.xml') # Fetch namespaces from XML document namespaces = xmlschema.fetch_namespaces('document.xml') ``` -------------------------------- ### Access component naming properties Source: https://github.com/sissaschool/xmlschema/blob/master/doc/components.md Retrieve different name formats for components that have names. ```python component.name component.qualified_name ``` -------------------------------- ### Access component metadata Source: https://github.com/sissaschool/xmlschema/blob/master/doc/components.md Retrieve the container schema and reference node for a component. ```python component.schema component.ref ``` -------------------------------- ### Download Schemas Directly Source: https://github.com/sissaschool/xmlschema/blob/master/doc/usage.md Download XSD resources directly to a specified target directory. This function saves the schemas and returns a location map for use as a `uri_mapper`. ```python from xmlschema import download_schemas download_schemas("https://www.omg.org/spec/ReqIF/20110401/reqif.xsd", target='my_schemas') ``` -------------------------------- ### Configure Security and Processing Limits Source: https://context7.com/sissaschool/xmlschema/llms.txt Set defuse policies and resource access controls to prevent malicious XML processing. Adjust global limits to manage memory and recursion depth. ```python import xmlschema # Create schema with defuse protection # 'remote': defuse only remote resources (default) # 'always': defuse all XML data # 'never': no defuse protection # 'nonlocal': defuse all except local files schema = xmlschema.XMLSchema('schema.xsd', defuse='always') # Access control on resources # 'all': allow all URLs (default) # 'remote': only remote URLs # 'local': only local files # 'sandbox': only files under schema directory # 'none': no URL access schema = xmlschema.XMLSchema('schema.xsd', allow='sandbox') # Secure configuration for public services schema = xmlschema.XMLSchema( 'schema.xsd', defuse='always', allow='none' ) # Configure processing limits import xmlschema.limits # Maximum XML depth (default: 1000) xmlschema.limits.MAX_XML_DEPTH = 500 # Maximum elements in non-lazy resources (default: 1,000,000) xmlschema.limits.MAX_XML_ELEMENTS = 100000 # Maximum schema sources per global map (default: 1000) xmlschema.limits.MAX_SCHEMA_SOURCES = 500 ``` -------------------------------- ### Access components with XPath Source: https://github.com/sissaschool/xmlschema/blob/master/doc/components.md Retrieve XSD elements and attributes using XPath expressions. ```python schema.find('xs:element[@name="item"]') schema.findall('.//xs:element') ``` -------------------------------- ### Access global components via dictionary Source: https://github.com/sissaschool/xmlschema/blob/master/doc/components.md Access specific global components using dictionary-style lookups on the schema object. ```python schema.elements['item'] schema.types['itemType'] ``` -------------------------------- ### Run XPath tests via unittest Source: https://github.com/sissaschool/xmlschema/blob/master/doc/testing.md Execute specific XPath tests using the Python unittest module. ```bash $ python -m unittest -k tests.test_xpath .......... ---------------------------------------------------------------------- Ran 10 tests in 0.133s OK ``` -------------------------------- ### Iterate schema components Source: https://github.com/sissaschool/xmlschema/blob/master/doc/components.md Use iter_components() to traverse all components or iter_globals() for global components only. ```python for component in schema.iter_components(): print(component) ``` ```python for component in schema.iter_globals(): print(component) ``` -------------------------------- ### Access full component classes Source: https://github.com/sissaschool/xmlschema/blob/master/doc/components.md Import specific component classes from the validators subpackage. ```python from xmlschema.validators import XsdElement, XsdAttribute ``` -------------------------------- ### Decode and encode XSD files Source: https://github.com/sissaschool/xmlschema/blob/master/doc/usage.md Apply decode and encode methods directly on XSD files or sources. ```python from xmlschema import XMLSchema10 data = XMLSchema10.meta_schema.decode('my_schema.xsd') xml_content = XMLSchema10.meta_schema.encode(data) ``` -------------------------------- ### Define test files index Source: https://github.com/sissaschool/xmlschema/blob/master/doc/testing.md Format for the testfiles index file used to define custom test cases, including optional error counts. ```text # XHTML XHTML/xhtml11-mod.xsd XHTML/xhtml-datatypes-1.xsd # Quantum Espresso qe/qes.xsd qe/qes_neb.xsd qe/qes_with_choice_no_nesting.xsd qe/silicon.xml qe/silicon-1_error.xml --errors 1 qe/silicon-3_errors.xml --errors=3 qe/SrTiO_3.xml qe/SrTiO_3-2_errors.xml --errors 2 ``` -------------------------------- ### Accessing Schema Components with Python Source: https://context7.com/sissaschool/xmlschema/llms.txt Inspect elements, types, and attributes defined in an XSD schema. Use XPath for searching and iterate through all or global components. Access specific element properties like type and content. ```python import xmlschema schema = xmlschema.XMLSchema('collection.xsd') # Access global elements for name, element in schema.elements.items(): print(f"Element: {name}, Type: {element.type.name}") # Access global types for name, xsd_type in schema.types.items(): print(f"Type: {name}") # Access global attributes for name, attr in schema.attributes.items(): print(f"Attribute: {name}") # Find elements using XPath elements = schema.findall('.//object') for elem in elements: print(f"Found: {elem.name}") # Get specific element by name element = schema.elements.get('collection') print(f"Element type: {element.type}") print(f"Is complex: {element.type.is_complex()()}) # Iterate all components (global and local) for component in schema.iter_components(): print(f"Component: {component}") # Iterate only global components for component in schema.iter_globals(): print(f"Global: {component.name}") # Access element's type properties element = schema.elements['collection'] if element.type.has_complex_content(): for child in element.type.content.iter_elements(): print(f"Child element: {child.name}") ``` -------------------------------- ### Configuration Options for XMLSchema Decoding Source: https://github.com/sissaschool/xmlschema/blob/master/doc/usage.md Overview of the configuration parameters used to control how XSD data is decoded into Python types and how validation is performed. ```APIDOC ## Configuration Options ### Description These options control the behavior of the XMLSchema decoder, including datatype mapping, handling of missing values, element processing, and custom validation hooks. ### Parameters #### Decoding Atomic Datatypes - **decimal_type** (type) - Optional - Decoding type for xs:decimal (default: decimal.Decimal). - **datetime_types** (bool) - Optional - If True, decodes datetime/duration to XSD atomic types instead of strings. - **binary_types** (bool) - Optional - If True, decodes xs:hexBinary/xs:base64Binary to XSD atomic types. #### Filling Missing Values - **filler** (function) - Optional - Callback to fill undecodable data. - **fill_missing** (bool) - Optional - If True, fills missing attributes. #### Element Decoding - **value_hook** (function) - Optional - Called with decoded atomic value and XSD type. - **keep_empty** (bool) - Optional - If True, decodes valid empty elements as empty strings. - **element_hook** (function) - Optional - Called with ElementData before converter decode. #### Wildcard Decoding - **keep_unknown** (bool) - Optional - If True, keeps unknown tags as xs:anyType. - **process_skipped** (bool) - Optional - Processes XML data matching wildcard with processContents='skip'. #### Depth Control - **max_depth** (int) - Optional - Maximum level of decoding. - **depth_filler** (function) - Optional - Callback for replacing data over max_depth. #### Validation - **extra_validator** (function) - Optional - Function for non-standard validations. - **validation_hook** (function) - Optional - Function for stopping or changing validation/decoding at element level. ``` -------------------------------- ### Export Schema and Dependencies Locally Source: https://github.com/sissaschool/xmlschema/blob/master/doc/usage.md Export a remote XSD schema and its dependencies to a local directory for offline use. This command transforms remote URLs into local ones within the exported files. ```python import xmlschema schema = xmlschema.XMLSchema("https://www.omg.org/spec/ReqIF/20110401/reqif.xsd") schema.export(target='my_schemas', save_remote=True) schema = xmlschema.XMLSchema("my_schemas/reqif.xsd") # works without internet ``` -------------------------------- ### XML Schema Validation using CLI Source: https://context7.com/sissaschool/xmlschema/llms.txt Perform batch validation of XML files against XSD schemas using the command-line interface. Supports specifying schema version, verbose error output, and lazy mode for large files. ```bash # Validate XML files against a schema xmlschema-validate document.xml --schema schema.xsd xmlschema-validate *.xml --schema schema.xsd --version 1.1 # Validate with verbose error output xmlschema-validate document.xml --schema schema.xsd -v # Validate with lazy mode for large files xmlschema-validate large.xml --schema schema.xsd --lazy ``` -------------------------------- ### Validate XSD sources using built-in meta-schemas Source: https://github.com/sissaschool/xmlschema/blob/master/doc/usage.md Use the built-in meta-schema instances to validate XSD sources directly without constructing a new schema object. ```python from xmlschema import XMLSchema10, XMLSchema11 XMLSchema10.meta_schema.validate('my_schema.xsd') XMLSchema11.meta_schema.validate('my_schema_11.xsd') ``` -------------------------------- ### Validate and decode XML with lxml and namespaces Source: https://github.com/sissaschool/xmlschema/blob/master/doc/usage.md Validate an XML file using its path and then decode it into a dictionary. This method leverages the lxml library for better namespace handling, suitable for complex XML structures. ```python >>> xs.is_valid('tests/test_cases/examples/vehicles/vehicles-ns-mix.xml') True >>> pprint(xs.to_dict('tests/test_cases/examples/vehicles/vehicles-ns-mix.xml')) {'@xmlns': 'http://example.com/vehicles', '@xmlns:vh': 'http://xmlschema.test/other-ns', '@xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance', '@xsi:schemaLocation': 'http://example.com/vehicles vehicles.xsd', 'vh:bikes': {'@xmlns': '', '@xmlns:vh': 'http://example.com/vehicles', 'vh:bike': [{'@make': 'Harley-Davidson', '@model': 'WL'}, {'@make': 'Yamaha', '@model': 'XS650'}]}, 'vh:cars': {'@xmlns': '', '@xmlns:vh': 'http://example.com/vehicles', 'vh:car': [{'@make': 'Porsche', '@model': '911'}, {'@make': 'Porsche', '@model': '911'}]}} ``` -------------------------------- ### Add Schema to Existing Instance Source: https://github.com/sissaschool/xmlschema/blob/master/doc/usage.md Use the `add_schema` method to incorporate additional schemas into an existing `XMLSchemaBase` instance. This allows for incremental schema loading and management. ```python import xmlschema schema = xmlschema.XMLSchema("schema1.xsd") schema.add_schema("schema2.xsd") ``` -------------------------------- ### Handle Schema-bound Documents with XmlDocument Source: https://context7.com/sissaschool/xmlschema/llms.txt Use the XmlDocument class for integrated validation, decoding, and file operations on schema-bound XML. ```python import xmlschema from xmlschema import XmlDocument # Create validated document (strict mode by default) try: doc = XmlDocument('document.xml', schema='schema.xsd') except xmlschema.XMLSchemaValidationError as e: print(f"Invalid document: {e}") # Create document with lax validation doc = XmlDocument('document.xml', schema='schema.xsd', validation='lax') if doc.errors: for error in doc.errors: print(f"Warning: {error.reason}") # Create document with skip validation doc = XmlDocument('document.xml', schema='schema.xsd', validation='skip') # Access document properties root = doc.getroot() schema = doc.schema # Decode document to dictionary data = doc.decode() # Convert to JSON json_string = doc.to_json() # Write document to file doc.write('output.xml', encoding='utf-8', xml_declaration=True) ``` -------------------------------- ### Apply XML-to-JSON Converters Source: https://context7.com/sissaschool/xmlschema/llms.txt Utilize built-in converters like BadgerFish, Parker, or JsonML to change the structure of decoded XML data. ```python import xmlschema schema = xmlschema.XMLSchema('vehicles.xsd') # Default converter data = schema.decode('vehicles.xml') # {'vh:cars': {'vh:car': [{'@make': 'Porsche', '@model': '911'}]}} # BadgerFish converter (preserves all XML info) data = schema.decode('vehicles.xml', converter=xmlschema.BadgerFishConverter) # {'vh:cars': {'vh:car': [{'@make': {'$': 'Porsche'}, '@model': {'$': '911'}}]}} # Parker converter (simplest, loses attributes) data = schema.decode('vehicles.xml', converter=xmlschema.ParkerConverter) # {'cars': {'car': [None]}} # JsonML converter (array-based, lossless) data = schema.decode('vehicles.xml', converter=xmlschema.JsonMLConverter) # ['vh:cars', {'xmlns:vh': '...'}, ['vh:car', {'make': 'Porsche'}]] # Abdera converter data = schema.decode('vehicles.xml', converter=xmlschema.AbderaConverter) # GData converter data = schema.decode('vehicles.xml', converter=xmlschema.GDataConverter) # Columnar converter (attributes as child elements) data = schema.decode('vehicles.xml', converter=xmlschema.ColumnarConverter) # UnorderedConverter (for unordered content) data = schema.decode('vehicles.xml', converter=xmlschema.UnorderedConverter) # Create schema with default converter schema = xmlschema.XMLSchema('vehicles.xsd', converter=xmlschema.BadgerFishConverter) ``` -------------------------------- ### Decode ElementTree data with namespaces Source: https://github.com/sissaschool/xmlschema/blob/master/doc/usage.md Use ElementTree to load XML data and provide a namespace map for correct URI-to-prefix conversion during decoding. This is useful when ElementTree's default namespace handling is insufficient. ```python >>> namespaces = {'xsi': 'http://www.w3.org/2001/XMLSchema-instance', 'vh': 'http://example.com/vehicles'} >>> pprint(xs.to_dict(xt, namespaces=namespaces)) {'@xmlns:vh': 'http://example.com/vehicles', '@xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance', '@xsi:schemaLocation': 'http://example.com/vehicles vehicles.xsd', 'vh:bikes': {'vh:bike': [{'@make': 'Harley-Davidson', '@model': 'WL'}, {'@make': 'Yamaha', '@model': 'XS650'}]}, 'vh:cars': {'vh:car': [{'@make': 'Porsche', '@model': '911'}, {'@make': 'Porsche', '@model': '911'}]}} ``` -------------------------------- ### Decode XML using package API with namespaces Source: https://github.com/sissaschool/xmlschema/blob/master/doc/usage.md Decode an XML file directly using the package's to_dict function, which also supports namespace mapping. This provides a convenient way to process XML data without explicitly creating an XMLResource instance. ```python >>> pprint(xmlschema.to_dict('tests/test_cases/examples/vehicles/vehicles-ns-mix.xml')) {'@xmlns': 'http://example.com/vehicles', '@xmlns:vh': 'http://xmlschema.test/other-ns', '@xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance', '@xsi:schemaLocation': 'http://example.com/vehicles vehicles.xsd', 'vh:bikes': {'@xmlns': '', '@xmlns:vh': 'http://example.com/vehicles', 'vh:bike': [{'@make': 'Harley-Davidson', '@model': 'WL'}, {'@make': 'Yamaha', '@model': 'XS650'}]}, 'vh:cars': {'@xmlns': '', '@xmlns:vh': 'http://example.com/vehicles', 'vh:car': [{'@make': 'Porsche', '@model': '911'}, {'@make': 'Porsche', '@model': '911'}]}} ``` -------------------------------- ### Parse and Validate WSDL 1.1 Document Source: https://github.com/sissaschool/xmlschema/blob/master/doc/extras.md Use Wsdl11Document for parsing and validating WSDL 1.1 documents, which can aggregate multiple WSDL/XSD files. ```python from xmlschema.extras.wsdl import Wsdl11Document wsdl_doc = Wsdl11Document('http://example.com/service?wsdl') # Use wsdl_doc for validation and parsing ``` -------------------------------- ### Perform Module-level XML Encoding Source: https://context7.com/sissaschool/xmlschema/llms.txt Encode data to ElementTree objects with options for validation, namespaces, and string conversion. ```python # Module-level encoding element = xmlschema.to_etree( data, schema='collection.xsd', path='collection' ) # Encode with validation element, errors = schema.encode(data, validation='lax') # Encode with namespaces element = schema.encode( data, namespaces={'col': 'http://example.com/ns/collection'} ) # Convert Element to string xml_string = xmlschema.etree_tostring(element, namespaces={'col': 'http://example.com/ns/collection'}) ``` -------------------------------- ### Validate XML with validate() Source: https://github.com/sissaschool/xmlschema/blob/master/doc/usage.md Validate an XML document against the schema. This method raises an exception if the document does not conform to the schema, providing detailed error information. ```python import xmlschema schema = xmlschema.XMLSchema("schema.xsd") try: schema.validate("document.xml") except xmlschema.XMLSchemaValidationError as e: print(e) ``` -------------------------------- ### Decode XML with DataBindingConverter Source: https://context7.com/sissaschool/xmlschema/llms.txt Use this snippet to decode an XML file into a Python object using a custom data binding converter. ```python data = schema.decode('collection.xml', converter=DataBindingConverter) ``` -------------------------------- ### Validate XML documents Source: https://github.com/sissaschool/xmlschema/blob/master/README.rst Check if an XML file conforms to the schema or raise an exception if validation fails. ```pycon >>> my_schema.is_valid('tests/test_cases/examples/vehicles/vehicles.xml') True >>> my_schema.is_valid('tests/test_cases/examples/vehicles/vehicles-1_error.xml') False >>> my_schema.validate('tests/test_cases/examples/vehicles/vehicles-1_error.xml') ``` -------------------------------- ### Check for simple types Source: https://github.com/sissaschool/xmlschema/blob/master/doc/components.md Verify if a type is a simpleType. ```python type.is_simple() ``` -------------------------------- ### Use DataElement for Data Binding Source: https://context7.com/sissaschool/xmlschema/llms.txt Utilize DataElement to create schema-bound objects that provide an ElementTree-like interface for easier data access and manipulation. ```python import xmlschema from xmlschema import DataElement, DataElementConverter schema = xmlschema.XMLSchema('collection.xsd') # Decode to DataElement tree data_element = schema.decode( 'collection.xml', converter=DataElementConverter ) # Access like ElementTree print(data_element.tag) print(data_element.text) print(data_element.attrib) # Iterate children for child in data_element: print(f"Child: {child.tag} = {child.value}") # Access typed value print(f"Value: {data_element.value}") print(f"Type: {data_element.xsd_type}") # Create DataElement programmatically element = DataElement( tag='object', value={'position': 1, 'title': 'Test'}, xsd_element=schema.elements['object'] ) # Encode DataElement back to XML xml_element = schema.encode(data_element) ``` -------------------------------- ### Controlling Validation Strictness Source: https://context7.com/sissaschool/xmlschema/llms.txt Manage validation behavior using 'strict', 'lax', and 'skip' modes. 'Strict' raises an error on the first validation failure, 'lax' collects errors and replaces invalid data with None, and 'skip' bypasses validation entirely. ```python import xmlschema schema = xmlschema.XMLSchema('schema.xsd') # Strict mode (default): raises on first error try: data = schema.decode('document.xml', validation='strict') except xmlschema.XMLSchemaValidationError as e: print(f"Validation failed: {e.reason}") # Lax mode: collects errors, replaces invalid with None data, errors = schema.decode('document.xml', validation='lax') print(f"Decoded with {len(errors)} errors") for error in errors: print(f" - {error.reason}") # Skip mode: no validation, invalid data kept as text data = schema.decode('document.xml', validation='skip') # Build schema with validation mode schema = xmlschema.XMLSchema('schema.xsd', validation='lax') # Validate with extra custom validator def custom_validator(element, xsd_element): if element.get('status') == 'draft': raise xmlschema.XMLSchemaValidationError( xsd_element, element, "Draft documents not allowed" ) errors = list(schema.iter_errors( 'document.xml', extra_validator=custom_validator )) ``` -------------------------------- ### Handle Validation and Parsing Errors Source: https://context7.com/sissaschool/xmlschema/llms.txt Implement robust error handling for schema validation and parsing, including custom hooks and error collection. ```python import xmlschema schema = xmlschema.XMLSchema('schema.xsd') # Catch validation errors try: schema.validate('document.xml') except xmlschema.XMLSchemaValidationError as e: print(f"Reason: {e.reason}") print(f"Schema element: {e.validator}") print(f"XML element: {e.elem.tag}") print(f"Path: {e.path}") print(f"Line: {e.sourceline}") # Catch schema parsing errors try: schema = xmlschema.XMLSchema('invalid_schema.xsd') except xmlschema.XMLSchemaParseError as e: print(f"Schema error: {e}") # Collect all errors errors = list(schema.iter_errors('document.xml')) for error in errors: print(f"[{error.path}] {error.reason}") # Custom error handling during decode def handle_errors(data, errors): for error in errors: log_error(error) return data data, errors = schema.decode('document.xml', validation='lax') result = handle_errors(data, errors) # Stop validation on custom condition class StopOnCritical(Exception): pass def validation_hook(element, xsd_element): if element.get('critical') == 'true': raise xmlschema.XMLSchemaStopValidation("Critical element found") return False try: schema.validate('document.xml', validation_hook=validation_hook) except xmlschema.XMLSchemaStopValidation as e: print(f"Validation stopped: {e}") ``` -------------------------------- ### Decode and encode data Source: https://github.com/sissaschool/xmlschema/blob/master/doc/components.md Use component methods to convert data between XML and Python objects. ```python component.decode(xml_data) component.encode(python_data) ``` -------------------------------- ### Access complex type attributes and content Source: https://github.com/sissaschool/xmlschema/blob/master/doc/components.md Access attributes and content models for complex types. ```python complex_type.attributes complex_type.content ``` -------------------------------- ### Serialize and Deserialize JSON Source: https://context7.com/sissaschool/xmlschema/llms.txt Convert XML documents to JSON strings or files and vice versa, supporting custom JSON options and validation modes. ```python import xmlschema schema = xmlschema.XMLSchema('collection.xsd') # Convert XML to JSON string json_string = xmlschema.to_json('collection.xml', schema=schema) print(json_string) # Convert XML to JSON file with open('output.json', 'w') as fp: xmlschema.to_json('collection.xml', fp=fp, schema=schema) # Convert with custom JSON options (pretty print) json_string = xmlschema.to_json( 'collection.xml', schema=schema, json_options={'indent': 2} ) # Convert JSON back to XML Element json_data = '{"@id": "test", "position": 1, "title": "Test"}' element = xmlschema.from_json( json_data, schema=schema, path='object' # XPath to target element ) # Convert JSON file to XML with open('data.json') as fp: element = xmlschema.from_json(fp, schema=schema, path='collection') # Lax conversion with error collection element, errors = xmlschema.from_json( json_data, schema=schema, path='object', validation='lax' ) ``` -------------------------------- ### Decode XML to Python dictionary Source: https://github.com/sissaschool/xmlschema/blob/master/README.rst Convert an XML document into a nested dictionary structure based on schema data types. ```pycon >>> import xmlschema >>> from pprint import pprint >>> xs = xmlschema.XMLSchema('tests/test_cases/examples/collection/collection.xsd') >>> pprint(xs.to_dict('tests/test_cases/examples/collection/collection.xml')) ``` -------------------------------- ### Validate XML with is_valid() Source: https://github.com/sissaschool/xmlschema/blob/master/doc/usage.md Check if an XML document is valid against the loaded schema. Returns `True` for valid documents and `False` otherwise. No exceptions are raised for invalid documents. ```python import xmlschema schema = xmlschema.XMLSchema("schema.xsd") is_valid = schema.is_valid("document.xml") ``` -------------------------------- ### Validate XML Documents with xmlschema Source: https://context7.com/sissaschool/xmlschema/llms.txt Validate XML documents against a schema using is_valid(), validate(), or iter_errors(). Module-level functions are also available for direct validation. ```python import xmlschema schema = xmlschema.XMLSchema('collection.xsd') # Check if document is valid (returns True/False) is_valid = schema.is_valid('collection.xml') print(f"Document valid: {is_valid}") # Document valid: True # Validate and raise exception on error try: schema.validate('invalid.xml') except xmlschema.XMLSchemaValidationError as e: print(f"Validation error: {e.reason}") # Iterate over all validation errors errors = list(schema.iter_errors('document.xml')) for error in errors: print(f"Error at line {error.sourceline}: {error.reason}") # Module-level validation (auto-discovers schema from XML) xmlschema.validate('document.xml') # Module-level is_valid check result = xmlschema.is_valid('document.xml', schema='schema.xsd') # Validate with custom namespaces schema.validate( 'document.xml', namespaces={'ns': 'http://example.com/namespace'} ) ``` -------------------------------- ### Define Custom Jinja2 Test Source: https://github.com/sissaschool/xmlschema/blob/master/doc/extras.md Add custom tests to Jinja2 for schema code generation by using the @test_method decorator. ```python from xmlschema.extras.codegen import AbstractGenerator class MyGenerator(AbstractGenerator): @test_method def my_custom_test(self, obj): # ... implementation ... pass ``` -------------------------------- ### Decode XML to Python Dictionaries Source: https://context7.com/sissaschool/xmlschema/llms.txt Convert XML documents into nested Python dictionaries, applying type conversions based on XSD types. Supports various decoding options like XPath filtering, lax/skip validation, and custom decimal/datetime types. ```python import xmlschema from pprint import pprint schema = xmlschema.XMLSchema('collection.xsd') # Decode XML to dictionary data = schema.decode('collection.xml') pprint(data) # Output: # {'object': [{'@id': 'b0836217462', # '@available': True, # 'position': 1, # 'title': 'The Umbrellas', # 'year': '1886', # 'author': {'@id': 'PAR', 'name': 'Pierre-Auguste Renoir'}, # 'estimation': Decimal('10000.00')}]} # Decode using to_dict() alias data = schema.to_dict('collection.xml') # Module-level decoding data = xmlschema.to_dict('collection.xml', schema='collection.xsd') # Decode with XPath to get specific elements data = schema.decode('collection.xml', path='/collection/object') # Decode with lax validation (returns data + errors tuple) data, errors = schema.decode('collection.xml', validation='lax') # Decode with skip validation (no validation errors) data = schema.decode('collection.xml', validation='skip') # Control decimal type decoding data = schema.decode('collection.xml', decimal_type=float) # Decode datetime types to Python objects data = schema.decode('collection.xml', datetime_types=True) ``` -------------------------------- ### Access XSD type of an element Source: https://github.com/sissaschool/xmlschema/blob/master/doc/components.md Access the XSD type associated with an element or attribute declaration. ```python element.type ``` -------------------------------- ### Lazy Validation for Large XML Files Source: https://context7.com/sissaschool/xmlschema/llms.txt Process large XML files efficiently using lazy mode to reduce memory consumption. This mode allows for iterative processing and decoding, suitable for files that may not fit entirely into memory. ```python import xmlschema schema = xmlschema.XMLSchema('schema.xsd') # Lazy validation (processes XML iteratively) is_valid = schema.is_valid('large_file.xml', lazy=True) # Lazy validation with specific depth is_valid = schema.is_valid('large_file.xml', lazy=3) # Lazy decoding for item in schema.iter_decode('large_file.xml', lazy=True): if isinstance(item, xmlschema.XMLSchemaValidationError): print(f"Error: {item.reason}") else: print(f"Decoded: {item}") # Module-level lazy iteration for result in xmlschema.iter_decode('large_file.xml', schema='schema.xsd', lazy=True): if not isinstance(result, xmlschema.XMLSchemaValidationError): process(result) # Lazy JSON conversion with open('output.json', 'w') as fp: errors = xmlschema.to_json( 'large_file.xml', fp=fp, schema=schema, lazy=True, validation='lax' ) ``` -------------------------------- ### Define Custom Jinja2 Filter Source: https://github.com/sissaschool/xmlschema/blob/master/doc/extras.md Add custom filters to Jinja2 for schema code generation by using the @filter_method decorator. ```python from xmlschema.extras.codegen import AbstractGenerator class MyGenerator(AbstractGenerator): @filter_method def my_custom_filter(self, obj): # ... implementation ... pass ``` -------------------------------- ### Encode Python Data to XML Source: https://context7.com/sissaschool/xmlschema/llms.txt Convert Python dictionaries into XML ElementTree elements based on a defined XML Schema. This allows for generating XML documents programmatically. ```python import xmlschema from xml.etree import ElementTree schema = xmlschema.XMLSchema('collection.xsd') # Python data matching the schema data = { 'object': [{ '@id': 'item001', '@available': True, 'position': 1, 'title': 'Starry Night', 'year': '1889', 'author': { '@id': 'VVG', 'name': 'Vincent van Gogh', 'born': '1853-03-30', 'dead': '1890-07-29', 'qualification': 'painter' } }] } # Encode to ElementTree Element element = schema.encode(data) print(ElementTree.tostring(element, encoding='unicode')) ``` -------------------------------- ### Validate XML at Module Level Source: https://github.com/sissaschool/xmlschema/blob/master/doc/usage.md Validate an XML document using the module-level `validate` function. This is useful for one-off validations when the schema location and namespace can be extracted directly from the XML document. ```python import xmlschema xmlschema.validate("document.xml", "schema.xsd") ``` -------------------------------- ### Encode Dictionary to XML Source: https://github.com/sissaschool/xmlschema/blob/master/doc/usage.md Encode a Python dictionary back into an XML document based on the schema. This process converts the dictionary structure and values into a valid XML format. ```python import xmlschema schema = xmlschema.XMLSchema("schema.xsd") xml_string = schema.encode(data) ``` -------------------------------- ### Decode Specific Part of XML using XPath Source: https://github.com/sissaschool/xmlschema/blob/master/doc/usage.md Decode only a specific portion of an XML document by providing an XPath expression to the `path` argument of the `decode` method. This allows for targeted data extraction. ```python import xmlschema schema = xmlschema.XMLSchema("schema.xsd") partial_data = schema.decode("document.xml", path="/root/element") ``` -------------------------------- ### Traverse model groups Source: https://github.com/sissaschool/xmlschema/blob/master/doc/components.md Use iter_elements() to traverse nested model groups in a complex type. ```python for element in complex_type.content.iter_elements(): print(element) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.