-2

I have a string variable that contains XML:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<osm attribution="http://www.openstreetmap.org/copyright" copyright="OpenStreetMap and contributors" generator="openstreetmap-cgimap 2.0.1 (3329554 spike-07.openstreetmap.org)" license="http://opendatacommons.org/licenses/odbl/1-0/" version="0.6">
     
        <way changeset="123350178" id="26695601" timestamp="2022-07-08T08:32:16Z" uid="616103" user="Max Tenerelli" version="12" visible="true">
              
            <nd ref="289140256"/>
              
            <nd ref="292764243"/>
              
            <nd ref="291616556"/>
              
            <nd ref="292764242"/>
              
            <nd ref="291616560"/>
              
            <nd ref="291616561"/>
              
            <nd ref="291616562"/>
              
            <tag k="access" v="permissive"/>
              
            <tag k="highway" v="service"/>
              
            <tag k="maxspeed" v="30"/>
              
            <tag k="name" v="Baracconi - Jacotenente"/>
              
            <tag k="oneway" v="no"/>
              
            <tag k="surface" v="paved"/>
             
        </way>
        
    </osm>

I need to read all nd node (ref value) using Python. I built this code but it is not working:

import xml.etree.ElementTree as ET
    root = ET.fromstring(data)
    for eir in root.findall('nodes'):
        print(eir.text)
3
  • 1
    Your XML does not contain any nodes with tag 'nodes', so findall does not find any. Additionally, the nodes with tag 'nd' do not contain any text, just an attribute. Commented Nov 13, 2024 at 16:21
  • This xml does not contain any <nodes> elements. Frankly I do not even understand the question. Commented Nov 13, 2024 at 16:27
  • Find all nd elements with a ref attribute and extract the attribute value: [e.get('ref') for e in root.findall('.//nd[@ref]')]. Commented Nov 13, 2024 at 18:48

1 Answer 1

2
  1. You first need to find the way element and search for nd inside
  2. Thus don't search for nodes, but the element name: nd.
  3. There is no .text, to get the attribute use: eir.attrib['ref']
import xml.etree.ElementTree as ET

root = ET.fromstring(input)
way = root.find('way')

for eir in way.findall('nd'):
        print(eir.attrib['ref'])

Output:

289140256
292764243
291616556
292764242
291616560
291616561
291616562

Try it online!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.