[Tutor] small ElementTree problem

Stefan Behnel stefan_ml at behnel.de
Fri Jan 28 07:11:12 CET 2011


Hi,

since you said that you have it working already, here are just a few 
comments on your code.

Alex Hall, 27.01.2011 23:23:
> all=root.findall("list/result")
> for i in all:
>   self.mylist.append(Obj().parse(i))

It's uncommon to use "i" for anything but integer loop variables. And 'all' 
is not a very telling name either. I'd use something like "all_results" and 
"result_element" instead.


> In Obj.parse(), the element passed in is treated like this:
>
> def parse(data):
>   root=data.getroot()

I don't understand this. You already have an Element here according to your 
code above. Why do you try to call getroot() on it? Again, "data" is not 
very telling. Giving it a better name will help you here.


>   self.id=root.find("id").text
> self.name=root.find("name).text

There's a findtext() method on Elements for this purpose.


> Printing the results of the above through Obj.id or Obj.name gives me
> odd behavior:
> print Obj.id :>  <Element 'result' at [mem addr]
> print self.id :>  None

"Obj.id" is a class attribute. "self.id" is an instance attribute. 
Different things.


> Does the root change when I call find()?

No.


> Why would
> an Element object get used when I clearly say to use the text of the
> found element?

I don't think the code snippets you showed us above are enough to answer this.

Stefan



More information about the Tutor mailing list