我使用 Python 自动化 XML 字段检查的那一天

王林
发布: 2024-08-15 06:35:37
原创
475 人浏览过

The Day I Automated XML Field Checking with Python

这一切都始于我接受检查多个 XML 文件是否缺少字段的任务。在我们继续下一步之前,团队需要确保这些文件中存在所有必填字段。听起来很简单,对吧?嗯,不完全是。

我打开了第一个 XML 文件,扫描了属性,手动查找所需字段,然后勾选了相应的框。正如你所预料的那样,很快就会感到疲倦。在一个文件中只看了几分钟后,我的眼睛变得呆滞,我没有真正的信心我没有错过一些重要的事情。我的意思是,XML 可能非常挑剔,单个缺失字段可能会导致严重问题。

我有一种令人痛苦的恐惧感,因为我知道我还有一堆文件需要处理。当然,准确性至关重要——一个被忽视的缺失字段可能会带来灾难。因此,经过几次深呼吸和思考片刻后,我决定必须有更好的方法来解决这个问题。

顿悟:自动化来救援

作为一名程序员,我有一个想法:为什么不写一个脚本来为我完成这项单调的工作呢?我可以将其自动化并保证准确性,同时在过程中保持理智,而不是手动检查每个字段。是时候利用 Python 的力量了。

概念很简单:

  • 我将必填字段的列表存储在 JSON 文件中,这使得脚本具有高度的可重用性和适应性。通过使用这种方法,脚本可以轻松处理其他 XML 文件,甚至是那些具有不同结构的文件。您只需使用任何新 XML 格式的所需字段更新 JSON 文件,即可让脚本自动调整为不同的 XML 架构而无需修改。
  • 我需要编写一个 Python 脚本来遍历每个 XML 文件,检查是否缺少任何必填字段,然后输出摘要。

这样,我可以轻松识别每个文件中缺少某个字段的次数、存在多少个属性,并获得清晰的报告 - 不再需要无休止的手动检查,不再出现错误。这是我的做法。

编写实用程序脚本

首先,我需要加载必填字段的列表。这些存储在 key required_fields 下的 JSON 文件中,因此我编写了一个函数来读取此文件:

import os
import json
import xml.etree.ElementTree as ET

def load_required_fields(json_file_path):
    with open(json_file_path, 'r') as file:
        data = json.load(file)
        return data.get("required_fields", [])
登录后复制

然后真正的魔法来了。我编写了一个函数来解析每个 XML 文件,循环遍历其属性,并检查每个必填字段是否存在:

def check_missing_fields(file_path, required_fields):
    # Load the XML file
    tree = ET.parse(file_path)
    root = tree.getroot()

    # Initialize variables to store counts and track missing fields
    total_properties = 0
    missing_fields_counts = {field: 0 for field in required_fields}

    # Loop through each property to check for missing fields
    for property in root.findall('.//property'):
        total_properties += 1
        for field in required_fields:
            # Use the find() method to look for direct children of the property element
            element = property.find(f'./{field}')
            # Check if the field is completely missing (not present)
            if element is None:
                missing_fields_counts[field] += 1

    # Print the results
    print('-----------------------------------------')
    print(f'File: {os.path.basename(file_path)}')
    print(f'Total number of properties: {total_properties}')
    print('Number of properties missing each field:')
    for field, count in missing_fields_counts.items():
        print(f'  {field}: {count} properties')
    print('-----------------------------------------')
登录后复制

此函数加载 XML 文件,计算属性数量,并跟踪每个必填字段缺少多少属性。该函数打印出一份报告,显示每个处理文件的结果。

最后,我将所有内容放在 main() 函数中。它将迭代指定目录中的所有 XML 文件并对每个文件运行字段检查函数:

def main():
    # Directory containing XML files
    xml_dir = 'xmls'
    json_file_path = 'required_fields.json'

    # Load required fields from JSON file
    required_fields = load_required_fields(json_file_path)

    # Iterate over each file in the xmls directory
    for file_name in os.listdir(xml_dir):
        if file_name.endswith('.xml'):
            file_path = os.path.join(xml_dir, file_name)
            check_missing_fields(file_path, required_fields)

if __name__ == "__main__":
    main()
登录后复制

运行该过程后,您将收到与此类似的结果摘要:

File: properties.xml
Total number of properties: 4170
Number of properties missing each field:
  Title: 0 properties
  Unit_Number: 0 properties
  Type: 0 properties
  Bedrooms: 0 properties
  Bathrooms: 0 properties
  Project: 0 properties
  Price: 0 properties
  VAT: 0 properties
  Status: 10 properties
  Area: 0 properties
  Location: 100 properties
  Latitude: 30 properties
  Longitude: 0 properties
  Apartment_Floor: 0 properties
  Block: 0 properties
  Phase: 0 properties
  Construction_Stage: 0 properties
  Plot_Size: 0 properties
  Yard: 120 properties
  Description: 0 properties
  gallery: 27 properties
登录后复制

结果:保持理智

一切准备就绪后,我就在 XML 文件目录上运行脚本。输出正是我所需要的:一个简洁的摘要,显示每个文件中有多少属性缺少哪些字段,以及每个 XML 中的属性总数。

我无需花费数小时手动检查每个文件,而是在几秒钟内得到答案。该脚本捕获了几个丢失的字段,如果我继续手动路线,我可能会忽略这些字段。

经验教训

  1. 自动化是救星:每当您面临重复性任务时,请考虑如何将它们自动化。它不仅可以节省您的时间,还可以降低人为错误的风险。
  2. 准确性很重要:在这种情况下,准确性至关重要。像我写的这样一个简单的脚本可以确保您不会忽略任何事情,这在处理关键数据时尤其重要。
  3. 利用你的编程技能:有时,我们会陷入手动做事的困境,即使我们有能力让我们的生活更轻松。花点时间退一步问自己,“有没有更有效的方法来做到这一点?”

最终,一开始令人厌烦且容易出错的任务变成了一次有益的体验。现在,每当我接到感觉乏味或容易出错的任务时,我都会提醒自己脚本和自动化的力量。我想知道接下来我还可以简化多少其他任务......

您可以通过克隆我创建的 XML Checker 存储库来快速开始这种自动化。这将为您提供所需的一切,包括脚本和示例文件。从那里,您将能够自己运行自动化,对其进行自定义以满足您的需求或进一步扩展其功能。

享受吧!

以上是我使用 Python 自动化 XML 字段检查的那一天的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!