Create XML files which have tags with prefix (python and lxml) -
i try create xml file 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 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 not working, python tells me that:
valueerror: invalid tag name u'pico:record'
if change 'pico:recors' 'record' error is:
valueerror: invalid tag name u'dc:identifier'
ok, question bit old ran same problem today.
you need provide namespace of "dc" generation , same goes "pico" too. , have make lxml aware of namespace. can namespace map provide when create 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 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
Thanks for this blog keep sharing your thoughts like this...
ReplyDeleteApplications of Matlab
What is Matlab?