Python 2.7 XML节点复制至新文件无数据问题求助
Hey there! Let's dig into why your test.xml is coming up empty. Since you're new to working with XML and Python, I'll walk through the most common issues that cause this, plus ask for a few details to zero in on the exact problem.
1. You forgot to write the XML tree to disk
Most Python XML libraries (like xml.etree.ElementTree or xml.dom.minidom) don't automatically save changes to a file. You have to explicitly write your modified tree out. For example, if you're using ElementTree:
# After building/modifying your target XML tree, you need this line tree.write('test.xml')
Skip this step, and your file will stay empty (or retain its original empty state).
2. Your code isn't finding any records to move
Maybe your logic for selecting records is targeting the wrong elements. XML tags are case-sensitive, so if your source has <Record> but your code looks for <record>, it won't pick anything up.
Quick check: Add a print statement to see how many records your code is finding. For example:
records = source_root.findall('.//record') print(f"Found {len(records)} records") # If this outputs 0, that's your issue
Double-check that your tag names, XPath queries, or loop logic match your source XML's structure exactly.
3. You're not adding records to the target XML tree
If you're creating a fresh root element for your target file, you need to actually append the extracted records to it. It's easy to miss this step! For example:
import xml.etree.ElementTree as ET # Set up target tree target_root = ET.Element('target_root') target_tree = ET.ElementTree(target_root) # Extract a record from source record = source_root.find('.//record') # Don't forget this line! Without it, target_root stays empty target_root.append(record)
4. You're moving elements instead of copying them
When transferring elements from the source to target tree, some parsers treat elements as tied to their original tree. If you just remove an element from the source and don't explicitly copy it to the target, it might not show up. Use copy.deepcopy() to fix this:
import copy # Copy the record instead of moving it directly target_root.append(copy.deepcopy(record))
5. File path or permission issues
It's possible your code is writing test.xml to a directory you don't expect, or you don't have write permissions there. Verify the full path with this snippet:
import os print(os.path.abspath('test.xml'))
Check that location — if the file exists but is empty, permissions might be blocking writes (though you'd usually get an error for this, it's worth ruling out).
To help me help you faster, could you share:
- A tiny sample of your source XML structure (just a couple of records)
- The expected structure of your target XML
- The key parts of your Python code (traversal, record selection, and file writing sections)
内容的提问来源于stack exchange,提问作者FutureCake

