How to set namespace prefix to attribute value using lxml?

I am trying to create an XML schema using lxml. For starters, something like this:

<xs:schema xmlns="http://www.goo.com" xmlns:xs="http://www.w3.org/2001/XMLSchema"         elementFormDefault="qualified" targetNamespace="http://www.goo.com">
  <xs:element type="xs:string" name="name"/>
  <xs:element type="xs:positiveInteger" name="age"/>
</xs:schema>

I did it this way - by puttingthing xs: to the value, but I think it can be done better.

def schema():
    SCHEMA_NAMESPACE = "http://www.w3.org/2001/XMLSchema"
    XS = "{%s}" % SCHEMA_NAMESPACE
    NSMAP = {None: "http://www.goo.com"}

    schema = etree.Element(XS+"schema",
                           nsmap = NSMAP,
                           targetNamespace="http://www.goo.com",
                           elementFormDefault="qualified")

    element = etree.Element(XS+"element", 
                            attrib = {"name" : "name",
                                      "type" : "xs:string"})
    schema.append(element)
    element = etree.Element(XS+"element", 
                            attrib = {"name" : "age",
                                      "type" : "xs:positiveInteger"})

    schema.append(element)
    return etree.tostring(schema, pretty_print=True)

Could it be written any better?

+3
source share
1 answer

In a way, you need to include "xs": SCHEMA_NAMESPACEone in your NSMAP, otherwise nothing in your generated XML will actually display the xs prefix to fix the namespace. It will also allow you to simply specify the names of your elements using prefixes; eg. "Xs: element"

, , , , , , , NSMAP. XML , , :

  • NSMAP "xs" ;
  • _Element.nsmap , .

:

SCHEMA_NAMESPACE = "http://www.w3.org/2001/XMLSchema"

def add_element(schema):
    nsmap = schema.nsmap
    nsrmap = dict([(uri, prefix) for prefix, uri in nsmap.items()])
    prefix = nsrmap[SCHEMA_NAMESPACE]
    xs = lambda name: "%s:%s" % (prefix, name)
    element = schema.makeelement(xs("element"), nsmap=nsmap,
                                 attrib={'name': 'age', 'type': xs('string')})
    schema.append(element)
    return etree.tostring(schema, pretty_print=True)

.

+2

Source: https://habr.com/ru/post/1764160/


All Articles