Home > database >  How do I assign values to specific values for multiple children?
How do I assign values to specific values for multiple children?

Time:08-16

From my previous question, I asked how to parse multiple siblings from the same child, now I am curious how you take each output and have it equal to a unique variable. For example, I want Unkown out equal to Occupation and 656 equal to CarrierCode, and so on.

from bs4 import BeautifulSoup
xml='''
from bs4 import BeautifulSoup

xml='''
<AdditonalAttributes>
    <Attribute>
        <Name> Occupation </Name> 
        <Value> Unknown </Value>
    </Attribute>
    <Attribute>
        <Name> CarrierCode </Name>
        <Value> 656 </Value>
    </Attribute>
<AdditonalAttributes>
'''

soup = BeautifulSoup(xml, 'xml')

for a in soup.select('Attribute'):
    if a.Name.get_text(strip=True) in ['Occupation','CarrierCode']:
        print(a.Value.get_text(strip=True))

Output:

Unknown
656

CodePudding user response:

Looks like you want to have a dict - see below

import xml.etree.ElementTree as ET

xml = '''<AdditonalAttributes>
    <Attribute>
        <Name> Occupation </Name> 
        <Value> Unknown </Value>
    </Attribute>
    <Attribute>
        <Name> CarrierCode </Name>
        <Value> 656 </Value>
    </Attribute>
</AdditonalAttributes>'''

root = ET.fromstring(xml)
data = {a.find('Name').text: a.find('Value').text for a in root.findall('.//Attribute')}
print(data)

output

{' Occupation ': ' Unknown ', ' CarrierCode ': ' 656 '}

CodePudding user response:

Assignment to variables is not clear but if you like to go the way along with BeautifulSoupto get a dict of your attributes:

dict(a.stripped_strings for a in soup.select('Attribute'))
Example
from bs4 import BeautifulSoup

xml='''
<AdditonalAttributes>
    <Attribute>
        <Name> Occupation </Name> 
        <Value> Unknown </Value>
    </Attribute>
    <Attribute>
        <Name> CarrierCode </Name>
        <Value> 656 </Value>
    </Attribute>
<AdditonalAttributes>
'''

soup = BeautifulSoup(xml, 'xml')

dict(a.stripped_strings for a in soup.select('Attribute'))

Output

{'Occupation': 'Unknown', 'CarrierCode': '656'}
  • Related