使用ElementTree.write写入XML文件时遇TypeError错误
Hey there, looks like you ran into a common type mismatch issue when trying to save Zillow API's XML byte response to a file with ElementTree. Let's break down why this happens and how to fix it properly.
Why the Error Happens
The core issue is that ElementTree.write() expects to work with parsed XML tree objects (or handle string-based content with proper encoding), but you're passing raw bytes directly. ElementTree's methods aren't designed to write raw byte strings directly without parsing first (or using the right file mode if you skip parsing).
Solution 1: Parse the Byte String First (Recommended for XML Processing)
If you need to work with the XML content (like modifying elements, reading data) before saving, first parse the byte string into an ElementTree object, then write it to the file. This ensures proper XML handling and encoding:
from xml.etree import ElementTree # Your Zillow API XML byte response content = b'<?xml version="1.0" encoding="utf-8"?><Comps:comps xsi:schemaLocation="http://www.zillow.com/static/xsd/Comps.xsd https://www.zillowstatic.com/vstatic/b20c067/static/xsd/Comps.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:Comps="http://www.zillow.com/static/xsd/Comps.xsd"></Comps:comps>' # Step 1: Parse the byte string into an ElementTree root node # fromstring() automatically handles decoding using the XML declaration's encoding root = ElementTree.fromstring(content) tree = ElementTree.ElementTree(root) # Step 2: Write the parsed tree to a file with correct encoding tree.write('zillow_comps.xml', encoding='utf-8', xml_declaration=True)
Key Notes:
ElementTree.fromstring()acceptsbytesdirectly and decodes it using the encoding specified in the XML declaration (utf-8in your case).- Setting
xml_declaration=Trueensures the output file includes the proper<?xml version="1.0" encoding="utf-8"?>header, matching the original response.
Solution 2: Write Raw Bytes Directly (For Saving Only)
If you don't need to parse or modify the XML and just want to save the exact byte response from the API, skip ElementTree entirely and write directly to the file in binary mode:
content = b'<?xml version="1.0" encoding="utf-8"?><Comps:comps xsi:schemaLocation="http://www.zillow.com/static/xsd/Comps.xsd https://www.zillowstatic.com/vstatic/b20c067/static/xsd/Comps.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:Comps="http://www.zillow.com/static/xsd/Comps.xsd"></Comps:comps>' # Open file in binary write mode and dump the bytes with open('zillow_comps.xml', 'wb') as f: f.write(content)
This is faster and simpler when you just need to archive the raw API response without processing it.
内容的提问来源于stack exchange,提问作者Kurt Peek

