Python 代码从 XML 文件读取但找不到任何内容

问题描述 投票:0回答:1

我是一名学生,我想做一个项目,读取 XML 文件并将信息写入 MySQL 数据库(本地主机)。

表格是这样的:

CREATE TABLE ClimateMonitoring (
    id INT PRIMARY KEY,
    name VARCHAR(255),
    label VARCHAR(255),
    value_type INT,
    offset FLOAT,
    gain FLOAT,
    precision_level INT,
    value VARCHAR(255),
    unit VARCHAR(50),
    sensor_date DATETIME,
    insert_date DATETIME DEFAULT CURRENT_TIMESTAMP
);

代码是这样的:

from lxml import etree
import mysql.connector

def parse_and_insert_to_mysql(file_path, db_config):
    conn = None
    cursor = None
    data_found = False
    try:
        # Parse the XML file using lxml
        print("Parsing XML file using lxml...")
        tree = etree.parse(file_path)
        root = tree.getroot()
        print("XML file parsed successfully.")
        
        # Print the root tag to verify successful parsing
        print(f"Root tag: {root.tag}")

        # Define the namespace
        namespace = {'icom': 'something'}

        # Connect to the MySQL database
        print("Connecting to MySQL database...")
        conn = mysql.connector.connect(**db_config)
        cursor = conn.cursor()
        print("Connected to MySQL database.")

        # Extract data and insert into the database
        for item in root.findall('icom:Item', namespaces=namespace):
            data_found = True  # Set flag to true if at least one item is found
            item_id = item.attrib['id']
            name = item.attrib['name']
            label = item.find('icom:Label', namespaces=namespace).text
            value_element = item.find('icom:Value', namespaces=namespace)
            value_type = value_element.attrib['valueType']
            offset = value_element.attrib['offset']
            gain = value_element.attrib['gain']
            precision_level = value_element.attrib['precision']
            value = value_element.text
            unit = item.find('icom:Unit', namespaces=namespace).text if item.find('icom:Unit', namespaces=namespace) is not None else ''
            sensor_date = '2024-10-05 00:00:00'

            # Debugging: Print each value to verify correctness
            print(f"Preparing to insert: id={item_id}, name={name}, label={label}, value_type={value_type}, offset={offset}, gain={gain}, precision_level={precision_level}, value={value}, unit={unit}, sensor_date={sensor_date}")

            insert_query = (
                "INSERT INTO ClimateMonitoring (id, name, label, value_type, offset, gain, precision_level, value, unit, sensor_date) "
                "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
            )
            try:
                cursor.execute(insert_query, (item_id, name, label, value_type, offset, gain, precision_level, value, unit, sensor_date))
                print(f"Inserted row with id={item_id}")
            except mysql.connector.Error as e:
                print(f"Failed to insert row with id={item_id}: {e}")
            except Exception as e:
                print(f"Unexpected error when inserting row with id={item_id}: {e}")

        # Check if no data was found
        if not data_found:
            raise ValueError("No insertable data found in the XML file.")

        # Commit the transaction
        print("Committing transaction...")
        conn.commit()
        print("Transaction committed successfully.")

    except etree.XMLSyntaxError as e:
        print(f"Error parsing the XML file: {e}")
    except mysql.connector.Error as e:
        print(f"Error with MySQL database: {e}")
    except ValueError as e:
        print(e)
    except Exception as e:
        print(f"An error occurred: {e}")
    finally:
        # Close the database connection
        if cursor:
            cursor.close()
        if conn:
            conn.close()
        print("Database connection closed.")

# Path to your XML file
file_path = r"path"

# MySQL database configuration
db_config = {
    'user': 'root',
    'password': 'password',  # The password you set during installation
    'host': 'localhost',     # Localhost
    'database': 'climate'  # The database you created
}

parse_and_insert_to_mysql(file_path, db_config)

XML文件是这样的:

