Re: Can't find elements using ElementTree find method

Discussion in 'Python' started by Stefan Behnel, Aug 31, 2010.

  1. Brendan Simon (eTRIX), 31.08.2010 10:49:
    > I am trying to use ElementTree (with Python 2.7) and can't seem to find
    > elements at the top level. The find() and findall() methods seem to
    > find elements within the top level, but not if it the elements are at
    > the top level.
    >
    > How do I find top level elements ??
    > Here is my code.
    >
    > import xml.etree.ElementTree as ET
    >
    > xml = '''\
    > <?xml version="1.0" encoding="Windows-1252" ?>
    > <components>
    > <component>
    > <name>Fred</name>
    > <location>Australia</location>
    > </component>
    > </components>
    > '''
    >
    > root = ET.fromstring( xml )
    >
    > ### This pattern is not found :(
    > comps = root.find( './/components' )


    "." matches the current element, so the path expression looks for all
    "components" nodes *below* the current element.

    You can either wrap the root in an ElementTree and search globally (i.e.
    without the leading "."), or you can test the root node yourself.

    Stefan
     
    Stefan Behnel, Aug 31, 2010
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    1
    Views:
    470
    Fredrik Lundh
    Oct 22, 2005
  2. Kee Nethery
    Replies:
    12
    Views:
    2,091
    Stefan Behnel
    Jun 27, 2009
  3. Alex van der Spek
    Replies:
    2
    Views:
    364
    Alain Ketterlin
    Oct 11, 2011
  4. Tharanga Abeyseela

    ElementTree Issue - Search and remove elements

    Tharanga Abeyseela, Oct 17, 2012, in forum: Python
    Replies:
    2
    Views:
    156
    Stefan Behnel
    Oct 17, 2012
  5. Stefan Behnel
    Replies:
    0
    Views:
    166
    Stefan Behnel
    Oct 17, 2012
Loading...

Share This Page