首页 > 编程问答 >需要帮助来提取此 XML 节点 - Python 中的 Excel 连接字符串

需要帮助来提取此 XML 节点 - Python 中的 Excel 连接字符串

时间:2024-07-25 13:33:01浏览次数:8  
标签:python excel xml

我有一个 Python 程序,打开 Excel (XLSX) 文件,并尝试查找 <connection> 节点。

这是 connections.xml 文件中的完整 XML。

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<connections 
    xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    mc:Ignorable="xr16" 
    xmlns:xr16="http://schemas.microsoft.com/office/spreadsheetml/2017/revision16">
    <connection 
        id="1" xr16:uid="{#####}" keepAlive="1" 
        name="Query - CargoData_small" 
        description="Connection to the 'CargoData_small' query in the workbook." 
        type="5" refreshedVersion="7" background="1">
        <dbPr connection="Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=CargoData_small;Extended Properties=&quot;&quot;" 
            command="SELECT * FROM [CargoData_small]"/>
    </connection>
</connections>

我正在尝试查找 <dbPr> 节点。 ||节点。但我被困在代码的子节点上,如下所示:

def checkfile(filename):
    if zipfile.is_zipfile(filename):
        zf = zipfile.ZipFile(filename, 'r')
        if "xl/connections.xml" in zf.namelist():
            print(filename)
            xml = zf.read('xl/connections.xml')
            root = parseString(xml)
            connections = root.getElementsByTagName('connection')
            try:
                for con in connections:
                    for child in con.childNodes:

                        # there are no 'children'
                        for children in child.childNodes:
                            dsn = children.attributes.values()[0].nodeValue
                            sql = children.attributes.values()[1].nodeValue
                            writeoutput(filename, dsn, sql )
            except:
                pass

所以发生的情况是我得到了“child”值,但我找不到 dbPr 部分。

这就是我收到的错误:

{TypeError}TypeError("'dict_values' object is not subscriptable")

我使用 Pycharm 作为 IDE。

谢谢


以下是使用 Python 提取 Excel 连接字符串的改进方法:

import zipfile
from xml.dom.minidom import parseString

def checkfile(filename):
    if zipfile.is_zipfile(filename):
        with zipfile.ZipFile(filename, 'r') as zf:
            if "xl/connections.xml" in zf.namelist():
                print(filename)
                xml = zf.read('xl/connections.xml')
                root = parseString(xml)
                connections = root.getElementsByTagName('connection')
                for con in connections:
                    dbpr = con.getElementsByTagName('dbPr')[0]
                    dsn = dbpr.getAttribute('connection')
                    sql = dbpr.getAttribute('command')
                    writeoutput(filename, dsn, sql)

def writeoutput(filename, dsn, sql):
    # 根据需要处理提取的信息
    print(f"文件:{filename}")
    print(f"DSN:{dsn}")
    print(f"SQL:{sql}")
    print("-" * 20)

# 示例用法
checkfile("your_excel_file.xlsx") 

说明:

  1. 直接访问 dbPr 代码现在直接使用 con.getElementsByTagName('dbPr')[0] 获取 dbPr 元素,而不是循环遍历所有子节点。这会查找 con 元素(即当前 connection 元素)内的 dbPr 元素,并选择第一个(也是唯一一个)匹配项。

  2. 使用 getAttribute 我们使用 getAttribute 方法来直接检索 connection command 属性的值,而不是尝试从 attributes 对象中获取它们。

  3. 错误处理: 虽然代码中没有显式处理 dbPr 元素不存在的情况,但如果预期某些文件可能没有连接信息,则应添加错误处理。

通过这些更改,代码应该能够有效地提取 Excel 连接字符串并避免之前的错误。

标签:python,excel,xml
From: 78791591

相关文章