Python将SOAP API返回的XML转换为CSV时仅显示表头无数据如何解决
问题原因
- 未处理XML命名空间:你的XML中
Level2及内部所有子节点都归属https://xxxxxxxxxx/xxxxxxx自定义命名空间,直接使用标签名搜索无法匹配到对应节点 - 节点遍历路径错误:你需要提取的
Date等字段均嵌套在Envelope/Body/Level2/Level3/VIP/MainVIP路径下,原代码直接遍历根节点的第一层子节点,完全没有深入到目标层级 - 方法调用错误:
Element.get()是用于读取节点属性的方法,你需要获取的是子节点的文本内容,不能使用该方法
修正后代码
import xml.etree.ElementTree as ET import pandas as pd cols = ['Date', 'RegisteredDate', 'Type', 'TypeDescription'] rows = [] # 解析XML xmlparse = ET.parse('xmldata.xml') root = xmlparse.getroot() # 定义命名空间映射 ns = { 'soap': 'http://schemas.xmlsoap.org/soap/envelope/', 'custom': 'https://xxxxxxxxxx/xxxxxxx' } # 定位到MainVIP节点,如果有多个MainVIP可以改用findall遍历 main_vip = root.find('./soap:Body/custom:Level2/custom:Level3/custom:VIP/custom:MainVIP', ns) if main_vip: # 提取对应字段值,空节点默认返回空字符串避免报错 Date = main_vip.find('custom:Date', ns).text if main_vip.find('custom:Date', ns) is not None else '' RegisteredDate = main_vip.find('custom:RegisteredDate', ns).text if main_vip.find('custom:RegisteredDate', ns) is not None else '' Type = main_vip.find('custom:Type', ns).text if main_vip.find('custom:Type', ns) is not None else '' TypeDescription = main_vip.find('custom:TypeDescription', ns).text if main_vip.find('custom:TypeDescription', ns) is not None else '' rows.append({ 'Date': Date, 'RegisteredDate': RegisteredDate, 'Type': Type, 'TypeDescription': TypeDescription }) df = pd.DataFrame(rows, columns=cols) print(df) df.to_csv('csvdata.csv', index=False)
如果你的实际返回结果中存在多个MainVIP节点,将find替换为findall后遍历所有匹配节点即可批量提取数据。
内容的提问来源于stack exchange,提问作者M v a n o
相关产品推荐
相关产品推荐

