0

I'm trying to edit a line in an XML file. One of the XML elements, called polyline, contains coordinates:

<location>
  <street>Interstate 76 (Ohio to Valley Forge)</street>
  <direction>ONE_DIRECTION</direction>
  <location_description>Donegal, PA</location_description>
  <polyline>40.100045 -79.202435, 40.09966 -79.20235, 40.09938 -79.20231<polyline>
</location>

I need to reverse the order and add a comma between each coordinate so it is written as:

<polyline>-79.202435,40.100045,-79.20235,40.09966,-79.20231,40.09938<polyline>

I can parse the file and format the polyline element, but not sure how to write it back into the XML file:

from xml.dom import minidom
mydoc = minidom.parse(xmlFile)

items = mydoc.getElementsByTagName('polyline')
for item in items:
    newPolyline = []
    lineList = item.firstChild.data.split(",")
    for line in lineList:
        lon = line.split(" -")[1]
        lat = line.split(" -")[0]
        newPolyline.append(str(lon))
        newPolyline.append(str(lat))
4
  • 1
    Can you post the way you have tried? Commented Sep 17, 2018 at 14:54
  • I can parse, and format the line, but I'm not sure how to write the new line back to the XML file. mydoc = minidom.parse(xmlFile) items = mydoc.getElementsByTagName('polyline') for item in items: newPolyline = [] lineList = item.firstChild.data.split(",") for line in lineList: lon = line.split(" -")[1] lat = line.split(" -")[0] newPolyline.append(str(lon)) newPolyline.append(str(lat)) Commented Sep 17, 2018 at 15:10
  • 1
    There's lots of documentation on the internet for parsing xml with python. Have you done any research, and can you show what you've tried? Commented Sep 17, 2018 at 17:18
  • @J.Skinner: 1) the question is tagged "elementtree", but in the code you use minidom. Please clarify. 2) Please edit the question instead of putting code in comments, which is very hard to read. Commented Sep 17, 2018 at 17:33

1 Answer 1

1

The code may look something like this:

from xml.dom.minidom import parseString

xmlobj = parseString('''<location>
    <street>Interstate 76 (Ohio to Valley Forge)</street>
    <direction>ONE_DIRECTION</direction>
    <location_description>Donegal, PA</location_description>
    <polyline>40.100045 -79.202435, 40.09966 -79.20235, 40.09938 -79.20231</polyline>
</location>''')

polyline = xmlobj.getElementsByTagName('polyline')[0].childNodes[0].data
xmlobj.getElementsByTagName('polyline')[0].childNodes[0].data = ','.join(
    ','.join(pair.split()[::-1]) for pair in polyline.split(','))
print(xmlobj.toxml())

This solution assumes, that there is only one polyline tag in the XML.

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.