def render_sub_node(self, parent: Element, value: Any, var: XmlVar, namespaces: Namespaces): if isinstance(value, AnyElement): self.render_wildcard_node(parent, value, var, namespaces) elif var.is_element or is_dataclass(value): self.render_element_node(parent, value, var, namespaces) elif not parent.text: SerializeUtils.set_text(parent, value, namespaces) else: SerializeUtils.set_tail(parent, value, namespaces)
def render_wildcard_node(self, parent: Element, value: Any, var: XmlVar, namespaces: Namespaces): if value.qname: sub_element = SubElement(parent, value.qname) else: sub_element = parent namespaces.add_all(value.ns_map) SerializeUtils.set_text(sub_element, value.text, namespaces) SerializeUtils.set_tail(sub_element, value.tail, namespaces) SerializeUtils.set_attributes(sub_element, value.attributes, namespaces) for child in value.children: self.render_sub_node(sub_element, child, var, namespaces) SerializeUtils.set_nil_attribute(sub_element, var.nillable, namespaces)
def render_wildcard_node(self, parent: Element, value: Any, var: XmlVar, namespaces: Namespaces): """Render a child element for the given parent according to the wildcard field metadata.""" if value.qname: sub_element = SubElement(parent, value.qname) else: sub_element = parent namespaces.add_all(value.ns_map) SerializeUtils.set_text(sub_element, value.text, namespaces) SerializeUtils.set_tail(sub_element, value.tail, namespaces) SerializeUtils.set_attributes(sub_element, value.attributes, namespaces) for child in value.children: self.render_sub_node(sub_element, child, var, namespaces) SerializeUtils.set_nil_attribute(sub_element, var.nillable, namespaces)
def render_complex_node(self, parent: Element, obj: Any, namespaces: Namespaces): meta = self.context.build(obj.__class__, QName(parent).namespace) for var, value in self.next_value(meta, obj): if value is None: continue elif var.is_attribute: SerializeUtils.set_attribute(parent, var.qname, value, namespaces) elif var.is_attributes: SerializeUtils.set_attributes(parent, value, namespaces) elif var.is_text: namespaces.add(var.qname.namespace) SerializeUtils.set_text(parent, value, namespaces) elif isinstance(value, list): self.render_sub_nodes(parent, value, var, namespaces) else: self.render_sub_node(parent, value, var, namespaces) SerializeUtils.set_nil_attribute(parent, meta.nillable, namespaces)
def render_node(self, parent: Element, obj: Any, namespaces: Namespaces): """Recursively traverse the given object and build the xml tree.""" if is_dataclass(obj): self.render_complex_node(parent, obj, namespaces) else: SerializeUtils.set_text(parent, obj, namespaces)
def test_set_text(self): SerializeUtils.set_text(self.element, 1, self.namespaces) self.assertEqual("1", self.element.text) SerializeUtils.set_text(self.element, "", self.namespaces) self.assertIsNone(self.element.text)