3

我尝试创建一个这样的 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>

我使用这段代码:

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

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

ValueError: 无效的标签名称 u'pico:record'

如果我将 'pico:recors' 更改为 'record' 错误是:

ValueError: 无效的标签名称 u'dc:identifier'

4

2 回答 2

3

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

您需要为生成提供“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)

结果是:

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

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

于 2014-08-16T14:41:27.117 回答
0

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)
于 2016-05-26T15:23:45.667 回答