【问题标题】:Parsing XML with Python and etree使用 Python 和 etree 解析 XML
【发布时间】:2015-06-26 20:29:16
【问题描述】:

我想从以下示例 Open Street Map XML 文件中提取包含带有键 'highway' 和特定值的标签的所有方式元素:

<?xml version="1.0" encoding="UTF-8"?>
<osm version="0.6" generator="CGImap 0.0.2">
 <bounds minlat="54.0889580" minlon="12.2487570" maxlat="54.0913900" maxlon="12.2524800"/>

 <node id="298884272" lat="54.0901447" lon="12.2516513" user="SvenHRO" uid="46882" visible="true" version="1" changeset="676636" timestamp="2008-09-21T21:37:45Z"/>
 <way id="26659127" user="Masch" uid="55988" visible="true" version="5" changeset="4142606" timestamp="2010-03-16T11:47:08Z">
  <nd ref="292403538"/>
  <nd ref="298884289"/>

  <nd ref="261728686"/>
  <tag k="highway" v="unclassified"/>
  <tag k="name" v="Pastower Straße"/>
 </way>
 <relation id="56688" user="kmvar" uid="56190" visible="true" version="28" changeset="6947637" timestamp="2011-01-12T14:23:49Z">
  <member type="node" ref="294942404" role=""/>
  ...
  <member type="node" ref="364933006" role=""/>
  <member type="way" ref="4579143" role=""/>
  ...
  <member type="node" ref="249673494" role=""/>
  <tag k="name" v="Küstenbus Linie 123"/>
  <tag k="network" v="VVW"/>
  <tag k="operator" v="Regionalverkehr Küste"/>
  <tag k="ref" v="123"/>
  <tag k="route" v="bus"/>
  <tag k="type" v="route"/>
 </relation>

</osm>

为此;我编写了以下使用 Etree 库的 Python 代码。它解析 XML 文档并使用 findall 函数(使用 XPath 语法)

import xml.etree.ElementTree as ET
supported_highways = ('motorway', 'trunk', 'primary', 'secondary', 'tertiary', 'unclassified', 'residential', 'highway_link', 'trunk_link', 'primary_link', 'secondary_link', 'tertiary_link')

class OSMParser:

    def __init__(self, inputData):
        self.root = ET.fromstring(inputData)


    def getRoads(self):
        ways = dict()
        for road in self.root.findall('./way/'):
            highway_tags = road.findall("./tag[@k='highway']")
            if not highway_tags:
                continue
            if all(highway.attrib['v'] not in supported_highways for highway in highway_tags):
                continue

但是,当我运行代码时,它没有找到 way 元素的标记(第二个 findall 生成一个空列表)。知道有什么问题吗?谢谢。

【问题讨论】:

  • 只需打印 root.tag 和 root.getchildren()。检查way标签是否是根标签的子标签。

标签: python xml xml-parsing elementtree


【解决方案1】:

尝试使用 XPath //way/ 而不是 ./way/

【讨论】:

    【解决方案2】:

    它的工作。

    >>> root.findall("./way/tag[@k='highway']")
    [<Element 'tag' at 0xb74568ac>]
    

    我认为在您的输入内容中标签way 不是主开始标签的子标签,即根标签

    或使用lxml.etree

    >>> import lxml.etree as ET1
    >>> root = ET1.fromstring(content)
    >>> root.xpath("//way/tag[@k='highway']")
    [<Element tag at 0xb745642c>]
    

    【讨论】:

      猜你喜欢
      • 2014-03-27
      • 1970-01-01
      • 1970-01-01
      • 2023-02-21
      • 2012-02-01
      • 2011-10-29
      • 2017-07-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多