<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="/simon.xsl" ?>
<icom:something schemaVersion="1.00" appVersion="1" xmlns:icom="a1234">
<Item id="354" name="SinglState">
<Label>Unit Status</Label>
<Value valueType="262144" offset="0.000" gain="1.000" precision="0">Unit On</Value>
<Unit></Unit>
</Item>
<Item id="361" name="LocTemp">
<Label>Return Air Temperature</Label>
<Value valueType="393216" offset="0.000" gain="1.000" precision="1">22.1</Value>
<Unit>&#176;C</Unit>
</Item>
<Item id="379" name="Std. Sensor Humidity">
<Label>Return Air Humidity</Label>
<Value valueType="393216" offset="0.000" gain="1.000" precision="1">35.1</Value>
<Unit>%rH</Unit>
</Item>
<Item id="380" name="Supply Air Temperature">
<Label>Supply Air Temperature</Label>
<Value valueType="393216" offset="0.000" gain="1.000" precision="1">---</Value>
<Unit></Unit>
</Item>
<Item id="356" name="Actual Temperature Setpoint">
<Label>Return Air Temperature Setpoint</Label>
<Value valueType="393216" offset="0.000" gain="1.000" precision="1">21.5</Value>
<Unit>&#176;C</Unit>
</Item>
<Item id="547" name="HuSetActDi">
<Label>Return Air Humidity Setpoint</Label>
<Value valueType="393216" offset="0.000" gain="1.000" precision="0">No</Value>
<Unit></Unit>
</Item>
<Item id="401" name="Supply Setpoint">
<Label>Supply Air Temperature Setpoint</Label>
<Value valueType="393216" offset="0.000" gain="1.000" precision="1">5.0</Value>
<Unit>&#176;C</Unit>
</Item>
<Item id="1110" name="Show_Fan">
<Label>Fan Status</Label>
<Value valueType="0" offset="0.000" gain="1.000" precision="0">On</Value>
<Unit></Unit>
</Item>
<Item id="1111" name="Show_Cool">
<Label>Cooling Status</Label>
<Value valueType="0" offset="0.000" gain="1.000" precision="0">On</Value>
<Unit></Unit>
</Item>
<Item id="1112" name="Show_FC">
<Label>Freecooling Status</Label>
<Value valueType="0" offset="0.000" gain="1.000" precision="0">Off</Value>
<Unit></Unit>
</Item>
<Item id="1114" name="Show_EHeat">
<Label>Electrical Heater Status</Label>
<Value valueType="0" offset="0.000" gain="1.000" precision="0">Off</Value>
<Unit></Unit>
</Item>
<Item id="1113" name="Show_HotW">
<Label>Hot Water Status</Label>
<Value valueType="0" offset="0.000" gain="1.000" precision="0">Off</Value>
<Unit></Unit>
</Item>
<Item id="1116" name="Show_Dehum">
<Label>Dehumdification Status</Label>
<Value valueType="0" offset="0.000" gain="1.000" precision="0">Off</Value>
<Unit></Unit>
</Item>
<Item id="1115" name="Show_Hum">
<Label>Humidifier Status</Label>
<Value valueType="0" offset="0.000" gain="1.000" precision="0">Off</Value>
<Unit></Unit>
</Item>
<Item id="1118" name="Show_Maint">
<Label>Maintenance Status</Label>
<Value valueType="0" offset="0.000" gain="1.000" precision="0">Off</Value>
<Unit></Unit>
</Item>
</icom:something>

代码无法读取任何可插入的信息。

我尝试过代码是否无法连接到数据库但可以连接。它没有提供在 XML 文件中找到的可插入数据。我需要它来用这些信息填充表格。

xml xml-parsing mysql-python
1个回答
0
投票

XML 具有名称空间声明

xmlns:icom="a1234"
,因此您的 Python 名称空间字典应该是例如
namespace = {'icom': 'a1234'}

此外,大多数后代元素都不在命名空间中,因此请使用例如

item.find('Label', ..)
而不是
item.find('icom:Label', ..)

© www.soinside.com 2019 - 2024. All rights reserved.