【问题标题】:How to find the starting element name in xml using iterparse如何使用 iterparse 在 xml 中查找起始元素名称
【发布时间】:2016-10-10 04:20:15
【问题描述】:

我有以下示例 xml

<osm version="0.6" generator="CGImap 0.3.3 (28791 thorn-03.openstreetmap.org)" copyright="OpenStreetMap and contributors" attribution="http://www.openstreetmap.org/copyright" license="http://opendatacommons.org/licenses/odbl/1-0/">
 <bounds minlat="41.9704500" minlon="-87.6928300" maxlat="41.9758200" maxlon="-87.6894800"/>
 <node id="261114295" visible="true" version="7" changeset="11129782" timestamp="2012-03-28T18:31:23Z" user="bbmiller" uid="451048" lat="41.9730791" lon="-87.6866303"/>

我想使用 python iter parse 从 xml 中提取边界和节点 我试过下面的代码sn -p

import xml.etree.cElementTree as ET
import pprint

def count_tags(filename):
    mytags = {}
    osmfile = open('example.osm', 'r')
    for event, elem in ET.iterparse(osmfile,events=('end',)):
        if elem.tag == "tag":
            if elem.attrib['k'] in mytags:
                mytags[elem.attrib['k']] += 1
            else:
                mytags[elem.attrib['k']] = 1

但我无法提取边界和节点...我错过了什么?

【问题讨论】:

  • elem.tag 永远不会等于“标签”。这是您的实际代码吗?
  • 我已经更新了xml

标签: python xml iterparse


【解决方案1】:

假设 boundsnode 是 XML 根目录下的一层,这应该可以工作:

def count_tags():
    mytags = {}
    for event, child in ET.iterparse('example.osm'):
        if child.tag in ('bounds', 'node'):
            mytags[child.tag] = child.attrib
    print mytags

调用count_tags 输出:

{
    'node': {'changeset': '11129782', 'uid': '451048', 'timestamp': '2012-03-28T18:31:23Z', 'lon': '-87.6866303', 'visible': 'true', 'version': '7', 'user': 'bbmiller', 'lat': '41.9730791', 'id': '261114295'}, 
    'bounds': {'minlat': '41.9704500', 'maxlon': '-87.6894800', 'minlon': '-87.6928300', 'maxlat': '41.9758200'}
}

【讨论】:

  • 我想为事件做一些事情,ET.iterparse中的孩子('example.osm'):如果mytags中的child.tag:mytags [child.tag] = 1 else:mytags [child .tag] += 1 但 m 在 += 上出现错误。我想将计数存储在值字段中
猜你喜欢
  • 2011-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-13
  • 2018-12-06
  • 2011-05-07
相关资源
最近更新 更多