lxml use namespace instead of ns0, ns1,

巧了我就是萌 提交于 2019-12-06 04:53:17

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/19909473/lxml-use-namespace-instead-of-ns0-ns1

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!