如何将XML格式数据读取为键值对格式并提取子节点键值
将XML子节点转为键值对列表
原始XML内容
<note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> <example></example> </note>
实现代码(Python)
import xml.etree.ElementTree as ET # 解析目标XML内容 xml_content = """ <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> <example></example> </note> """ root = ET.fromstring(xml_content) # 遍历子节点生成键值对列表 result = [] for child in root: # 处理空节点的文本,将None转为空字符串 text = child.text.strip() if child.text is not None else "" result.append([child.tag, text]) # 输出指定格式的结果 print(result)
运行结果
[['to', 'Tove'], ['from', 'Jani'], ['heading', 'Reminder'], ['body', "Don't forget me this weekend!"], ['example', '']]
说明
- 自动跳过根节点
<note>,仅处理其直接子节点 - 空节点
<example>的文本会被转为空字符串,完全匹配需求格式
内容的提问来源于stack exchange,提问作者john
相关产品推荐
相关产品推荐

