python - 创建带有前缀标签的 XML 文件(python 和 lxml)

标签 python lxml xml-namespaces

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

最佳答案

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

您需要为生成提供“dc”命名空间,“pico”也是如此。而且你必须让 lxml 知道这个命名空间。您可以使用在创建根元素时提供的 namespace 映射来执行此操作:

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

关于python - 创建带有前缀标签的 XML 文件(python 和 lxml),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16637908/

相关文章:

python - 从失败的 rq 作业中获取异常消息

python - 解析 XML 模板标签的正则表达式

python - pip 无法正确安装软件包 : Permission denied error

python - 在python中向XML添加子元素

XSLT、循环中的多个 XML 文件、命名空间问题

xml - XML 的 XPath 具有默认 namespace 且未定义前缀?

python - Django:按[无,其他]中的值过滤

python - 将 2 1/2 小时添加到 python 中的时间对象

python - Python3 上的 Twistd 可执行文件

c# - 将 XSD 与包含一起使用