0

I have the following text file:

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

I would like to convert it to the following format:

"<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" />

What I tried so far?

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

How can I add the x and y co-ordinates to the XML output?

1 Answer 1

1

Give the below a try

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)

output

<?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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.