XML Parser and serializer wrapper.
| 54 | |
| 55 | |
| 56 | class XmlParserSerializer: |
| 57 | """XML Parser and serializer wrapper.""" |
| 58 | |
| 59 | def __init__(self) -> None: |
| 60 | self.context = XmlContext() |
| 61 | self.parser = build_xml_parser(self.context) |
| 62 | self.serializer = build_serializer(self.context) |
| 63 | |
| 64 | def parse(self, xml: bytes, clazz: type[T]) -> T: |
| 65 | """ |
| 66 | Parse an XML file to an object. |
| 67 | |
| 68 | Args: |
| 69 | xml: The XML file as bytes. |
| 70 | clazz: The class to parse to. |
| 71 | """ |
| 72 | return self.parser.from_bytes(xml, clazz) |
| 73 | |
| 74 | def serialize(self, obj: object, ns_map: Optional[dict[Optional[str], str]] = None) -> str: |
| 75 | """ |
| 76 | Serialize an object to XML. |
| 77 | |
| 78 | Args: |
| 79 | obj: The object to serialize. |
| 80 | ns_map: The namespace map to use. |
| 81 | |
| 82 | Returns: |
| 83 | The XML as string. |
| 84 | """ |
| 85 | ns_map = ns_map or self.parser.ns_map or {"xs": "http://www.w3.org/2001/XMLSchema"} |
| 86 | return self.serializer.render(obj, ns_map) |
no outgoing calls