简体   繁体   English

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

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

I am creating a new xml file from scratch using python and the lxml library.我正在使用 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">

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

there is a SyntaxError: invalid syntax有一个 SyntaxError: invalid syntax

How can I do that ?我怎样才能做到这一点 ?

Here is how it can be done:这是如何做到的:

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

The main "trick" is to use QName to create the xsi:schemaLocation attribute.主要的“技巧”是使用QName创建xsi:schemaLocation属性。 An attribute with a colon in its name cannot be used as the name of a keyword argument.名称中带有冒号的属性不能用作关键字参数的名称。

I've added the declaration of the xsi prefix to nsmap , but it can actually be omitted.我已经在nsmap添加了xsi前缀的声明,但实际上可以省略它。 lxml defines default prefixes for some well-known namespace URIs, including xsi for http://www.w3.org/2001/XMLSchema-instance . lxml 为一些众所周知的命名空间 URI 定义了默认前缀,包括http://www.w3.org/2001/XMLSchema-instance xsi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM