I want to generate the following xml element:
<dcterms:created xsi:type="dcterms:W3CDTF">2024-08-12T05:56:00Z</dcterms:created>
Here not only the element and type have a namespace but also the attribute. I can successfully create the element like this with lxml
:
tag = '{http://purl.org/dc/terms/}created'
e = etree.Element(tag)
e.set("{http://www.w3.org/2001/XMLSchema-instance}type", "W3CDTF")
and both namespaces are properly translated in the output XML. But it seems I can’t do:
tag = '{http://purl.org/dc/terms/}created'
e = etree.Element(tag)
e.set("{http://www.w3.org/2001/XMLSchema-instance}type", "{http://purl.org/dc/terms/}w3CDTF")
My workaround is to do this:
tag = '{http://purl.org/dc/terms/}created'
e = etree.Element(tag)
dcterms_prefix = [k for k, v in e.nsmap.items() if v == "http://purl.org/dc/terms/"][0]
e.set("{http://www.w3.org/2001/XMLSchema-instance}type", dcterms_prefix + ":W3CDTF")
Is there any more elegant solution?