Skip to content

Keep extra elements and attributes, mixed with predefined ones #304

Description

@RobertoRoos

I have a situation where I want to: load a massive XML, interact with a small set of elements and attributes and re-save the XML again.
There is no interest in most of the schema, defining a full model would just be a burden. Fortunately we can load most elements as raw XML (as described here: https://pydantic-xml.readthedocs.io/en/latest/pages/data-binding/raw.html).

However, this is only for entire elements. We still have some cases where an element is partially relevant. Take for instance this XML:

<company type="private" language="en">
    <contact>
        <email>info@business.nl</email>
    </contact>
    <product>Ice-cream</product>
    <product>Bread</product>
    <product>Milk</product>
</company>

With this model:

class Contact(BaseXmlModel):
    email: str = element()


class Company(BaseXmlModel, tag="company", arbitrary_types_allowed=True):
    type_: str = attr(name="type")

    contact: Contact
    products_raw: list[Element] = element(tag="product")

This loads and I can use the important entities as desired. But then when I export this again to XML the language="en" attribute is dropped.
Similarly, if the original XML has more child-elements that I didn't specifically call by name, they will have disappeared in the export.

How can I make sure extra entities like these will remain after the export?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions