Python 文本文件到 xml 的转换

Python text file to xml conversion

我有以下文本文件:

"POLYGON ((7529 4573, 7541 4573, 7565 4577, 7586 4580, 7607 4584, 7633 4586, 7649 4591, 7675 4594, 7708 4600, 7758 4612))"

我想将其转换为以下格式:

"<Vertices><V X="7529" Y="4573" /><V X="7541" Y="4573" /><V X="7565" Y="4577" /><V X="7586" Y="4580" /><V X="7607" Y="4584" /><V X="7708" Y="4586" /><V X="7649" Y="4591" /><V X="7675" Y="4594" /><V X="13278" Y="4600" /><V X="7758" Y="4612" />

到目前为止我尝试了什么?

from xml.etree.ElementTree import Element, SubElement, tostring

top = Element('Vertices')
child = SubElement(top, 'V')

child.text = "POLYGON ((7529 4573, 7541 4573, 7565 4577, 7586 4580, 7607 4584, 7633 4586, 7649 4591, 7675 4594, 7708 4600, 7758 4612))"
print(tostring(top))

如何将 x 和 y 坐标添加到 XML 输出?

试试下面的方法

import xml.etree.ElementTree as ET

text = "POLYGON ((7529 4573, 7541 4573, 7565 4577, 7586 4580, 7607 4584, 7633 4586, 7649 4591, 7675 4594, 7708 4600, 7758 4612))"
top = ET.Element('Vertices')
pairs = text[10:-2].split(',')
for pair in pairs:
    x, y = pair.strip().split(' ')
    child = ET.SubElement(top, 'V')
    child.attrib = {'X': x, 'Y': y}
ET.dump(top)

输出

<?xml version="1.0" encoding="UTF-8"?>
<Vertices>
   <V X="7529" Y="4573" />
   <V X="7541" Y="4573" />
   <V X="7565" Y="4577" />
   <V X="7586" Y="4580" />
   <V X="7607" Y="4584" />
   <V X="7633" Y="4586" />
   <V X="7649" Y="4591" />
   <V X="7675" Y="4594" />
   <V X="7708" Y="4600" />
   <V X="7758" Y="4612" />
</Vertices>