# Serialization
TreeStore supports multiple serialization formats for persisting and transferring tree data.
## Serialization Formats
```{mermaid}
graph LR
subgraph "TreeStore"
TS[TreeStore
In-Memory]
end
subgraph "Formats"
TYTX[TYTX
Type-preserving]
XML[XML
Standard markup]
DICT[Dict
Python native]
end
TS -->|to_tytx()| TYTX
TS -->|to_xml()| XML
TS -->|to_dict()| DICT
TYTX -->|from_tytx()| TS
XML -->|from_xml()| TS
DICT -->|from_dict()| TS
```
## TYTX Format
TYTX (TYped Tree eXchange) is TreeStore's native serialization format that preserves Python types.
### Supported Types
| Type | Preserved | Example |
|------|-----------|---------|
| `str` | ✓ | `"hello"` |
| `int` | ✓ | `42` |
| `float` | ✓ | `3.14` |
| `bool` | ✓ | `True` |
| `None` | ✓ | `None` |
| `Decimal` | ✓ | `Decimal('1234.56')` |
| `date` | ✓ | `date(2025, 1, 15)` |
| `datetime` | ✓ | `datetime.now()` |
| `list` | ✓ | `[1, 2, 3]` |
| `dict` | ✓ | `{'key': 'value'}` |
### Basic Usage
```python
from decimal import Decimal
from datetime import date, datetime
from genro_treestore import TreeStore
store = TreeStore()
store.set_item('invoice.amount', Decimal('1234.56'))
store.set_item('invoice.date', date(2025, 1, 15))
store.set_item('invoice.timestamp', datetime.now())
store.set_item('invoice.paid', False)
# Serialize to JSON (types preserved as metadata)
json_data = store.to_tytx()
# Deserialize - types restored exactly
restored = TreeStore.from_tytx(json_data)
assert isinstance(restored['invoice.amount'], Decimal)
assert isinstance(restored['invoice.date'], date)
assert isinstance(restored['invoice.timestamp'], datetime)
assert restored['invoice.paid'] is False
```
### Transport Formats
```{mermaid}
graph TB
subgraph "TYTX Transports"
JSON[JSON
Human-readable]
MSGPACK[MessagePack
Binary, compact]
end
JSON -->|"transport='json'"| DEFAULT[Default]
MSGPACK -->|"transport='msgpack'"| COMPACT[Compact]
```
```python
# JSON transport (default) - human-readable
json_data = store.to_tytx() # or to_tytx(transport='json')
# MessagePack transport - more compact, binary
binary_data = store.to_tytx(transport='msgpack')
# Restore from either format
from_json = TreeStore.from_tytx(json_data)
from_msgpack = TreeStore.from_tytx(binary_data, transport='msgpack')
```
### TYTX Structure
The TYTX format stores type information alongside values:
```json
{
"nodes": {
"invoice": {
"nodes": {
"amount": {
"value": "1234.56",
"type": "decimal"
},
"date": {
"value": "2025-01-15",
"type": "date"
}
}
}
}
}
```
## XML Serialization
TreeStore can import and export XML documents.
### Parsing XML
```python
from genro_treestore import TreeStore
xml = '''