0

etree.ElementTree package in python to parse my xml file but it seems it fails to do so.

My xml file hierarchy is like this: root <- -> config data <> sourcefile <- -> file object1 object2 ... etc.

when I use print self.xml_root.findall(".\config"), I only got "[]", which is an empty list, thanks

1
  • can you please give a sample of your xml file and the code you used? Commented Jul 14, 2013 at 20:21

1 Answer 1

2

If you really have '.\config' in the string, that would be the problem. That's a string literal using \c as one of its characters. Even if you have '.\\config' or r'.\config', both of which specify a literal backslash, that would still be wrong:

$ cat eleme.py
import xml.etree.ElementTree as ET

root = ET.fromstring("""
<root>
  <config>
    source
  </config>
  <config>
    source
  </config>
</root>""")

print r'using .\config', root.findall('.\config')
print r'using .\\config', root.findall('.\\config')
print 'using ./config', root.findall('./config')
$ python2.7 eleme.py 
using .\config []
using .\\config []
using ./config [<Element 'config' at 0x8017a8610>, <Element 'config' at 0x8017a8650>]
Sign up to request clarification or add additional context in comments.

2 Comments

so I need './config'?, but the actual situation is that I cannot use root.iter('object'), which is a grand-child node of root. What's the problem with that? Thank you
I'll need to see more actual code and XML to know what you mean here. In general elem.iter(), for any element, gives you an iterator over the item and its children: basically, yield self followed by `yield next_child_in_sequence', optionally restricting by tag-match.

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.