You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python获取XML中嵌套标签的名称

获取XML所有嵌套标签名称的解决方案

获取文档内全部标签(含所有层级)

使用find_all(True)匹配所有标签对象,遍历提取每个标签的name属性即可:

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>
    ''', "lxml")

# 提取所有标签名称
all_tag_names = [tag.name for tag in soup.find_all(True)]
print(all_tag_names)

运行后输出所有层级的标签名:

['AlternativeIdentifiers', 'NationalLocationCode', 'Name', 'SixteenCharacterName', 'Address', 'com:PostalAddress', 'add:A_5LineAddress', 'add:Line', 'add:Line', 'add:Line', 'add:Line', 'add:PostCode']

获取指定父标签下的嵌套标签

如果只需要某一特定父标签(如AlternativeIdentifiers或Address)内部的所有嵌套标签,先定位父标签,再遍历其所有后代标签:

# 提取AlternativeIdentifiers下的所有嵌套标签
parent_tag = soup.find("AlternativeIdentifiers")
nested_names = [tag.name for tag in parent_tag.find_all(True)]
print(nested_names)
# 输出:['AlternativeIdentifiers', 'NationalLocationCode']

# 提取Address下的所有嵌套标签
address_tag = soup.find("Address")
address_nested_names = [tag.name for tag in address_tag.find_all(True)]
print(address_nested_names)
# 输出:['Address', 'com:PostalAddress', 'add:A_5LineAddress', 'add:Line', 'add:Line', 'add:Line', 'add:Line', 'add:PostCode']

若不需要包含父标签本身,仅提取子标签及更深层级,可过滤掉父标签对象:

# 仅提取AlternativeIdentifiers的子标签及后代
parent_tag = soup.find("AlternativeIdentifiers")
child_only_names = [tag.name for tag in parent_tag.find_all(True) if tag != parent_tag]
print(child_only_names)
# 输出:['NationalLocationCode']

关键说明

  • find_all(True)会匹配文档中所有类型的标签,无论标签名是什么;
  • 带命名空间的标签(如com:PostalAddress)会完整保留前缀,BeautifulSoup解析XML时会保留原始标签名;
  • 每个标签对象的name属性即为标签的名称,直接提取即可。

内容的提问来源于stack exchange,提问作者snoozy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 19:01:17