Menu

Convert between pyxb and dictionary

Help
2017-05-30
2017-05-30
  • Sergei SInitsyn

    Sergei SInitsyn - 2017-05-30

    Hello. Is there simple way to convert generated PYXB objects to dictionaries?

     

    Last edit: Sergei SInitsyn 2017-05-30
  • Peter A. Bigot

    Peter A. Bigot - 2017-05-30

    Not a simple way, no. You could use the class _ElementMap and _AttributeMap properties to extract elements and attributes from an instance and put them into a dictionary.

     
  • Sergei SInitsyn

    Sergei SInitsyn - 2017-05-30

    Thanks for answer. And is there any example how to do that?

     
  • Peter A. Bigot

    Peter A. Bigot - 2017-05-30

    No. I've never encountered a situation where I've had to do it.

     
  • Sergei SInitsyn

    Sergei SInitsyn - 2017-05-30

    Here is a the snippet. It dont look at attributes.

    def recursive_to_dict(node):
        if node is None:
            return node
        res = {}
        if isinstance(node, simpleTypeDefinition):
            return node
        for expanded_name, element_declaration in node._ElementMap.items():
            element_name = expanded_name.localName()
            node_value = getattr(node, element_name)
            if element_declaration.isPlural():
                res[element_name] = [
                    recursive_to_dict(plural_node)
                    for plural_node in node_value
                ]
            else:
                res[element_name] = recursive_to_dict(getattr(node, element_name))
        return res
    
     

Log in to post a comment.