e-nouri e-nouri - 3 months ago 11
Python Question

Python: QName on node's attribute, lxml

In Python's lxml.etree, How do i add the namesapce to an attribute of a node like this one:
name space is:

XS_NS = 'http://www.w3.org/2001/XMLSchema'


result looking for is:

<xs:element name="label" type="xs:string"></xs:element> 


I tried this one but the result is not what i am looking for:

element = ET.SubElement(
sequence,
ET.QName(XS_NS, "element"),
name="label",
type=str(ET.QName(XS_NS, "string")),
)


Gave me:

<xs:element name="label" type="{http://www.w3.org/2001/XMLSchema}string"/>

Answer

As far as I know, while an attribute it self may have a namespace, the value of the attribute doesn't consider namespaces:

<!-- this attribute has namespace prefix -->
<dummy xs:foo="bar"/>
<!-- this attribute has value of string containing colon -->
<dummy foo="xs:bar"/>

So you can simply put the "prefix" and the "value" as a single string altogether:

type="xs:string"

Related discussion: XML Schema. Processing namespace-aware attribute values. There it's implicitly stated that a prefix in the attribute value isn't significant, only placeholders for the actual namespaces.

Comments