Skip to main content

Module for serialize (convert) xml to Python dict (with Python objects)

Project description

XML Serializer

Allows you to convert XML to python dict (with python objects) using a schema.

Examples

You can see examples of using the module in serializer_test.py

We have next xml data (profiles.xml)

<payload>
    <MyProfile>
        <record id="1" nickname="eff1c" admin="true">
            <posts topic="something">
                <post name="test post" description="It's my test post." />
                <post name="python xml_serializer" description="It's very useful module!" />
            </posts>
        </record>
    </MyProfile>
</payload>

And we want to turn it into

{
    "payload": {
        "my_profile": {
            "record": {
                "id": 1,
                "nickname": "eff1c",
                "admin": True,
                "posts": {
                    "topic": "something",
                    "post": [
                        {"name": "test post", "description": "It's my test post."},
                        {
                            "name": "python xml_serializer",
                            "description": "It's very useful module!",
                        },
                    ],
                },
            }
        }
    }
}

We will write next schema

from xml_serializer import Tag, TagAttr
from xml_serializer.converter_types import Integer, String, Boolean

profiles_schema = {
    Tag("payload"): {
        Tag("MyProfile", "my_profile"): {
            Tag("record"): {
                TagAttr("id"): Integer(nullable=False),
                TagAttr("nickname"): String(nullable=False),
                TagAttr("admin"): Boolean(),
                Tag("posts"): {
                    TagAttr("topic"): String(nullable=False),
                    Tag("post"): [
                        {
                            TagAttr("name"): String(),
                            TagAttr("description"): String()
                        }
                    ]
                }
            }
        }
    }

Get etree element (tag)

from xml.etree import ElementTree as etree

tree = etree.parse("profiles.xml")
root = tree.getroot()

# you can use root tag or find any else
main_tag = root.find("payload")

And call the method to pass them to

from xml_serializer import xml_serialize

response = xml_serialize(profiles_schema, main_tag)

Schema

Tag/TagAttr

In order to serialize data, you need to describe the scheme of its structure.
To do this, we create a python dict with Tag/TagAttr object keys.
The value for Tag is a set of TagAttr-s or Tag. I think it's clear that TagAttr is an attribute of the current tag, and Tag is actually a nested tag.

from xml_serializer import Tag, TagAttr
from xml_serializer.converter_types import String

schema = {
    Tag("posts"): {
        TagAttr("topic"): String(nullable=False),
        Tag("post"): [
            {
                TagAttr("name"): String(),
                TagAttr("description"): String()
            }
        ]
    }
}

Both Tag and TagAttr have 2 parameters: field_name and name.
field_name - it is name in xml.
name - it is our custom name with which the object will return to us after serialization (by default - field_name).

Field data types

To convert TagAttr values, we use data types: String, Integer, Float, Boolean, NestedType.

String, Integer, Float, Boolean are similar to common data types (as in python). All of them have the nullable parameter (True by default).
When set to False, if the tag does not have this attribute in the input data, an error will be raised

NestedType

It is a data type that allows you to intercept serialization in the middle of a schema and process the resulting data according to your needs.

In order to use it, we have to describe the nested schema separately and create a function that will process the data received from it.
NestedType has 2 attributes for it: schema and data_handling_function

from xml_serializer import Tag, TagAttr
from xml_serializer.converter_types import Boolean, String, NestedType


posts_schema = {
    Tag("post", "posts"): [
        {
            TagAttr("name"): String(),
            TagAttr("description"): String()
        }
    ]
}


def get_post_names(data):
    posts = data["posts"]

    return [post["name"] for post in posts]


schema_with_nesting = {
    Tag("record"): {
        TagAttr("admin"): Boolean(),
        Tag("posts", "post_names"): NestedType(posts_schema, get_post_names)
    }
}

In this example, we return only a list of post-s names to the posts tag, discarding all the information we don't need. This way, NestedType allows you to modify the output data schema without unnecessary iterations.

Custom type

You can create your own field data types. Use AbstractType for it.

from xml_serializer.abstract_type import AbstractType

class Boolean(AbstractType):
    def convert_method(self, value):
        return True if value.lower() == "true" else False

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

xml_serializer-1.0.3.tar.gz (7.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

xml_serializer-1.0.3-py3-none-any.whl (6.5 kB view details)

Uploaded Python 3

File details

Details for the file xml_serializer-1.0.3.tar.gz.

File metadata

  • Download URL: xml_serializer-1.0.3.tar.gz
  • Upload date:
  • Size: 7.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.10.5

File hashes

Hashes for xml_serializer-1.0.3.tar.gz
Algorithm Hash digest
SHA256 fb7a74345bf915e4ac7373f814cb7c426d319a338545f02e08bc9b487bad0e44
MD5 dec13c708a99ea1a69a03c92a4ad6e85
BLAKE2b-256 b9cfba0884cf29906a1a7463525f543de46af7f6c853a6018256146f005b9802

See more details on using hashes here.

File details

Details for the file xml_serializer-1.0.3-py3-none-any.whl.

File metadata

  • Download URL: xml_serializer-1.0.3-py3-none-any.whl
  • Upload date:
  • Size: 6.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.10.5

File hashes

Hashes for xml_serializer-1.0.3-py3-none-any.whl
Algorithm Hash digest
SHA256 9b9a86d0e73856a24a60f109b467db24445b40865cc4852eca1060a9e5c00ee0
MD5 507b2bcfa5bb78f73f5cd24d0e4bb217
BLAKE2b-256 f83ae924ab7995785b2b90796fcd8de88d2eee664493827111a6716d9a35eb18

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page