Parsing XML in Python using ElementTree example

前端 未结 2 1040
野性不改
野性不改 2020-12-07 22:34

I\'m having a hard time finding a good, basic example of how to parse XML in python using Element Tree. From what I can find, this appears to be the easiest library to use f

相关标签:
2条回答
  • 2020-12-07 23:01

    If I understand your question correctly:

    for elem in doc.findall('timeSeries/values/value'):
        print elem.get('dateTime'), elem.text
    

    or if you prefer (and if there is only one occurrence of timeSeries/values:

    values = doc.find('timeSeries/values')
    for value in values:
        print value.get('dateTime'), elem.text
    

    The findall() method returns a list of all matching elements, whereas find() returns only the first matching element. The first example loops over all the found elements, the second loops over the child elements of the values element, in this case leading to the same result.

    I don't see where the problem with not finding timeSeries comes from however. Maybe you just forgot the getroot() call? (note that you don't really need it because you can work from the elementtree itself too, if you change the path expression to for example /timeSeriesResponse/timeSeries/values or //timeSeries/values)

    0 讨论(0)
  • 2020-12-07 23:03

    So I have ElementTree 1.2.6 on my box now, and ran the following code against the XML chunk you posted:

    import elementtree.ElementTree as ET
    
    tree = ET.parse("test.xml")
    doc = tree.getroot()
    thingy = doc.find('timeSeries')
    
    print thingy.attrib
    

    and got the following back:

    {'name': 'NWIS Time Series Instantaneous Values'}
    

    It appears to have found the timeSeries element without needing to use numerical indices.

    What would be useful now is knowing what you mean when you say "it doesn't work." Since it works for me given the same input, it is unlikely that ElementTree is broken in some obvious way. Update your question with any error messages, backtraces, or anything you can provide to help us help you.

    0 讨论(0)
提交回复
热议问题