0

I having difficulty in accessing the great-grandchildren using element tree in python. Specifically, I want access the tree of Ev,Ec,St,DU and Si. The full xml is attached together at the bottom of this thread.

I tried the following code, but it return nothing.

import xml.etree.ElementTree as ET
tree = ET.parse('shhs_eval.xml')
root = tree.getroot()
for ScoreEvent in root.findall('Sco'):
    Event = ScoreEvent.find('Ev').text
    Start = ScoreEvent.find('St').text
    print(Event,Start)

Thanks in advance

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <PSG>
    <Sof>Compumedics</Sof>
    <Ep>30</Ep>
    <Scs>
    <Sco>
        <Ev>Arousal</Ev>
        <Ec>Arousal|Arousal ()</Ec>
        <St>8062.4</St>
        <Du>22.8</Du>
        <Si>EMG</Si>
    </Sco>
    <Sco>
        <Ev>N1</Ev>
        <Evc>wl|Aw ()</Evc>
        <St>8062.4</St>
        <Du>22.8</Du>
        <Si>EMG</Si>
    </Sco>
    </Scs>
    </PSG>
mpx
  • 3,081
  • 2
  • 26
  • 56

1 Answers1

0

As <Sco> is not a direct child of the root, you have to access it with using findall(.//<node>) (depth first search).

import xml.etree.ElementTree as ET
tree = ET.parse('sshs_eval.xml')
root = tree.getroot()
for ScoreEvent in root.findall('.//Sco'):
    Event = ScoreEvent.find('Ev').text
    Start = ScoreEvent.find('St').text
    print(Event,Start)
bitnahian
  • 516
  • 5
  • 17
  • May I know why we have .// . Is it represent search? Anyhow, thanks for the solution, really appreciate it – mpx Oct 06 '18 at 16:41
  • It's depth first search. It looks for all instances of nested . Would you mind selecting this as the answer if it's correct? :) – bitnahian Oct 06 '18 at 16:45
  • Yes, I already accepted you post as an answer for this posting. Thanks – mpx Oct 06 '18 at 16:52