### Install xsdata with CLI requirements
Source: https://github.com/tefra/xsdata/blob/main/docs/codegen/intro.md
Install xsdata with the necessary CLI requirements.
```console
$ pip install xsdata[cli]
```
--------------------------------
### Verify xsdata installation
Source: https://github.com/tefra/xsdata/blob/main/docs/installation.md
Verify the installation by running the xsdata help command.
```console
$ xsdata --help
```
--------------------------------
### Basic Example
Source: https://github.com/tefra/xsdata/blob/main/docs/models/classes.md
A basic example demonstrating how to define a Book class and serialize it to XML.
```python
from dataclasses import dataclass
from xsdata.formats.dataclass.serializers import XmlSerializer
serializer = XmlSerializer()
serializer.config.indent = " "
@dataclass
class Book:
title: str
author: str
year: int
book = Book(title="The Catcher in the Rye", author="J.D. Salinger", year=1951)
print(serializer.render(book))
```
--------------------------------
### Install xsdata from repository using pip
Source: https://github.com/tefra/xsdata/blob/main/docs/installation.md
Install xsdata directly from its GitHub repository using pip.
```console
pip install xsdata[cli,lxml] @ git+https://github.com/tefra/xsdata
```
--------------------------------
### Install xsdata using pip
Source: https://github.com/tefra/xsdata/blob/main/docs/installation.md
Install xsdata with optional dependencies for CLI, lxml, and SOAP.
```console
pip install xsdata[cli,lxml,soap]
```
--------------------------------
### Include Header Example
Source: https://github.com/tefra/xsdata/blob/main/docs/codegen/config.md
Example of the module docstring that is added to output files when the `--include-header` option is enabled.
```python
"""This file was generated by xsdata, v24.1, on 2024-01-22 10:20:25
Generator: DataclassGenerator
See: https://xsdata.readthedocs.io/
"""
```
--------------------------------
### Install xsData
Source: https://github.com/tefra/xsdata/blob/main/README.md
Install xsData with all dependencies including CLI, lxml, and SOAP support.
```console
# Install all dependencies
pip install xsdata[cli,lxml,soap]
```
--------------------------------
### Install xsdata using conda
Source: https://github.com/tefra/xsdata/blob/main/docs/installation.md
Install xsdata from the conda-forge channel.
```console
conda install -c conda-forge xsdata
```
--------------------------------
### Wrapper Fields Example
Source: https://github.com/tefra/xsdata/blob/main/docs/codegen/config.md
Examples of Python code demonstrating the use of wrapper fields for single or collections of simple and complex elements.
```python
alpha: str = field(
metadata={
"wrapper": "alphas",
"type": "Element",
},
)
bravo: List[int] = field(
default_factory=list,
metadata={
"wrapper": "bravos",
"type": "Element",
},
)
charlie: List[Charlie] = field(
default_factory=list,
metadata={
"wrapper": "charlies",
"type": "Element",
},
)
```
--------------------------------
### Install CLI and SOAP requirements
Source: https://github.com/tefra/xsdata/blob/main/docs/codegen/wsdl_modeling.md
Command to install xsdata with CLI and SOAP support.
```console
$ pip install xsdata[cli,soap]
```
--------------------------------
### house.py
Source: https://github.com/tefra/xsdata/blob/main/docs/data_binding/basics.md
Example of house model definition.
```python
--8<-- "tests/fixtures/typemapping/house.py"
```
--------------------------------
### city.py
Source: https://github.com/tefra/xsdata/blob/main/docs/data_binding/basics.md
Example of city model definition.
```python
--8<-- "tests/fixtures/typemapping/city.py"
```
--------------------------------
### Download Schemas Example
Source: https://github.com/tefra/xsdata/blob/main/docs/codegen/download_schemas.md
Download a schema and its dependencies recursively to a specified output directory.
```console
❯ xsdata download https://www.w3.org/Math/XMLSchema/mathml3/mathml3.xsd -o ~/schemas
========= xsdata v24.6.1 / Python 3.11.8 / Platform linux =========
Setting base path to https:/www.w3.org/Math/XMLSchema/mathml3
Fetching https://www.w3.org/Math/XMLSchema/mathml3/mathml3.xsd
Fetching https://www.w3.org/Math/XMLSchema/mathml3/mathml3-content.xsd
Fetching https://www.w3.org/Math/XMLSchema/mathml3/mathml3-strict-content.xsd
Writing /home/chris/schemas/mathml3-strict-content.xsd
Writing /home/chris/schemas/mathml3-content.xsd
Fetching https://www.w3.org/Math/XMLSchema/mathml3/mathml3-presentation.xsd
Writing /home/chris/schemas/mathml3-presentation.xsd
Fetching https://www.w3.org/Math/XMLSchema/mathml3/mathml3-common.xsd
Writing /home/chris/schemas/mathml3-common.xsd
Writing /home/chris/schemas/mathml3.xsd
```
--------------------------------
### Basic XML Parsing Setup
Source: https://github.com/tefra/xsdata/blob/main/docs/data_binding/xml_parsing.md
Initialize the XmlParser with optional configuration and context.
```python
>>> from xsdata.formats.dataclass.context import XmlContext
>>> from xsdata.formats.dataclass.parsers import XmlParser
>>> from xsdata.formats.dataclass.parsers.config import ParserConfig
>>> config = ParserConfig()
>>> context = XmlContext()
>>> parser = XmlParser(context=context, config=config)
>>> parser = XmlParser()
```
--------------------------------
### Compound Fields Example
Source: https://github.com/tefra/xsdata/blob/main/docs/codegen/config.md
Examples of how compound fields are represented in Python code, showing different scenarios like forcing default names, limiting name parts, and using substitution groups.
```python
# Force default name or max name parts > 3
choice: list[str | int | float | bool] = field(...)
# max name parts <= 3
hat_or_bat_cat: list[str | int | float] = field(...)
# All types belong to the same substitution group `product`
product: list[Shoe | Shirt | Hat] = field(...)
```
--------------------------------
### Register a new generator
Source: https://github.com/tefra/xsdata/blob/main/docs/plugins/how_to.md
Example of registering a new generator with xsdata.
```python
from xsdata.codegen.writer import CodeWriter
from xsdata.formats.mixins import AbstractGenerator
class AwesomeGenerator(AbstractGenerator):
...
CodeWriter.register_generator("awesome", AwesomeGenerator)
```
```console
$ xsdata generate --output awesome
```
--------------------------------
### Install xsdata with lxml support
Source: https://github.com/tefra/xsdata/blob/main/docs/codegen/dtd_modeling.md
Install xsdata with the lxml extra to enable DTD processing.
```console
$ pip install xsdata[lxml]
```
--------------------------------
### street.py
Source: https://github.com/tefra/xsdata/blob/main/docs/data_binding/basics.md
Example of street model definition.
```python
--8<-- "tests/fixtures/typemapping/street.py"
```
--------------------------------
### Metadata: namespace
Source: https://github.com/tefra/xsdata/blob/main/docs/models/classes.md
Example showing how to set the 'namespace' metadata for an XML element.
```python
@dataclass
class Root:
class Meta:
namespace = "xsdata"
print(serializer.render(Root()))
```
--------------------------------
### Extension Configuration Example
Source: https://github.com/tefra/xsdata/blob/main/docs/codegen/config.md
XML configuration for adding base classes and decorators to generated classes.
```xml
```
--------------------------------
### Wildcard
Source: https://github.com/tefra/xsdata/blob/main/docs/models/fields.md
Example of using the Wildcard type for xs:any elements.
```python
>>> from xsdata.formats.dataclass.parsers import XmlParser
>>>
>>> @dataclass
... class Root:
... any: object = field(metadata={"type": "Wildcard"})
...
>>> xml = 'foo'
>>> parser = XmlParser()
>>> parser.from_string(xml, clazz=Root)
Root(any=AnyElement(qname='child', text='foo', tail=None, children=[], attributes={'a': 'b'}))
```
--------------------------------
### Metadata: name
Source: https://github.com/tefra/xsdata/blob/main/docs/models/classes.md
Example showing how to set the 'name' metadata for an XML element.
```python
from dataclasses import dataclass, field
from xsdata.formats.dataclass.serializers import XmlSerializer
serializer = XmlSerializer()
serializer.config.indent = " "
serializer.config.xml_declaration = False
@dataclass
class Root:
class Meta:
name = "xsdata"
print(serializer.render(Root()))
```
--------------------------------
### XML Schema Wildcard Example
Source: https://github.com/tefra/xsdata/blob/main/docs/data_binding/xml_serializing.md
An example of an XML schema defining complex type with wildcards for elements and attributes.
```xml
```
--------------------------------
### Default Configuration XML
Source: https://github.com/tefra/xsdata/blob/main/docs/codegen/config.md
Example of the default configuration XML generated by xsdata.
```xml
2
79
utf-8
true
true
true
true
true
true
true
false
false
false
true
false
false
true
false
```
--------------------------------
### Attributes
Source: https://github.com/tefra/xsdata/blob/main/docs/models/fields.md
Example of using the Attributes type for xs:anyAttribute elements.
```python
>>> @dataclass
... class Root:
... known: int = field(metadata={"type": "Attribute"})
... attrs: dict = field(metadata={"type": "Attributes"})
...
>>> xml = ''
>>> xml = ''
>>> parser.from_string(xml, clazz=Root)
Root(known=1, attrs={'unknown': '2'})
```
--------------------------------
### Metadata: nillable
Source: https://github.com/tefra/xsdata/blob/main/docs/models/classes.md
Example demonstrating the 'nillable' metadata for specifying xsi:nil="true".
```python
@dataclass
class Child:
class Meta:
nillable = True
@dataclass
class Root:
child: Child
root = Root(child=Child())
print(serializer.render(root))
```
--------------------------------
### Register a new class type
Source: https://github.com/tefra/xsdata/blob/main/docs/plugins/how_to.md
Example of registering a new class type for binding operations.
```python
from xsdata.formats.dataclass.compat import class_types
from xsdata.formats.dataclass.compat import ClassType
class AwesomeType(ClassType):
...
class_types.register("awesome", AwesomeType())
```
```python
from xsdata.formats.dataclass.context import XmlContext
from xsdata.formats.dataclass.parsers import XmlParser
context = XmlContext(class_types="awesome")
parser = XmlParser(context=context)
```
--------------------------------
### Elements
Source: https://github.com/tefra/xsdata/blob/main/docs/models/fields.md
Example of using the Elements type for repeatable choice elements.
```python
>>> @dataclass
... class Root:
... value: list[str | int | bool] = field(
... metadata={
... "type": "Elements",
... "choices": (
... {"name": "string", "type": str},
... {"name": "integer", "type": int},
... {"name": "bool", "type": bool}
... )
... }
... )
...
>>> root = Root(value=[1, True, "a", "b", True])
>>> print(serializer.render(root))
1
true
a
b
true
```
--------------------------------
### Using Generic Models with Wildcards
Source: https://github.com/tefra/xsdata/blob/main/docs/data_binding/xml_serializing.md
An example demonstrating the usage of AnyElement and DerivedElement for complex XML structures with wildcards.
```python
>>> from xsdata.formats.dataclass.models.generics import AnyElement
>>> from xsdata.formats.dataclass.models.generics import DerivedElement
...
>>> obj = MetadataType(
... any_element=[
... AnyElement(
... qname="bar",
... children=[
... AnyElement(qname="first", text="1st", attributes={"a": "1"}),
... AnyElement(qname="second", text="2nd", attributes={"b": "2"}),
... AnyElement(qname="{http://xsdata}third", text="2nd", attributes={"b": "2"}),
... DerivedElement(
... qname="fourth",
... value=MetadataType(other_attributes={"c": "3"})
... )
... ]
... )
... ]
... )
>>> print(serializer.render(obj))
```
--------------------------------
### Pycode Serializer Example
Source: https://github.com/tefra/xsdata/blob/main/docs/data_binding/pycode_serializing.md
Render an object tree into python representation code.
```python
>>> from tests.fixtures.books.fixtures import books
>>> from xsdata.formats.dataclass.serializers import PycodeSerializer
...
>>> serializer = PycodeSerializer()
>>> print(serializer.render(books, var_name="books"))
from tests.fixtures.books.books import BookForm
from tests.fixtures.books.books import Books
from xsdata.models.datatype import XmlDate
books = Books(
book=[
BookForm(
author='Hightower, Kim',
title='The First Book',
genre='Fiction',
price=44.95,
pub_date=XmlDate(2000, 10, 1),
review='An amazing story of nothing.',
id='bk001'
),
BookForm(
author='Nagata, Suanne',
title='Becoming Somebody',
genre='Biography',
price=33.95,
pub_date=XmlDate(2001, 1, 10),
review='A masterpiece of the fine art of gossiping.',
id='bk002'
),
]
)
```
--------------------------------
### Global Namespace Example
Source: https://github.com/tefra/xsdata/blob/main/docs/data_binding/basics.md
Demonstrates using the globalns option to manage type mappings for serialization, especially useful for handling circular imports or complex model relationships.
```python
>>> from xsdata.formats.dataclass.serializers import XmlSerializer
>>> from xsdata.formats.dataclass.serializers.config import SerializerConfig
>>> from tests.fixtures.typemapping.city import City
>>> from tests.fixtures.typemapping.house import House
>>> from tests.fixtures.typemapping.street import Street
>>>
>>> city1 = City(name="footown")
>>> street1 = Street(name="foostreet")
>>> house1 = House(number=23)
>>> city1.streets.append(street1)
>>> street1.houses.append(house1)
>>> type_map = {"City": City, "Street": Street, "House": House}
>>> serializer_config = SerializerConfig(indent=" ", globalns=type_map)
>>> xml_serializer = XmlSerializer(config=serializer_config)
>>> serialized_house = xml_serializer.render(city1)
>>> print(serialized_house)
footown
foostreet
23
```
--------------------------------
### Example
Source: https://github.com/tefra/xsdata/blob/main/docs/data_binding/tree_serializing.md
Render an object into an lxml element tree and print the resulting XML.
```python
>>> from lxml import etree
>>> from tests.fixtures.books.fixtures import books
>>> from xsdata.formats.dataclass.serializers import TreeSerializer
...
>>> serializer = TreeSerializer()
>>> serializer.config.indent = " "
>>> result = serializer.render(books, ns_map={'bk': "urn:books"})
...
>>> actual = etree.tostring(result)
>>> print(actual.decode())
Hightower, Kim
The First Book
Fiction
44.95
2000-10-01
An amazing story of nothing.
Nagata, Suanne
Becoming Somebody
Biography
33.95
2001-01-10
A masterpiece of the fine art of gossiping.
```
--------------------------------
### DictEncoder Example
Source: https://github.com/tefra/xsdata/blob/main/docs/data_binding/dict_encoding.md
Encode a BookForm instance to a dictionary and print it.
```python
>>> import pprint
>>> from xsdata.models.datatype import XmlDate
>>> from tests.fixtures.books import BookForm
>>>
>>> book = BookForm(
... id="bk001",
... author="Hightower, Kim",
... title="The First Book",
... genre="Fiction",
... price=44.95,
... pub_date=XmlDate(2000, 10, 1),
... review="An amazing story of nothing.",
... )
>>> pprint.pprint(encoder.encode(book))
```
--------------------------------
### Custom Class Factory for Object Instantiation
Source: https://github.com/tefra/xsdata/blob/main/docs/data_binding/basics.md
Example of overriding the default class factory in ParserConfig to customize object instantiation.
```python
>>> from dataclasses import dataclass
>>> from xsdata.formats.dataclass.parsers import JsonParser
>>> from xsdata.formats.dataclass.parsers.config import ParserConfig
...
>>> def custom_class_factory(clazz, params):
... if clazz.__name__ == "Person":
... return clazz(**{k: v.upper() for k, v in params.items()})
...
... return clazz(**params)
...
>>> config = ParserConfig(class_factory=custom_class_factory)
>>> parser = JsonParser(config=config)
...
>>> @dataclass
... class Person:
... first_name: str
... last_name: str
...
>>> json_str = """{"first_name": "chris", "last_name": "foo"}"""
...
...
>>> print(parser.from_string(json_str, Person))
Person(first_name='CHRIS', last_name='FOO')
```
--------------------------------
### Google Docstring Style
Source: https://github.com/tefra/xsdata/blob/main/docs/codegen/docstrings.md
Example of using the Google docstring style.
```python
--8<-- "tests/fixtures/docstrings/google/schema.py:31:"
```
--------------------------------
### Blank Docstring Style
Source: https://github.com/tefra/xsdata/blob/main/docs/codegen/docstrings.md
Example of using the Blank docstring style.
```python
--8<-- "tests/fixtures/docstrings/blank/schema.py:21:"
```
--------------------------------
### Parse XML with xsData
Source: https://github.com/tefra/xsdata/blob/main/README.md
Example of parsing an XML file into a Python dataclass object using xsData's XmlParser.
```python
>>> from tests.fixtures.primer import PurchaseOrder
>>> from xsdata.formats.dataclass.parsers import XmlParser
>>>
>>> parser = XmlParser()
>>> order = parser.parse("tests/fixtures/primer/sample.xml", PurchaseOrder)
>>> order.bill_to
Usaddress(name='Robert Smith', street='8 Oak Avenue', city='Old Town', state='PA', zip=Decimal('95819'), country='US')
```
--------------------------------
### Operation Class Example
Source: https://github.com/tefra/xsdata/blob/main/docs/codegen/wsdl_modeling.md
Python code snippet showing the generation of static classes for unique operations and binding procedures.
```python
--8<-- "tests/fixtures/calculator/services.py:488:494"
```
--------------------------------
### Mixed Content with Known Choices
Source: https://github.com/tefra/xsdata/blob/main/docs/data_binding/xml_serializing.md
Example of handling mixed content in XML where xsdata can match specific known elements.
```python
>>> @dataclass
... class Beta:
... class Meta:
... name = "beta"
...
>>> @dataclass
... class Alpha:
... class Meta:
... name = "alpha"
...
>>> @dataclass
... class Doc:
... class Meta:
... name = "doc"
...
... content: List[object] = field(
... default_factory=list,
... metadata={
... "type": "Wildcard",
... "namespace": "##any",
... "mixed": True,
... "choices": (
... {
... "name": "a",
... "type": Alpha,
... "namespace": "",
... },
... {
... "name": "b",
... "type": Beta,
... "namespace": "",
... },
... ),
... }
... )
...
>>> obj = Doc(
... content=[
... Alpha(),
... Beta(),
... ]
... )
...
>>> print(serializer.render(obj))
```
--------------------------------
### Use a directory as source
Source: https://github.com/tefra/xsdata/blob/main/docs/codegen/intro.md
Instruct the cli to search all subdirectories recursively with the -r, --recursive flag.
```console
$ xsdata generate project/schemas
$ xsdata generate project/schemas --recursive
```
--------------------------------
### xsdata generate --help
Source: https://github.com/tefra/xsdata/blob/main/docs/codegen/intro.md
Display help information for the xsdata generate command.
```console
$ xsdata generate --help
```
--------------------------------
### Use a filename or URI as source
Source: https://github.com/tefra/xsdata/blob/main/docs/codegen/intro.md
Specify a filename or URI as the source for xsdata generation.
```console
$ xsdata generate project/schemas/feed.xsd
$ xsdata generate http://www.gstatic.com/localfeed/local_feed.xsd
```
--------------------------------
### XmlContext and Parser/Serializer Initialization
Source: https://github.com/tefra/xsdata/blob/main/docs/data_binding/basics.md
Demonstrates how to initialize XmlContext and common parser/serializer instances.
```python
>>> from xsdata.formats.dataclass.context import XmlContext
>>> from xsdata.formats.dataclass.parsers import XmlParser
>>> from xsdata.formats.dataclass.parsers import JsonParser
>>> from xsdata.formats.dataclass.serializers import XmlSerializer
>>> from xsdata.formats.dataclass.serializers import JsonSerializer
>>> context = XmlContext()
>>> xml_parser = XmlParser(context=context)
>>> json_parser = JsonParser(context=context)
>>> xml_serializer = XmlSerializer(context=context)
>>> json_serializer = JsonSerializer(context=context)
```
--------------------------------
### Initialize Configuration
Source: https://github.com/tefra/xsdata/blob/main/docs/codegen/config.md
Command to create a default xsdata configuration file.
```console
$ xsdata init-config --help
```
--------------------------------
### DTD Definition
Source: https://github.com/tefra/xsdata/blob/main/docs/codegen/dtd_modeling.md
The DTD definition for the example.
```dtd
--8<-- "tests/fixtures/dtd/complete_example.dtd"
```
--------------------------------
### Merge redefined types
Source: https://github.com/tefra/xsdata/blob/main/docs/codegen/architecture.md
Example of merging redefined types.
```xml
```
--------------------------------
### Metadata: attribute_name_generator
Source: https://github.com/tefra/xsdata/blob/main/docs/models/classes.md
Example using 'attribute_name_generator' with the 'camel_case' utility.
```python
@dataclass
class Root:
who_are_you: str = field(default="xsdata", metadata={"type": "Attribute"})
class Meta:
attribute_name_generator = camel_case
print(serializer.render(Root()))
```
--------------------------------
### Download Schemas Help
Source: https://github.com/tefra/xsdata/blob/main/docs/codegen/download_schemas.md
Display the help message for the xsdata download command.
```console
$ xsdata download --help
```
--------------------------------
### Metadata: element_name_generator
Source: https://github.com/tefra/xsdata/blob/main/docs/models/classes.md
Example using 'element_name_generator' with the 'camel_case' utility.
```python
from xsdata.utils.text import camel_case
@dataclass
class RootType:
class Meta:
element_name_generator = camel_case
print(serializer.render(RootType()))
```
--------------------------------
### Generate with Configuration
Source: https://github.com/tefra/xsdata/blob/main/docs/codegen/config.md
Command to generate code using a specified configuration file.
```console
$ xsdata generate --config project/.xsdata.xml
```
--------------------------------
### Global Property Names with Naming Schemes
Source: https://github.com/tefra/xsdata/blob/main/docs/data_binding/basics.md
Shows how to use XmlContext to apply global naming schemes for elements and attributes.
```python
>>> from dataclasses import dataclass, field
>>> from datetime import date
>>> from xsdata.utils import text
>>> from xsdata.formats.dataclass.context import XmlContext
...
>>> @dataclass
... class Person:
...
... first_name: str
... last_name: str
... birth_date: date = field(
... metadata=dict(
... type="Attribute",
... format="%Y-%m-%d"
... )
... )
...
>>> obj = Person(
... first_name="Chris",
... last_name="T",
... birth_date=date(1986, 9, 25),
... )
...
>>> context = XmlContext(
... element_name_generator=text.camel_case,
... attribute_name_generator=text.kebab_case
... )
>>> serializer = XmlSerializer(context=context)
>>> serializer.config.indent = " "
>>> print(serializer.render(obj))
Chris
T
```
--------------------------------
### Remove duplicate overridden types
Source: https://github.com/tefra/xsdata/blob/main/docs/codegen/architecture.md
Example of removing duplicate overridden types.
```xml
```
--------------------------------
### Remove types with unknown references
Source: https://github.com/tefra/xsdata/blob/main/docs/codegen/architecture.md
Example of removing types with unknown references.
```xml
```
--------------------------------
### XML Documents
Source: https://github.com/tefra/xsdata/blob/main/docs/codegen/samples_modeling.md
Generate models from XML documents.
```console
$ xsdata generate --package tests.fixtures.artists tests/fixtures/artists
```
```xml
--8<
-- "tests/fixtures/artists/art001.xml"
```
```xml
--8<
-- "tests/fixtures/artists/art002.xml"
```
```xml
--8<
-- "tests/fixtures/artists/art003.xml"
```
```python
--8<
-- "tests/fixtures/artists/metadata.py"
```
--------------------------------
### Ignore
Source: https://github.com/tefra/xsdata/blob/main/docs/models/fields.md
Example of using the Ignore type to force the binding context to ignore a field.
```python
>>> @dataclass
... class Root:
... index: int = field(default_factory=int, metadata={"type": "Ignore"})
...
>>> print(serializer.render(Root()))
```
--------------------------------
### Remove duplicate types
Source: https://github.com/tefra/xsdata/blob/main/docs/codegen/architecture.md
Example of removing duplicate types, keeping the last definition.
```xml
```
--------------------------------
### JSON Documents
Source: https://github.com/tefra/xsdata/blob/main/docs/codegen/samples_modeling.md
Generate models from JSON documents.
```console
$ xsdata generate --package tests.fixtures.series tests/fixtures/series/samples
```
```json
--8<
-- "tests/fixtures/series/samples/show1.json"
```
```json
--8<
-- "tests/fixtures/series/samples/show2.json"
```
```python
--8<
-- "tests/fixtures/series/series.py"
```
--------------------------------
### Initialize Serializer
Source: https://github.com/tefra/xsdata/blob/main/docs/data_binding/xml_serializing.md
Initialize an XmlSerializer with custom configuration for indentation.
```python
>>> from xsdata.formats.dataclass.context import XmlContext
>>> from xsdata.formats.dataclass.serializers import XmlSerializer
>>> from xsdata.formats.dataclass.serializers.config import SerializerConfig
>>> config = SerializerConfig(indent=" ")
>>> context = XmlContext()
>>> serializer = XmlSerializer(context=context, config=config)
```
--------------------------------
### Accessible Docstring Style
Source: https://github.com/tefra/xsdata/blob/main/docs/codegen/docstrings.md
Example of using the Accessible docstring style.
```python
--8<-- "tests/fixtures/docstrings/accessible/schema.py:31:"
```
--------------------------------
### NumPy Docstring Style
Source: https://github.com/tefra/xsdata/blob/main/docs/codegen/docstrings.md
Example of using the NumPy docstring style.
```python
--8<-- "tests/fixtures/docstrings/numpy/schema.py:31:"
```
--------------------------------
### Manual Client Configuration
Source: https://github.com/tefra/xsdata/blob/main/docs/codegen/wsdl_modeling.md
Python code to manually configure a Client instance.
```python
config = Config(
style="document",
location="",
transport=TransportTypes.SOAP,
soap_action="",
input=None,
output=None,
)
client = Client(config=config)
```
--------------------------------
### reStructuredText Docstring Style
Source: https://github.com/tefra/xsdata/blob/main/docs/codegen/docstrings.md
Example of using the reStructuredText docstring style.
```python
--8<-- "tests/fixtures/docstrings/rst/schema.py:31:"
```
--------------------------------
### Python Class with Extensions
Source: https://github.com/tefra/xsdata/blob/main/docs/codegen/config.md
Python code demonstrating the application of extensions (base class and decorator).
```python
from dataclasses import dataclass
from dataclasses_jsonschema import JsonSchemaMixin
from typed_dataclass import typed_dataclass
@dataclass
@typed_dataclass
class Cores(JsonSchemaMixin):
...
```
--------------------------------
### Client Initialization from Service
Source: https://github.com/tefra/xsdata/blob/main/docs/codegen/wsdl_modeling.md
Python code to initialize a Client instance from an operation class.
```python
>>> from xsdata.formats.dataclass.client import Client
>>> from tests.fixtures.calculator import CalculatorSoapAdd
>>> client = Client.from_service(CalculatorSoapAdd)
>>> client.config
Config(style='document', location='http://www.dneonline.com/calculator.asmx', transport='http://schemas.xmlsoap.org/soap/http', soap_action='http://tempuri.org/Add', input=, output=, encoding=None)
```
--------------------------------
### Performing Request with Dictionary Input
Source: https://github.com/tefra/xsdata/blob/main/docs/codegen/wsdl_modeling.md
Python code demonstrating how to send a request using a dictionary of raw values.
```python
client = Client.from_service(CalculatorSoapAdd)
params = {"body": {"add": {"int_a": 3, "int_b": 4}}}
client.send(params)
# CalculatorSoapAddOutput(body=CalculatorSoapAddOutput.Body(add_response=AddResponse(add_result=7)))
```
--------------------------------
### Naive Assumption
Source: https://github.com/tefra/xsdata/blob/main/docs/index.md
An example of a naive assumption made by xsdata to simplify XML schema processing.
```text
All xs:schema elements are classes everything else is either noise or class properties
```
--------------------------------
### Custom Type Registration
Source: https://github.com/tefra/xsdata/blob/main/docs/models/types.md
Example of registering a custom float type with specific serialization and deserialization logic.
```python
from dataclasses import dataclass, field
from xsdata.formats.converter import Converter, converter
from xsdata.formats.dataclass.parsers import XmlParser
from xsdata.formats.dataclass.serializers import XmlSerializer
serializer = XmlSerializer()
serializer.config.indent = " "
serializer.config.xml_declaration = False
class TheGoodFloat(float):
pass
@dataclass
class Example:
good: TheGoodFloat = field(metadata=dict(format="{:.2f}"))
bad: float
class TheGoodFloatConverter(Converter):
def deserialize(self, value: str, **kwargs) -> TheGoodFloat:
return round(TheGoodFloat(value), 1) # Even nicer
def serialize(self, value: TheGoodFloat, **kwargs) -> str:
if kwargs["format"]:
return kwargs["format"].format(value)
return str(value)
converter.register_converter(TheGoodFloat, TheGoodFloatConverter())
output = serializer.render(Example(TheGoodFloat(10.983263748), -9.9827632))
print(output)
XmlParser().from_string(output)
```
--------------------------------
### Custom namespace prefixes
Source: https://github.com/tefra/xsdata/blob/main/docs/data_binding/xml_serializing.md
Render an object to XML with custom namespace prefixes using the ns_map argument.
```python
>>> print(serializer.render(books, ns_map={"bk": "urn:books"}))
Hightower, Kim
The First Book
Fiction
44.95
2000-10-01
An amazing story of nothing.
```
--------------------------------
### Default Substitutions
Source: https://github.com/tefra/xsdata/blob/main/docs/codegen/config.md
Default XML configuration for package and class name substitutions.
```xml
```
--------------------------------
### Performing Request with Object Input
Source: https://github.com/tefra/xsdata/blob/main/docs/codegen/wsdl_modeling.md
Python code demonstrating how to send a request using an object that matches the config input type.
```python
request = CalculatorSoapAddInput(body=CalculatorSoapAddInput.Body(add=Add(10, 2)))
client.send(request)
# CalculatorSoapAddOutput(body=CalculatorSoapAddOutput.Body(add_response=AddResponse(add_result=12)))
```
--------------------------------
### Custom json dump factory
Source: https://github.com/tefra/xsdata/blob/main/docs/data_binding/json_serializing.md
Use a custom dump factory, for example, ujson.dump, for JSON serialization.
```python
import ujson
serializer = JsonSerializer(dump_factory=ujson.dump)
```
--------------------------------
### Override standard type converters
Source: https://github.com/tefra/xsdata/blob/main/docs/models/types.md
This example demonstrates how to override the default serialization behavior for `XmlDateTime` by registering a custom converter.
```python
from dataclasses import dataclass
from typing import Any, Optional
from xsdata.formats.converter import Converter, converter
from xsdata.formats.dataclass.parsers import XmlParser
from xsdata.formats.dataclass.serializers import XmlSerializer
from xsdata.formats.dataclass.serializers.config import SerializerConfig
from xsdata.models.datatype import XmlDateTime
serializer = XmlSerializer(config=SerializerConfig(xml_declaration=False))
@dataclass
class DateTimeObject:
datetime: XmlDateTime
datetime_obj = DateTimeObject(
datetime=XmlDateTime(
year=2023,
month=11,
day=24,
hour=10,
minute=38,
second=56,
fractional_second=123_000_000,
)
)
print(serializer.render(datetime_obj))
class MyXmlDateTimeConverter(Converter):
def deserialize(self, value: Any, **kwargs: Any) -> XmlDateTime:
return XmlDateTime.from_string(value)
def serialize(self, value: Any, **kwargs: Any) -> Optional[str]:
if isinstance(value, XmlDateTime):
# Can be anything you like
return (
f"{value.day}-{value.month}-{value.year}"
f"T{value.hour}:{value.minute}:{value.second}"
)
converter.register_converter(XmlDateTime, MyXmlDateTimeConverter())
print(serializer.render(datetime_obj))
converter.unregister_converter(XmlDateTime)
```
--------------------------------
### Client Initialization with Encoding
Source: https://github.com/tefra/xsdata/blob/main/docs/codegen/wsdl_modeling.md
Python code to initialize a client with a specified encoding for non-ASCII characters.
```python
client = Client.from_service(encoding="utf-8")
```
--------------------------------
### Using Alternative Handlers
Source: https://github.com/tefra/xsdata/blob/main/docs/data_binding/xml_parsing.md
Demonstrates explicitly setting the XmlEventHandler, useful for performance or feature customization.
```python
>>> from xsdata.formats.dataclass.parsers.handlers import XmlEventHandler
...
>>> parser = XmlParser(handler=XmlEventHandler)
>>> order = parser.parse("tests/fixtures/primer/sample.xml")
>>> order.bill_to.street
'8 Oak Avenue'
```
--------------------------------
### Message Model Example
Source: https://github.com/tefra/xsdata/blob/main/docs/codegen/wsdl_modeling.md
Python code snippet representing the message model structure, including the Envelope wrapper.
```python
--8<-- "tests/fixtures/calculator/services.py:148:169"
```
--------------------------------
### Performing Request with Custom Headers
Source: https://github.com/tefra/xsdata/blob/main/docs/codegen/wsdl_modeling.md
Python code demonstrating how to send a request with custom headers.
```python
client.send(params, headers={"User-Agent": "xsdata"})
```
--------------------------------
### Parsing with lxml.etree.ElementTree
Source: https://github.com/tefra/xsdata/blob/main/docs/data_binding/xml_parsing.md
Use lxml's ElementTree for selective parsing, modifying the DOM, or starting from a specific node.
```python
>>> import lxml
>>> from xsdata.formats.dataclass.parsers.handlers import LxmlEventHandler
>>> from tests.fixtures.primer import Usaddress
...
>>> parser = XmlParser(handler=LxmlEventHandler)
>>> tree = lxml.etree.parse("tests/fixtures/primer/sample.xml")
>>> bill_to = parser.parse(tree.find('.//billTo'), Usaddress)
>>> bill_to
Usaddress(name='Robert Smith', street='8 Oak Avenue', city='Old Town', state='PA', zip=Decimal('95819'), country='US')
```