简体   繁体   中英

Python - parse xml with lxml trouble

I've found a lot of questions on this issue but nothing I saw fits mine. I'm new to lxml so need some help.

my users.xml file:

<?xml version="1.0" encoding="UTF-8"?>

<root>
    <user>
    <login>elena</login>
    <password>elena</password>
    <group>1</group>
    </user>

    <user>
    <login>anele</login>
    <password>anele</password>
    <group>2</group>
    </user>
</root>

the trouble function:

def analize_data(login):
   doc = etree.parse("/myapp/users.xml")   
   for elem in doc.iter(tag='login'):       
       if elem.text == login:
          parent = elem.getparent()
          group = etree.SubElement(parent, 'group')
          return group.text

What I need: to find a user tag with login passed to function and get the text of group subelement of this user. But this function returns None when testing. What am I doing wrong and how to fix it?

I'm new to all these things, so need help. Thanks in advance!

Try using:

group = parent.iterchildren(tag="group").next()

etree.SubElement does something completely different:

This function creates an element instance, and appends it to an existing element.

Which is clearly not what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM