如何使用 lxml 将名称空间包含到 xml 文件中?

How to include the namespaces into a xml file using lxml?

我正在使用 python 和 lxml 库从头开始创建一个新的 xml 文件。

<route xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.xxxx" version="1.1"
xmlns:stm="http://xxxx/1/0/0"
xsi:schemaLocation="http://xxxx/1/0/0 stm_extensions.xsd">

我需要将此命名空间信息作为路由标签的属性包含到根标签中。

我无法将信息包含到根声明中。

from lxml import etree
root = etree.Element("route",
    xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance",
    xmlns = "http://www.xxxxx",
    version = "1.1",
    xmlns: stm = "http://xxxxx/1/0/0"
)

存在语法错误:语法无效

我该怎么做?

操作方法如下:

from lxml import etree

attr_qname = etree.QName("http://www.w3.org/2001/XMLSchema-instance", "schemaLocation")
nsmap = {None: "http://www.xxxx",
         "stm": "http://xxxx/1/0/0",
         "xsi": "http://www.w3.org/2001/XMLSchema-instance"}

root = etree.Element("route", 
                     {attr_qname: "http://xxxx/1/0/0 stm_extensions.xsd"},
                     version="1.1", 
                     nsmap=nsmap)

print etree.tostring(root)

此代码的输出(已添加换行符以提高可读性):

<route xmlns:stm="http://xxxx/1/0/0"
       xmlns="http://www.xxxx"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://xxxx/1/0/0 stm_extensions.xsd"
       version="1.1"/>

主要"trick"是利用QName创建xsi:schemaLocation属性。名称中带冒号的属性不能用作关键字参数的名称。

我在nsmap中添加了xsi前缀的声明,但实际上可以省略。 lxml 为一些众所周知的命名空间 URI 定义了默认前缀,包括 xsi for http://www.w3.org/2001/XMLSchema-instance.