0

I've got an XML file which looks like this:

<?xml version="1.0"?>
-<Object>
    <ID>Object_01</ID>
    <Location>Manchester</Location>
    <Date>01-01-2020</Date>
    <Time>15u59m05s</Time>   
-<Max_25Hz>
    <25Hz>0.916631065043311</25Hz>
    <25Hz>0.797958008447961</25Hz>
</Max_25Hz>
-<Max_75Hz>
    <75Hz>1.96599232706463</75Hz>
    <75Hz>1.48317837078523</75Hz>
</Max_75Hz>
</Object>

I still don't really understand the difference between attributes and text. With below code I tried to receive all the values using text.

import xml.etree.ElementTree as ET

root = r'c:\data\FF\Desktop\My_files\XML-files\Object_01.xml'

tree = ET.parse(root)
root = tree.getroot()

for elem in root:
    for subelem in elem:
        print(subelem.text) 

Expected output:

Object_01
Manchester
01-01-2020
15u59m05s
0.916631065043311
0.797958008447961
1.96599232706463
1.48317837078523

Received output:

0.916631065043311
0.797958008447961
1.96599232706463
1.48317837078523

I tried to do to same with .attributes in the hope to receive all the 'column' names but then I received:

{}
{}
{}
{}

2 Answers 2

1

You can access them directly above the for-loop.

Ex:

tree = ET.ElementTree(ET.fromstring(X))
root = tree.getroot()

for elem in root:
    print(elem.text)       #! Access them Here
    for subelem in elem:
        print(subelem.text) 

Output:

Object_01
Manchester
01-01-2020
15u59m05s

        
0.916631065043311
0.797958008447961

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

3 Comments

Thank you, and how about printing all the 'colum' names?
use .tag ex: elem.tag or subelem.tag
Great! Thank you. So whats the difference between attrib and tag?
0

You could give a try to https://github.com/martinblech/xmltodict. It is almost a replacement for json module. This allows to read an xml file into a python dict. This simplifies greatly accessing the xml content.

Something like:

from xmldict import *

root = r'c:\data\FF\Desktop\My_files\XML-files\Object_01.xml'
with open(root) as file:
   xmlStr = file.read()
   xmldict = xml.parse(xmlStr)

print (xmldict['Object']['Id'])

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.