Search code examples
pythonxmljaxbxml-namespacespyxb

How to remove 'ns1' prefix with PyXB or JaXB?


From this xsd file:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema"  
           targetNamespace="http://foo.org/FooIsNotBar" 
           elementFormDefault="qualified">
<xs:element name="Foo" type="xs:string"/> 
</xs:schema>

I want to use PyXB to get this XML:

<?xml version="1.0" ?>
<Foo xmlns="http://foo.org/FooIsNotBar">hello</Foo>

So I did this:

pyxbgen -m test -u test.xsd # Where test.xsd is the above xsd file
echo -e "import test\\nprint test.Foo('Hello World').toxml()" | python

Unfortunately I get an XML that has the unwanted ns1 prefix:

<?xml version="1.0" ?>
<ns1:Foo xmlns:ns1="http://foo.org/FooIsNotBar">Hello World</ns1:Foo>

I would like to get rid of these ns1: prefixes. How?

EDIT

This question about jaxb gives me some hints about that but, I did not find the solution to my issue yet.

I discovered that I can set my prefix using test.Namespace.setPrefix('foo'). Unfortunately I cannot hide the prefix.

A dirty solution would be to do this:

import test
rmp = 'REMOVE_ME_PLEASE'
test.Namesapce.setPrefix(rmp)
print test.Foo('Hello World').toxml().replace(rmp + ':', '').replace(':' + rmp, '')

Solution

  • You can't just remove the prefix because the XML wouldn't be valid anymore. You can hide it by setting a default namespace as in this example:

    import pyxb.utils.domutils
    pyxb.utils.domutils.BindingDOMSupport.SetDefaultNamespace(test.Namespace)