我正在使用 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">
我需要将此 namespace 信息作为路由标记的属性包含到根标记中。
我无法将信息包含到根声明中。
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"/>
主要的“技巧”是使用QName
创建xsi:schemaLocation
属性。名称中带有冒号的属性不能用作关键字参数的名称。
我已将 xsi
前缀的声明添加到 nsmap
中,但实际上可以省略。 lxml 为一些众所周知的命名空间 URI 定义了默认前缀,包括 http://www.w3.org/2001/XMLSchema-instance
的 xsi
。
关于python - 如何使用 lxml 将命名空间包含到 xml 文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46405690/