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

XML API查询结果保存异常:首尾标签格式错误致无法跨文件处理

Fixing Your Deutsche Bahn API XML Output Format Issue

Hey there! I see the problem with your XML output—those extra < at the start and /> at the end are happening because you're not parsing the API response correctly into an ElementTree object. Let me break this down and fix it for you.

What's Going Wrong?

Your line root = ET.Element(data.text) is taking the entire XML string from the API and treating it as the name of a single XML element. That's why you end up with a malformed element like <[full XML text]/> instead of properly structured XML.

Corrected Code

Here's the fixed version of your script, with comments explaining the changes:

import requests
import xml.etree.ElementTree as ET

# Your auth header—keep this as is
header = {'Authorization': 'Bearer 9d4e1ef8b563b40f9a8737768a18e64d'}

# Fetch the API response
data = requests.get('https://api.deutschebahn.com/timetables/v1/fchg/8005598', headers=header)

# Check if the request was successful first
if data.status_code == 200:
    # Parse the XML response correctly using fromstring()
    root = ET.fromstring(data.text)
    # Create the ElementTree from the parsed root
    tree = ET.ElementTree(root)
    
    # Optional: Print the parsed XML to verify
    ET.dump(tree)
    
    # Write to file with proper encoding to avoid issues
    tree.write("output.xml", encoding='utf-8', xml_declaration=True)
else:
    print(f"Request failed with status code: {data.status_code}")

Key Changes:

  • ET.fromstring(data.text): This method parses the XML string directly into an ElementTree root node, which is the correct way to handle XML responses.
  • xml_declaration=True: Adds the standard XML declaration (<?xml version='1.0' encoding='utf-8'?>) to the output file, making it fully compliant.
  • Success check: Added a quick check for the 200 status code to handle any API errors gracefully.

Why This Works

Now when you run the script, output.xml will have properly structured XML without the extra characters. You can then read and process this file in other Python scripts using ET.parse("output.xml") without any issues.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 14:52:39