pythonxmlnumpyxml.etree

python numpy array convert to xml


For example ,there is my data :

import numpy as np
a = np.array([[ 26.2, 280. ],
       [ 26.2, 279. ],
       [ 26. , 278.8],
       [ 25.2, 278. ],
       [ 25. , 277.8],
       [ 24.2, 277. ],
       [ 24. , 276.8],
       [ 23. , 276.8],
       [ 22.8, 277. ],
       [ 23. , 277.2],
       [ 23.8, 278. ],
       [ 24. , 278.2],
       [ 24.8, 279. ],
       [ 25. , 279.2],
       [ 25.8, 280. ],
       [ 26. , 280.2],
       [ 26.2, 280. ]])

I want to get a xml flie like this:

<?xml version="1.0"?>
<ASAP_Annotations>
    <Annotations>
        <Annotation Name="Annotation 0" Type="Spline" PartOfGroup="_1" Color="#F4FA58">
            <Coordinates>
                <Coordinate Order="0" X="26.2" Y="280." />
                <Coordinate Order="1" X="26.2" Y="279. " />
                <Coordinate Order="2" X="26." Y="278.8" />
                .........
                .........
                .........
                <Coordinate Order="14" X="25.8" Y="280." />
                <Coordinate Order="15" X="26." Y="280.2" />
                <Coordinate Order="16" X="26.2" Y="280." />
            </Coordinates>
        </Annotation>
    </Annotations>
</ASAP_Annotations>

I know it may be implemented by xml.etree.ElementTree,but I never learn it,could you please tell me how to do it in python.Thank you ~


Solution

  • A simple for loop will do that:

    headerXML = '''<?xml version="1.0"?>
    <ASAP_Annotations>
        <Annotations>
            <Annotation Name="Annotation 0" Type="Spline" PartOfGroup="_1" Color="#F4FA58">
                <Coordinates>
    '''
    
    elements = ""
    
    i = 0
    for element in a:
        elements = elements+ '<Coordinate Order="%s" X="%s" Y="%s" />\n'% (i,element[0],element[1] )
        i = i + 1
    
    
    footerXML = '''
                </Coordinates>
            </Annotation>
        </Annotations>
    </ASAP_Annotations>
    '''
    
    XML =(headerXML+elements+footerXML)
    
    outFile = open("coordinates.xml","w")
    outFile.write(XML)
    outFile.close()