[Tutor] small ElementTree problem

Karim karim.liateni at free.fr
Fri Jan 28 00:12:38 CET 2011


id is a tag so it is a OBJECT Element with attributes accessible by 
dictionnary x.attrib[key] and x.text for tag content text.

canonical string representation of your Element object: Obj.id :>  <Element 'result' at [mem addr]
And root is also an Element but the parent of id and name childs =>  composite pattern.
For result use iterator as below (not tested but should be ok):

*_/#Parsing:/_

       doc = ElementTree()
       doc.parse(xmlFile)*

*_/#iteration over tag element:/_

ids  = []
names =[]
for result in doc.iter('result'):
   idElem   = result.find('id')
***   nameElem = result.find('name')**
*   ids.append(idElem.text)
   names.append(nameElement.text)

final = zip(ids, names)
*

You are not obliged to provide the full XPATH. Etree search for you.

Regards
Karim

On 01/27/2011 11:23 PM, Alex Hall wrote:
> Hi all,
> I am using, and very much enjoying, the ElementTree library. However,
> I have hit a problem. Say I have something along the lines of:
>
> <service>
> <message>Message from Service</message>
> <version>1.0</version>
>   <list>
>    <result>
>     <id>1</id>
>     <name>result 1</name>
>    </result>
>    <result>
>     <id>2</id>
>     <name>result 2</name>
>    </result>
>   </list>
> </service>
>
> In my ResultSet class, I parse this to get the text of elements like
> message or version. Then, I use root.findall("list/result") and
> iterate over the result, passing to a second function which parses the
> passed-in elements into Result objects. For example:
>
> all=root.findall("list/result")
> for i in all:
>   self.mylist.append(Obj().parse(i))
>
> In Obj.parse(), the element passed in is treated like this:
>
> def parse(data):
>   root=data.getroot()
>   self.id=root.find("id").text
> self.name=root.find("name).text
>
> 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
>
> What is going on? Does the root change when I call find()? Why would
> an Element object get used when I clearly say to use the text of the
> found element? TIA.
>

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110128/1c371532/attachment.html>


More information about the Tutor mailing list