5

我刚刚开始学习 lxml 基础知识,但我被命名空间困住了:我需要生成这样的 xml:

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

通过使用以下代码:

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)

我明白了:

<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>

这与我想要的完全不同,我的软件不解析它。如何获得正确的xml?

4

1 回答 1

3
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)

印刷

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

请参阅lxml.etree 教程 - 命名空间

于 2013-11-11T15:17:47.617 回答