[英]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"
)
有一个 SyntaxError: invalid syntax
我怎样才能做到这一点 ?
这是如何做到的:
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
属性。 名称中带有冒号的属性不能用作关键字参数的名称。
我已经在nsmap
添加了xsi
前缀的声明,但实际上可以省略它。 lxml 为一些众所周知的命名空间 URI 定义了默认前缀,包括http://www.w3.org/2001/XMLSchema-instance
xsi
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.