-
-
Notifications
You must be signed in to change notification settings - Fork 79
Is it possible to specify the namespace prefixes and the default namespace #922
-
I'm searching the documentation regarding namespace prefixes, but not finding anything which works. When serialising, I'm looking for a way to set the namespace prefix for specific namespaces and set the default namespace.
For example I don't want to generate this:
<ns0:foo xmlns:ns0="http://bar.example.com" />
I want to be able to specify either the default namespace:
<foo xmlns="http://bar.example.com" />
Or force the namespace to be a prefix of my chosing (bar in this example)
<bar:foo xmlns:bar="http://bar.example.com" />
I realise that in terms of XML standards these are all equivalent. However there are still broken interpreters around that choke on the "wrong" prefix.
Beta Was this translation helpful? Give feedback.
All reactions
Hello @couling,
You can use below codesnap:
from xsdata.formats.dataclass.serializers.xml import XmlSerializer
from xsdata.formats.dataclass.serializers.config import SerializerConfig
serializer_config: SerializerConfig = SerializerConfig(pretty_print=True)
xml_serializer: XmlSerializer = XmlSerializer(config=serializer_config)
The foo param is the root class of your xml & ns_map can be a dict variable if you want
For
<foo xmlns="http://bar.example.com" />
try below:
xml_foo: str = xml_serializer.render(foo, ns_map={"": "http://bar.example.com"})
For
<bar:foo xmlns:bar="http://bar.example.com" />
try below:
xml_foo: str = xml_serializer.render(foo, ns_map={"": "http://bar.example.com","...
Replies: 1 comment
-
Hello @couling,
You can use below codesnap:
from xsdata.formats.dataclass.serializers.xml import XmlSerializer
from xsdata.formats.dataclass.serializers.config import SerializerConfig
serializer_config: SerializerConfig = SerializerConfig(pretty_print=True)
xml_serializer: XmlSerializer = XmlSerializer(config=serializer_config)
The foo param is the root class of your xml & ns_map can be a dict variable if you want
For
<foo xmlns="http://bar.example.com" />
try below:
xml_foo: str = xml_serializer.render(foo, ns_map={"": "http://bar.example.com"})
For
<bar:foo xmlns:bar="http://bar.example.com" />
try below:
xml_foo: str = xml_serializer.render(foo, ns_map={"": "http://bar.example.com","bar":"http://bar.example.com"})
Here you write the xml file:
with open(f"{props.OUTPUT_PATH}{export_filename}.xml", "r") as f:
f.write(xml_foo)
Beta Was this translation helpful? Give feedback.