如何使用lxml将名称空间包含到xml文件中? [英] How to include the namespaces into a xml file using lxml?
问题描述
我正在使用python和lxml库从头开始创建一个新的xml文件.
I am creating a new xml file from scratch using python and the lxml library.
<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">
我需要将此名称空间信息包括在根标签中,作为路由标签的属性.
I need to include this namespace information into the root tag as attributes of the route tag.
我无法将信息包含在根声明中.
I can´t include the information into the root declaration.
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:无效的语法
there is a 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)
此代码的输出(已添加换行符以提高可读性):
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
.
这篇关于如何使用lxml将名称空间包含到xml文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!