Python 3.6中获取XML子节点的方法咨询(新手求助)
如何用Python 3.6提取XML中的子节点?
嘿,作为Python和XML新手,用3.6版本的话,其实用Python自带的xml.etree.ElementTree模块就能轻松搞定子节点提取啦,不用装额外库,特别适合入门。我给你一步步拆解怎么操作:
首先,先把你的XML数据整理成字符串变量(方便后续操作),假设你的XML存在xml_str里:
import xml.etree.ElementTree as ET # 补全了新加坡部分的闭合标签,保证XML格式合法 xml_str = '''<?xml version="1.0"?> <data> <country name="Liechtenstein"> <rank>1</rank> <year>2008</year> <gdppc>141100</gdppc> <neighbor name="Austria" direction="E"/> <neighbor name="Switzerland" direction="W"/> </country> <country name="Singapore"> <rank>4</rank> <year>2011</year> <gdppc>59900</gdppc> </country> </data>''' # 解析XML字符串,得到根节点<data> root = ET.fromstring(xml_str)
接下来给你两种常用的提取子节点的方式:
方式1:遍历节点获取所有子节点
如果你想把所有层级的子节点都过一遍,直接嵌套遍历就行:
# 遍历根节点<data>下的所有<country>子节点 for country in root: # 先获取country节点的name属性 country_name = country.attrib['name'] print(f"=== 国家: {country_name} ===") # 遍历当前country下的所有子节点(比如rank、year、gdppc) for child_node in country: print(f"节点名: {child_node.tag}, 内容: {child_node.text}") # 单独处理<neighbor>这种带属性的自闭合节点 neighbor_nodes = country.findall('neighbor') for neighbor in neighbor_nodes: print(f"邻国: {neighbor.attrib['name']}, 方向: {neighbor.attrib['direction']}")
运行后就能看到每个国家的所有子节点内容,包括属性信息。
方式2:精准查找特定子节点
如果你不需要全部遍历,只想找某个特定的子节点,可以用find()(找第一个匹配项)或findall()(找所有匹配项),还能结合XPath语法定位:
# 精准查找名为Liechtenstein的国家的rank子节点 liechtenstein_node = root.find(".//country[@name='Liechtenstein']") if liechtenstein_node: rank_text = liechtenstein_node.find('rank').text print(f"Liechtenstein的排名: {rank_text}") # 查找所有国家的year子节点 all_year_nodes = root.findall(".//year") for year_node in all_year_nodes: print(f"年份: {year_node.text}")
这样操作下来,你就能轻松获取XML里的各种子节点内容啦。Python 3.6完全支持这个模块,不用担心版本兼容问题~
内容的提问来源于stack exchange,提问作者Jaycel Cunanan
相关产品推荐
相关产品推荐

