How to get the name of nested tag from xml python

Question:

I want to get the name of all tags of nested tag. here is the code that I tried

soup = BeautifulSoup('''
<AlternativeIdentifiers>
   <NationalLocationCode>513100</NationalLocationCode>
</AlternativeIdentifiers>
<Name>Abbey Wood</Name>
<SixteenCharacterName>ABBEY WOOD.</SixteenCharacterName>
<Address>
 <com:PostalAddress>
   <add:A_5LineAddress>
       <add:Line>Abbey Wood station</add:Line>
       <add:Line>Wilton Road</add:Line>
       <add:Line>Abbey Wood</add:Line>
       <add:Line>Greater London</add:Line>
       <add:PostCode>SE2 9RH</add:PostCode>
   </add:A_5LineAddress>
 </com:PostalAddress>
</Address>
    ''', "lxml")

tags = soup.find("AlternativeIdentifiers").name 

print(tags)

for example, it will print AlternativeIdentifiers but I want the inside tag name too which is NationalLocationCode. I tried using the for loop but got the error.
Just for more clarification I have tried find_all and then use the for loop to traverse to get the tag name but it will print the entire tag not the tag.name

Asked By: snoozy

||

Answers:

Just invoke the find_all method, then you will get the desired ResultSet.

from bs4 import BeautifulSoup

soup = BeautifulSoup('''
<AlternativeIdentifiers>
   <NationalLocationCode>513100</NationalLocationCode>
</AlternativeIdentifiers>
<Name>Abbey Wood</Name>
<SixteenCharacterName>ABBEY WOOD.</SixteenCharacterName>
<Address>
 <com:PostalAddress>
   <add:A_5LineAddress>
       <add:Line>Abbey Wood station</add:Line>
       <add:Line>Wilton Road</add:Line>
       <add:Line>Abbey Wood</add:Line>
       <add:Line>Greater London</add:Line>
       <add:PostCode>SE2 9RH</add:PostCode>
   </add:A_5LineAddress>
 </com:PostalAddress>
</Address>
    ''', "xml")

for tag in tags:
    print(tag.name)
    print(tag.find('NationalLocationCode').name)

Output:

AlternativeIdentifiers
NationalLocationCode
Answered By: Fazlul

when you define the soup variable like this the tag names get changed.
try to print soup variable you will get your answer.

do print(soup) once

Answered By: Tushar Mazumdar
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.