首页 > 解决方案 > 使用python解析xml获取x,y值

问题描述

我需要从 xml 文件中获取 x,y 本地化

-<TwoDimensionSpatialCoordinate>

<coordinateIndex value="0"/>

<x value="302.6215607602997"/>

<y value="166.6285651861381"/>

</TwoDimensionSpatialCoordinate>
from xml.dom import minidom
doc = minidom.parse("1.631791322.58809740.14.834982.40440.3641459051.955.6373933.1920.xml")

"""doc.getElementsByTagName returns NodeList
coordinate = doc.getElementsByTagName("coordinateIndex")[0]
print(coordinate.firstChild.data)
"""

coordinate = doc.getElementsByTagName("coordinateIndex")
for coordinateIndex in coordinate:
        value = coordinateIndex.getAttribute("value")
coordinatex = doc.getElementsByTagName("x")
for x in coordinatex:
        valuex = x.getAttribute("value")        
coordinatey = doc.getElementsByTagName("y")
for y in coordinatey:
            valuey = y.getAttribute("value")
            print("value:%s, x:%s,y:%s" % (value, x , y))

所以当我执行我得到这个结果值:22,x:,y:

任何人都可以帮助我吗? :(

标签: pythonxmlparsingdom

解决方案


作为您的示例 xml 文件

<?xml version="1.0" ?>
<TwoDimensionSpatialCoordinate>
    <coordinateIndex value="0"/>
        <x value="302.6215607602997"/>
        <y value="166.6285651861381"/>
    <coordinateIndex value="1"/>
        <x value="3.6215607602997"/>
        <y value="1.6285651861381"/>
</TwoDimensionSpatialCoordinate>
import xml.dom.minidom


def main(file):
    doc = xml.dom.minidom.parse(file)
    values = doc.getElementsByTagName("coordinateIndex")
    coordX = doc.getElementsByTagName("x")
    coordY = doc.getElementsByTagName("y")
    d = {}
    for atr_value, atr_x, atr_y in zip(values, coordX, coordY):
        value = atr_value.getAttribute('value')
        x = atr_x.getAttribute('value')
        y = atr_y.getAttribute('value')
        d[value] = [x, y]
    return d


result = main('/path/file.xml')
print(result)

# {'0': ['302.621', '166.628'], '1': ['3.621', '1.628']}


推荐阅读