0
# Cobra Convention
1
2
Cobra convention uses 'attributes' and 'children' keys with sorted attributes and string-only values. It ensures consistent attribute ordering and preserves all values as strings for predictable data handling.
3
4
## Capabilities
5
6
### Cobra Class
7
8
Creates a Cobra converter with sorted attributes and string preservation.
9
10
```python { .api }
11
class Cobra(XMLData):
12
def __init__(self, **kwargs):
13
"""
14
Initialize Cobra converter.
15
16
Parameters:
17
- **kwargs: Additional XMLData parameters (xml_fromstring, xml_tostring,
18
element, dict_type, list_type, simple_text, invalid_tags)
19
20
Note: xml_fromstring defaults to False (string preservation)
21
"""
22
```
23
24
### Data to XML Conversion
25
26
Converts Python dictionaries and lists to XML elements using Cobra convention structure with explicit 'attributes' and 'children' handling.
27
28
```python { .api }
29
def etree(self, data, root=None):
30
"""
31
Convert data structure into a list of etree.Element using Cobra format.
32
33
Cobra etree() expects specific structure:
34
- Dictionary values must have 'attributes' key (dict of attributes)
35
- Dictionary values may have 'children' key (list of child elements)
36
- Simple string values become element text content
37
- Attributes from 'attributes' dict are set on XML element
38
- Children from 'children' list are recursively processed
39
40
Parameters:
41
- data: dict or list, data structure with Cobra format:
42
- {"element": {"attributes": {...}, "children": [...]}}
43
- {"element": "text"} for simple text elements
44
- root: Element, optional root element to append to
45
46
Returns:
47
List of etree.Element objects or modified root element
48
"""
49
```
50
51
### XML to Data Conversion
52
53
Converts XML elements to Python dictionaries using Cobra convention with sorted attributes and structured output.
54
55
```python { .api }
56
def data(self, root):
57
"""
58
Convert etree.Element into a dictionary using Cobra convention.
59
60
Cobra convention produces consistent output:
61
- 'attributes': Always present (sorted alphabetically, even when empty)
62
- 'children': List of child elements and text content (when present)
63
- Text-only elements: Become direct string values (flattened)
64
- String preservation: All values remain as strings (xml_fromstring=False)
65
- Merge behavior: Adjacent text and single elements may be merged
66
67
Parameters:
68
- root: Element, XML element to convert
69
70
Returns:
71
dict: Dictionary with element name as key and structured value:
72
- Simple text: {"element": "text"}
73
- Complex: {"element": {"attributes": {...}, "children": [...]}}
74
- Attributes dict always sorted by key
75
"""
76
```
77
78
**Usage Examples:**
79
80
```python
81
from xmljson import cobra
82
from xml.etree.ElementTree import fromstring, tostring
83
import json
84
85
# XML to data conversion (attributes always sorted)
86
xml_string = '<item zebra="z" alpha="a" beta="b"><title>Sample</title><count>42</count></item>'
87
xml_element = fromstring(xml_string)
88
data = cobra.data(xml_element)
89
print(json.dumps(data, indent=2))
90
# Output:
91
# {
92
# "item": {
93
# "attributes": {
94
# "alpha": "a",
95
# "beta": "b",
96
# "zebra": "z"
97
# },
98
# "children": [
99
# {"title": "Sample"},
100
# {"count": "42"}
101
# ]
102
# }
103
# }
104
105
# Data to XML conversion
106
data = {
107
'item': {
108
'attributes': {'id': '123', 'type': 'book'},
109
'children': [
110
{'title': 'Python Guide'},
111
{'author': 'John Doe'}
112
]
113
}
114
}
115
elements = cobra.etree(data)
116
print(tostring(elements[0]).decode())
117
# Output: <item id="123" type="book"><title>Python Guide</title><author>John Doe</author></item>
118
```
119
120
### Pre-configured Instance
121
122
```python { .api }
123
cobra: Cobra
124
```
125
126
A pre-configured Cobra instance available at module level for immediate use.
127
128
## Convention Rules
129
130
- **Attributes**: Always present as sorted dictionary under 'attributes' key (even when empty)
131
- **Children**: Present under 'children' key when elements have child nodes
132
- **String Values**: All values preserved as strings (no type conversion)
133
- **Sorted Order**: Attributes always sorted alphabetically for consistency
134
- **Empty Attributes**: Empty 'attributes' dict included even for elements with no attributes
135
- **Simple Elements**: Text-only elements become string values without structure
136
137
## Structure Patterns
138
139
### Element with Attributes and Children
140
```python
141
{
142
"element": {
143
"attributes": {"attr1": "value1", "attr2": "value2"}, # Always sorted
144
"children": [
145
{"child1": "text"},
146
{"child2": "more text"}
147
]
148
}
149
}
150
```
151
152
### Element with No Attributes
153
```python
154
{
155
"element": {
156
"attributes": {}, # Always present, even when empty
157
"children": [...]
158
}
159
}
160
```
161
162
### Simple Text Element
163
```python
164
{"element": "text content"} # Flattened when no attributes/children
165
```
166
167
## Use Cases
168
169
- **Deterministic Output**: When consistent attribute ordering is required
170
- **String Fidelity**: When all values must remain as strings
171
- **API Integration**: Compatible with Cisco's Cobra SDK format
172
- **Data Validation**: When predictable JSON structure is needed
173
- **Configuration Management**: Enterprise systems requiring consistent formatting
174
175
## Comparison with Abdera
176
177
```python
178
from xmljson import cobra, abdera
179
from xml.etree.ElementTree import fromstring
180
import json
181
182
xml_string = '<item beta="2" alpha="1"><title>Test</title></item>'
183
xml_element = fromstring(xml_string)
184
185
# Cobra: sorted attributes, strings only
186
cobra_data = cobra.data(xml_element)
187
print("Cobra:", json.dumps(cobra_data))
188
# Output: Cobra: {"item": {"attributes": {"alpha": "1", "beta": "2"}, "children": [{"title": "Test"}]}}
189
190
# Abdera: unsorted attributes, type conversion
191
abdera_data = abdera.data(xml_element)
192
print("Abdera:", json.dumps(abdera_data))
193
# Output: Abdera: {"item": {"attributes": {"beta": 2, "alpha": 1}, "children": [{"title": "Test"}]}}
194
```
195
196
## Enterprise Features
197
198
- **Consistent Serialization**: Same XML always produces identical JSON
199
- **Merge-Friendly**: Sorted attributes reduce diff noise in version control
200
- **Schema Validation**: Predictable structure aids in schema validation
201
- **Debugging**: Sorted attributes make debugging easier
202
203
## Error Handling
204
205
- **Missing Structure**: Handles elements without required 'attributes'/'children' keys
206
- **Invalid Types**: Converts all values to strings safely
207
- **Empty Documents**: Properly handles empty XML elements