Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
972 views
in Technique[技术] by (71.8m points)

python - 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.

<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

How can I do that ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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. 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. lxml defines default prefixes for some well-known namespace URIs, including xsi for http://www.w3.org/2001/XMLSchema-instance.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...