lxml使用命名空间而不是ns0,ns1,

时间:2013-11-11 15:06:06

标签: python xml lxml

我刚开始使用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?

1 个答案:

答案 0 :(得分: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 Tutorial - Namespaces