I try to create an XML file like this:
<pico:record xsi:schemaLocation="http://purl.org/pico/1.0/ http://www.culturaitalia.it/pico/schemas/1.0/pico.xsd>
<dc:identifier>work_3117</dc:identifier>
</pico:record>
I use this code:
from lxml import etree
xsi="http://www.w3.org/2001/XMLSchema-instance"
schemaLocation="http://purl.org/pico/1.0/ http://www.culturaitalia.it/pico/schemas/1.0/pico.xsd"
ns = "{xsi}"
root=etree.Element("pico:record", attrib={"{" + xsi + "}schemaLocation" : schemaLocation})
etree.SubElement(root, "dc:identifier").text = "work_3117"
print(etree.tostring(root, pretty_print=True))
The result is not working, python tells me that:
ValueError: Invalid tag name u'pico:record'
If I change 'pico:recors' with 'record' the error is:
ValueError: Invalid tag name u'dc:identifier'
OK, the question is a bit old but I ran into the same problem today.
You need to provide the namespace of "dc" to the generation and the same goes for "pico" too. And you have to make lxml be aware of this namespace. You can do this with a namespace map which you provide when you create the root element:
from lxml import etree
xsi="http://www.w3.org/2001/XMLSchema-instance"
schemaLocation="http://purl.org/pico/1.0/ http://www.culturaitalia.it/pico/schemas/1.0/pico.xsd"
pico = "http://purl.org/pico/1.0/"
dc = "http://purl.org/dc/elements/1.1/"
ns = {"xsi": xsi, "dc": dc, "pico": schemalocation}
root=etree.Element("{" + pico + "}record", attrib={"{" + xsi + "}schemaLocation" : schemaLocation}, nsmap=ns)
etree.SubElement(root, "{" + dc + "}" + "identifier").text = "work_3117"
print etree.tostring(root, pretty_print=True)
And the result is:
<pico:record xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:pico="http://purl.org/pico/1.0/" xsi:schemaLocation="http://purl.org/pico/1.0/ http://www.culturaitalia.it/pico/schemas/1.0/pico.xsd">
<dc:identifier>work_3117</dc:identifier>
</pico:record>
For more details see: http://lxml.de/tutorial.html#namespaces
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With