且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-31 21:50:31

以下是操作方法:

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)

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

Output from this code (line breaks have been added for readability):

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

主要的技巧"是使用QName创建xsi:schemaLocation属性.名称中带有冒号的属性不能用作关键字参数的名称.

The main "trick" is to use QName to create the xsi:schemaLocation attribute. An attribute with a colon in its name cannot be used as the name of a keyword argument.

我已将xsi前缀的声明添加到nsmap,但实际上可以省略. lxml为一些众所周知的名称空间URI(包括xsi表示http://www.w3.org/2001/XMLSchema-instance)定义了默认前缀.

I've added the declaration of the xsi prefix to nsmap, but it can actually be omitted. lxml defines default prefixes for some well-known namespace URIs, including xsi for http://www.w3.org/2001/XMLSchema-instance.