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

前端 未结 1 1801
悲哀的现实
悲哀的现实 2020-12-11 11:40

I am creating a new xml file from scratch using python and the lxml library.



        
相关标签:
1条回答
  • 2020-12-11 12:12

    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.

    0 讨论(0)
提交回复
热议问题