如何访问xml标记中用逗号分隔的元素



我需要将用逗号分隔的元素存储在xml标记中

例如,这些x和y坐标:

<points>
<point>558.000000,790.000000</point>
<point>530.000000,829.000000</point>
<point>567.000000,855.000000</point>
<point>595.000000,815.000000</point>
<point>558.000000,790.000000</point>
</points>

我试过这种

x1, y1 = ((item.getElementsByTagName('points')[0]).getElementsByTagName('point')[0]).firstChild.data

但是得到了以下错误

ValueError: too many values to unpack (expected 2)

如有任何帮助,我们将不胜感激。

我最近致力于访问XML标记,我更喜欢python的xml.dom.minidom库。

问题中上述XML标记的代码是:

import xml.dom.minidom as minidom
name = "<points><point>558.000000,790.000000</point><point>530.000000,829.000000</point><point>567.000000," 
"855.000000</point><point>595.000000,815.000000</point><point>558.000000,790.000000</point></points> "
point = []
xml_loaded = minidom.parseString(name)
Points_Node = xml_loaded.getElementsByTagName("points")
for Main_Node in range(len(Points_Node)):
Point_Child = Points_Node[Main_Node].getElementsByTagName("point")
for Child_Node in range(len(Point_Child)):
point.append((Point_Child[Child_Node].firstChild.nodeValue).split(","))
print(point)

上述代码的输出用x和y坐标分割,并按照您在问题中的要求存储在一个数组中。输出如下:

[['558.000000', '790.000000'], ['530.000000', '829.000000'], ['567.000000', '855.000000'], ['595.000000', '815.000000'], ['558.000000', '790.000000']]

希望能得到帮助,如果这是你想要的,请告诉我。

您可以使用

import xml.etree.ElementTree as ET
data = """
<points>
<point>558.000000,790.000000</point>
<point>530.000000,829.000000</point>
<point>567.000000,855.000000</point>
<point>595.000000,815.000000</point>
<point>558.000000,790.000000</point>
</points>
"""
tree = ET.fromstring(data)
for element in tree:
x,y = element.text.split(",")
print(x, y)

相关内容

  • 没有找到相关文章

最新更新