Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lxml use namespace instead of ns0, ns1,

Tags:

python

xml

lxml

I have just started with lxml basics and I am stuck with namespaces: I need to generate an xml like this:

<CityModel
xmlns:bldg="http://www.opengis.net/citygml/building/2.0"
    <cityObjectMember>
        <bldg:Building>
            <bldg:function>1000</bldg:function>
        </bldg:Building>
    </cityObjectMember>
</CityModel>

By using the following code:

from lxml import etree

cityModel = etree.Element("cityModel")
cityObject = etree.SubElement(cityModel, "cityObjectMember")
bldg = etree.SubElement(cityObject, "{http://schemas.opengis.net/citygml/building/2.0/building.xsd}bldg")
function = etree.SubElement(bldg, "{bldg:}function")
function.text = "1000"

print etree.tostring(cityModel, pretty_print=True)

I get this:

<cityModel>
    <cityObjectMember>
        <ns0:bldg xmlns:ns0="http://schemas.opengis.net/citygml/building/2.0/building.xsd">
            <ns1:function xmlns:ns1="bldg:">1000</ns1:function>
        </ns0:bldg>
        </cityObjectMember>
</cityModel>

which is quite different from what I want, and my software doesn't parse it. How to get the correct xml?

like image 619
528 Avatar asked Oct 21 '22 20:10

528


1 Answers

from lxml import etree

ns_bldg = "http://www.opengis.net/citygml/building/2.0"
nsmap = {
    'bldg': ns_bldg,
}

cityModel = etree.Element("cityModel", nsmap=nsmap)
cityObject = etree.SubElement(cityModel, "cityObjectMember")
bldg = etree.SubElement(cityObject, "{%s}Building" % ns_bldg)
function = etree.SubElement(bldg, "{%s}function" % ns_bldg)
function.text = "1000"
print etree.tostring(cityModel, pretty_print=True)

prints

<cityModel xmlns:bldg="http://www.opengis.net/citygml/building/2.0">
  <cityObjectMember>
    <bldg:Building>
      <bldg:function>1000</bldg:function>
    </bldg:Building>
  </cityObjectMember>
</cityModel>

See lxml.etree Tutorial - Namespaces.

like image 122
falsetru Avatar answered Oct 23 '22 11:10

falsetru