如何使用Python实现XML转CSV?附状态XML数据示例
Python Solution to Convert XML Activity Logs to CSV
Since your XML uses a default namespace, we need to account for that when parsing—otherwise, we won't be able to locate the ActivityRecord elements and their children. Below is a complete, self-contained solution using Python's built-in xml.etree.ElementTree and csv modules (no external dependencies needed):
import xml.etree.ElementTree as ET import csv # Parse the XML file tree = ET.parse('file.xml') root = tree.getroot() # Extract the default namespace from the root element namespace = root.tag.split('}')[0][1:] ns = {'ns': namespace} # Define the CSV columns we want to extract csv_columns = ['time', 'oper'] # Open the output CSV file for writing with open('activity_logs.csv', 'w', newline='', encoding='utf-8') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=csv_columns) writer.writeheader() # Iterate over each ActivityRecord in the XML for record in root.findall('ns:ActivityRecord', ns): # Extract the values (handle missing elements gracefully with a fallback) log_entry = { 'time': record.find('ns:time', ns).text if record.find('ns:time', ns) is not None else 'N/A', 'oper': record.find('ns:oper', ns).text if record.find('ns:oper', ns) is not None else 'N/A' } writer.writerow(log_entry) print("Conversion complete! CSV saved as activity_logs.csv")
Key Details:
- Namespace Handling: The XML uses
http://www.cisco.com/PowerKEYDVB/Auditingas the default namespace. We extract this from the root element's tag and use it in ourfindallandfindcalls to correctly target elements. - Graceful Missing Elements: The code checks if each element exists before accessing its
.textproperty, using'N/A'as a fallback if an element is missing (you can adjust this fallback value as needed). - Encoding: We use
utf-8encoding for both reading the XML and writing the CSV to handle any special characters in your logs.
How to Use:
- Save your XML content as
file.xmlin the same directory as the script. - Run the script—this will generate
activity_logs.csvwith your parsed data.
内容的提问来源于stack exchange,提问作者Nipun khanna
相关产品推荐
相关产品推荐

