用python解析xml获取x,y值

2024-06-29 00:57:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要从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:

谁能帮帮我吗


Tags: 文件incoordinatefordocvaluexmlprint
2条回答

作为示例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']}

使用ElementTree API(使用ET.parse(filename).getroot()而不是ET.XML()从文件加载):

from xml.etree import ElementTree as ET

xml = ET.XML("""
<?xml version="1.0" ?>
<Things>
    <TwoDimensionSpatialCoordinate>
        <coordinateIndex value="0"/>
        <x value="302.6215607602997"/>
        <y value="166.6285651861381"/>
    </TwoDimensionSpatialCoordinate>
    <TwoDimensionSpatialCoordinate>
        <coordinateIndex value="1"/>
        <x value="3.6215607602997"/>
        <y value="1.6285651861381"/>
    </TwoDimensionSpatialCoordinate>
</Things>
""".strip())

coords_by_index = {}
for coord in xml.findall(".//TwoDimensionSpatialCoordinate"):
    coords_by_index[coord.find("coordinateIndex").get("value")] = (
        coord.find("x").get("value"),
        coord.find("y").get("value"),
    )
print(coords_by_index)

输出

{
  '0': ('302.6215607602997', '166.6285651861381'),
  '1': ('3.6215607602997', '1.6285651861381'),
}

相关问题 更多 >