python - 使用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:
任何人都可以帮助我吗? :(
解决方案
作为您的示例 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']}
推荐阅读
- c# - 依赖属性获取和设置
- reactjs - 添加事件时,我的 React-Redux 项目输出错误
- android - 如何创建 android.opengl.EGLContext 对象的实例?
- python-3.x - 在 python 中添加与 Telethon 的联系
- jquery - 带图像显示的表
- css - 调整引导容器宽度
- oracle - 找不到 Oracle 12 C 安装错误文件
- c - 将 /dev/urandom 读入 c 字符串缓冲区
- android - View.OnDragListener() 方法不调用
- python - Efficiently Reorder DataFrame of Lists/Pairings