python numpy 数组转换为 xml

python numpy array convert to xml

例如,有我的数据:

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

我想要这样的 xml 飞行:

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

我知道xml.etree.ElementTree可以实现,但是我没学过,请问python.Thank你能告诉我怎么做吗~

一个简单的 for 循环就可以做到这一点:

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()