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

Python使用ElementTree解析XML 提取connectionStrings标签指定值

XML配置文件连接信息提取方案

目标需求

从XML配置文件的connectionStrings节点中,提取所有数据库配置的三类信息:

  • 配置项name属性值
  • 连接字符串内的User ID字段值
  • 连接字符串内的Password字段值

目标XML结构示例:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <configSections>
        |
        |
   </configSections>
   <connectionStrings>
        <clear />
        <add name="Database1" connectionString="DataSource=[ServerName];Initial Catalog=[DatabaseName]; User ID=user2;Password=oogabooga1" providerName="Database1provider"/>
        <add name="Database12" connectionString="DataSource=[ServerName];Initial Catalog=[DatabaseName]; User ID=user1;Password=oogabooga2" providerName="Database2provider"/>

   </connectionStrings>
</configuration>

原有代码问题

原有代码存在4处错误,导致无法正确提取数据:

  • 导入模块别名不匹配:导入时写import xml.etree.ElementTree as ET,解析时却调用etree.parse
  • 遍历语法错误:Python遍历语法为for 变量 in 可迭代对象,原代码写为from elem in ...
  • 节点定位逻辑错误:ET.parse()返回的是文档树对象,调用getroot()拿到的根节点本身就是<configuration>标签,不需要额外查找
  • 取值逻辑错误:目标数据存储在<add>标签的属性中,不是标签的text文本内容,且User ID、Password是connectionString属性值内的嵌套键值对,需要拆分字符串提取

可直接运行的实现代码

import xml.etree.ElementTree as ET

# 替换为你的XML文件实际存储路径
filepath = "web.config"
# 解析XML文档获取根节点
tree = ET.parse(filepath)
root = tree.getroot()

# 遍历connectionStrings节点下所有add配置项
for add_node in root.findall("connectionStrings/add"):
    # 直接读取name属性
    config_name = add_node.get("name")
    conn_str = add_node.get("connectionString")
    
    uid = None
    pwd = None
    # 拆分连接字符串提取账号密码
    for item in conn_str.split(";"):
        item = item.strip()
        if not item:
            continue
        # 按第一个等号拆分,兼容值中包含等号的场景
        key, val = item.split("=", 1)
        key = key.strip()
        if key == "User ID":
            uid = val.strip()
        elif key == "Password":
            pwd = val.strip()
    
    print(f"配置名称:{config_name} | 用户ID:{uid} | 密码:{pwd}")

运行结果

针对示例XML,代码运行输出如下:

配置名称:Database1 | 用户ID:user2 | 密码:oogabooga1
配置名称:Database12 | 用户ID:user1 | 密码:oogabooga2

内容的提问来源于stack exchange,提问作者Jeremy Lin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 15:48:44