简体   繁体   English

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

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

I need to store the elements separated by comma in xml tags我需要将用逗号分隔的元素存储在 xml 标签中

For example, these x and y coordinates:例如,这些 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>

I tried something like this我尝试过这样的事情

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

But got the following error但是出现以下错误

ValueError: too many values to unpack (expected 2)

Any help in this will be appreciated.对此的任何帮助将不胜感激。

You could use你可以使用

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)

I have recently work on accessing the XML tags and I prefer xml.dom.minidom library of python for this use.我最近致力于访问 XML 标签,我更喜欢xml.dom.minidom的 xml.dom.minidom 库用于此用途。

The code for your above-mentioned XML tags in the question is:问题中上述 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)

The output for above-mentioned code is split with x and y coordinates and stored in an array as you requested in the question.上述代码的 output 用 x 和 y 坐标拆分,并按照您在问题中的要求存储在一个数组中。 The output can be seen below: output 如下图所示:

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

Hope this help, please let me know if this is what you want.希望对您有所帮助,如果这是您想要的,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM