创建具有前缀标记的XML文件(python和lxml)

2024-10-01 17:29:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试创建这样的XML文件:

<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>

我使用这个代码:

^{pr2}$

结果不起作用,python告诉我:

值错误:无效的标记名u'皮科:记录'

如果我改变皮科:录音机'使用'record'时,错误为:

值错误:无效的标记名u'dc:identifier'


Tags: 文件标记orghttpwww错误xmldc
2条回答

好吧,这个问题有点老了,但我今天碰到了同样的问题。在

您需要为代提供“dc”的名称空间,“pico”也一样。你必须让lxml知道这个名称空间。可以使用创建根元素时提供的命名空间映射来完成此操作:

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)

结果是:

^{pr2}$

有关详细信息,请参见:http://lxml.de/tutorial.html#namespaces

GHajba的代码第6行出现了一个小故障。修正如下。在

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": pico}
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)

相关问题 更多 >

    热门问题