Search code examples
pythonxmlobject-detectionyololabelimg

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


I need to store the elements separated by comma in xml tags

For example, these x and y coordinates:

<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.


Solution

  • I have recently work on accessing the XML tags and I prefer xml.dom.minidom library of python for this use.

    The code for your above-mentioned XML tags in the question is:

    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. The output can be seen below:

    [['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.