Question

i just want to parse users from my xml file with python lxml;

here is my xml file:

<?xml version="1.0" encoding="utf-8"?>
<users>
    <user id="1">
        <username>xxx</username>
        <password>xxx</password>
        <email>xxx@example.com</email>
        <nickname>xxx</nickname>
        <phone>xxx</phone>
        <status>xxx</status>
    </user>
</users>

i searched a lot but i couldn't find a real good example about it. Thanks for your helps...

Was it helpful?

Solution

I hope this will give you a head start:

>>> s = b"""\
... <?xml version="1.0" encoding="utf-8"?>
... <users>
...     <user id="1">
...         <username>xxx</username>
...         <password>xxx</password>
...         <email>xxx@example.com</email>
...         <nickname>xxx</nickname>
...         <phone>xxx</phone>
...         <status>xxx</status>
...     </user>
... </users>
... """
>>> t = etree.XML(s)
>>> t.xpath('//username/text()')
['xxx']
>>> t.find('user[@id="1"]/username').text
'xxx'
>>> t.find('user[@id="1"]/password').text
'xxx'
…
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top