id id id

add default namespace to xml elements with etree in python

157 views Asked by At

I was able to create this xml with elementtree:

<createRequest xmlns:mam="http://www.link.com/schema/mig/messaging/mam">
<Id>id</mId>
<Info>
    <startTimeCode>00:00:00:00</startTimeCode>
</Info>
<segment>
    <tcIn>00:00:00:00</tcIn>
    <content>Content 1</content>
</segment>
<segment>
    <tcIn>00:00:40:01</tcIn>
    <content>Content 2</content>
</segment>

with this Python code:

createRequest = etree.Element('{}createRequest ', nsmap = {'mam' : 'http://www.link.com/schema/mig/messaging/mam'})
Id = etree.SubElement(createRequest , 'Id')
Id.text = "id"
Info = etree.SubElement(createRequest , 'Info')
startTimeCode = etree.SubElement(Info, 'startTimeCode')
startTimeCode.text = "00:00:00:00"
for start, end, phrase in textTiming:
    segment = etree.SubElement(createRequest, 'segment')
    tcIn = etree.SubElement(segment, 'tcIn')
    tcIn.text = start
    content = etree.SubElement(segment,'content')
    content.text = phrase

Now I want to add a default namespace and URN, so the xml looks like this:

<mam:createRequest xmlns:mam="http://www.link.com/schema/mig/messaging/mam" xmlns:urn="urn:ebu:metadata-schema:ebuCore_2012">
    <mam:Id>id</mam:mId>
    <mam:Info>
        <mam:startTimeCode>00:00:00:00</mam:startTimeCode>
    </mam:Info>
    <mam:segment>
        <mam:tcIn>00:00:00:00</mam:tcIn>
        <mam:content>Content 1</mam:content>
    </mam:segment>
    <mam:segment>
        <mam:tcIn>00:00:40:01</mam:tcIn>
        <mam:content>Content 2</mam:content>
    </mam:segment>
</mam:createRequest>

What do I need to add to my code to get this fixed?

1

There are 1 answers

0
user2811144 On

I just had to add the namespaces as a list and the default namespace for every element:

nslist = {
        'mam':'http://www.link.com/schema/mig/messaging/mam',
        'urn':'ebu:metadata-schema:ebuCore_2012'}
createRequest = etree.Element('{http://www.link.com/schema/mig/messaging/mam}createRequest ', nsmap = nslist)
Id = etree.SubElement(createRequest , '{http://www.link.com/schema/mig/messaging/mam}Id')
Id.text = "id"
Info = etree.SubElement(createRequest , '{http://www.link.com/schema/mig/messaging/mam}Info')
startTimeCode = etree.SubElement(Info, '{http://www.link.com/schema/mig/messaging/mam}startTimeCode')
startTimeCode.text = "00:00:00:00"
for start, end, phrase in textTiming:
    segment = etree.SubElement(createRequest, '{http://www.link.com/schema/mig/messaging/mam}segment')
    tcIn = etree.SubElement(segment, '{http://www.link.com/schema/mig/messaging/mam}tcIn')
    tcIn.text = start
    content = etree.SubElement(segment,'{http://www.link.com/schema/mig/messaging/mam}content')
    content.text = phrase