如何访问 xml 标签中以逗号分隔的元素?

How can I access the elements separated by comma in xml tags?

我需要将逗号分隔的元素存储在 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)

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

你可以使用

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)

我最近致力于访问 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']]

希望对您有所帮助,如果这是您想要的,请告诉我。