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

如何使用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/Auditing as the default namespace. We extract this from the root element's tag and use it in our findall and find calls to correctly target elements.
  • Graceful Missing Elements: The code checks if each element exists before accessing its .text property, using 'N/A' as a fallback if an element is missing (you can adjust this fallback value as needed).
  • Encoding: We use utf-8 encoding for both reading the XML and writing the CSV to handle any special characters in your logs.

How to Use:

  1. Save your XML content as file.xml in the same directory as the script.
  2. Run the script—this will generate activity_logs.csv with your parsed data.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:39:21