pythonlxmlattributeerrornonetypexml.etree

Python XML Element AttributeError: 'NoneType' object has no attribute 'text'


I am trying to parse the following xml file.

<xml version="1">
    <nodes>
    1      -2.50000000E+01       0.00000000E+00       5.00000000E+00
    </nodes>
</xml>

I want to retrieve the values within the element nodes in that file. I have tried the following code:

import pandas as pd
import xml.etree.ElementTree as ET

xtree = ET.parse("SafePGInput_t.dat")
xroot = xtree.getroot()

for node in xroot:
    s_nodes = node.find('nodes')
    print(s_nodes.text)

What is returned is AttributeError: 'NoneType' object has no attribute 'text'. I thought it would return a string. Just printing s_nodes returns None. How do I get the text of the four values in the element nodes? I want to load these values into pandas if possible, since I need to calculate a new row. The actual nodes element contains a large amount of rows with values that exceeds pd.read_xmls limit when using the parser 'lxml'.

Any help would be appreciated.

Kind regards,

Ali


Solution

  • If you want to check the tag of the current node use:

    node.tag
    

    To get the content, if the node is the one you want, use

    node.text
    

    In your case, maybe you want:

    import pandas as pd
    import xml.etree.ElementTree as ET
    
    xtree = ET.parse("trash/d.xml")
    xroot = xtree.getroot()
    for node in xroot:
        if node.tag == "nodes":
            print(node.text)