1

I am a beginner in python and trying to parse the below string from xmlfile where I can get an output like below :

Expected output :{macman:(linkedin,facebook,stack overflow)}

so that I can find out which user has which clients

XML File :  <user name="macman">  <client name="linkedin" /> 
<client name="facebook" />  <client name="stack overflow" /> 
</user>

Code i am trying :

import urllib.request as url
import xml.etree.ElementTree as ET

xmlfile=url.urlopen(r'file:///D:/Python/user.html')

tree=ET.parse(xmlfile)

root=tree.getroot()
print(root.tag)

for item in root.findall("./user"):
   users={}
   for child in item:
      users[child.tag]=child.text
   print(users)

2 Answers 2

1

You need to findall() the client not the user. So, your code should look like this:

...
users = {root.get("name"): []}
for item in root.findall("client"):
    users[root.get("name")].append(item.get("name"))

print(users)
#{'macman': ['linkedin', 'facebook', 'stack overflow']}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks , what if i want to search facebook (value) and print all those keys(users) who has access to facebook ? Easy to print key and its corresponding values but not sure about the value if i want to search for ..
0

Below

import xml.etree.ElementTree as ET


xml =  '''<r><user name="macman1">  <client name="linkedin1" /> 
<client name="facebook1" />  <client name="stack overflow1" /> 
</user><user name="macman2">  <client name="linkedin2" /> 
<client name="facebook2" />  <client name="stack overflow2" /> 
</user></r>'''

root = ET.fromstring(xml)
data = {u.attrib['name']: [c.attrib['name'] for c in u.findall('./client')] for u in root.findall('.//user')}
print(data)

output

{'macman2': ['linkedin2', 'facebook2', 'stack overflow2'], 'macman1': ['linkedin1', 'facebook1', 'stack overflow1']}

Comments

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.