[Python] Handling XML default namespace in Python using Pydantic

Discussão em 'Python' iniciado por Stack, Maio 22, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to convert some JSON data into XML in Python using the Pydantic-XML library (https://pydantic-xml.readthedocs.io/en/latest/index.html). However, I am having trouble getting the default namespaces according to my business requirements.

    This is my code:

    class Socials(
    BaseXmlModel,
    tag='socials',
    nsmap={'': 'http://www.company.com/soc'},
    ):
    urls: List[str] = element(tag='social')


    class Contacts(
    BaseXmlModel,
    tag='contacts',
    nsmap={'': 'http://www.company.com/cnt'},
    ):
    socials: Socials = element()


    class Company(
    BaseXmlModel,
    tag='company',
    nsmap={'': 'http://www.company.com/co'},
    ):
    contacts: Contacts = element()


    My desired output: (requirement from business, ns starts from 1 not 0)

    <ns1:company xmlns:ns1="http://www.company.com/co"
    xmlns:ns2="http://www.company.com/cnt"
    xmlns:ns3="http://www.company.com/soc">
    <ns2:contacts>
    <ns3:socials>
    <ns3:social>https://www.linkedin.com/company/spacex</ns2:social>
    <ns3:social>https://twitter.com/spacex</ns2:social>
    <ns3:social>https://www.youtube.com/spacex</ns2:social>
    </ns3:socials>
    </ns2:contacts>
    </ns1:company>


    What I get from library:

    <company xmlns="http://www.company.com/co">
    <contacts xmlns="http://www.company.com/cnt" >
    <socials xmlns="http://www.company.com/soc">
    <social>https://www.linkedin.com/company/spacex</social>
    <social>https://twitter.com/spacex</social>
    <social>https://www.youtube.com/spacex</social>
    </socials>
    </contacts>
    </company>


    Can anyone help let me know how to achieve this with the pydantic-xml library or any other python library?

    Regards, Krish

    Continue reading...

Compartilhe esta Página