使用Python从RDL中获取数据集和查询数据

2024-09-29 23:29:40 发布

您现在位置:Python中文网/ 问答频道 /正文

今天,我打算使用Python解析ssrsrdl文件(XML),以便收集数据集和查询数据。最近的一个项目让我回溯了各种报告和数据源,目的是整合和清理我们发布的内容。在

我可以使用此脚本创建一个包含以下列的CSV文件: 系统路径|报告文件名|命令类型|命令文本|

虽然不太雅致,但很管用。在

我希望通过这篇文章能够做的是,请那些已经尝试过或者在使用Python进行XML解析方面有经验的专家尝试一下清理它,并提供以下能力:

  • 包括头,这将是XML标记
  • 在列中包含数据集名称
  • 将结果传送到单个文件中

这是我的rdlparser.py“”文件:

import sys, os

from xml.dom import minidom
xmldoc = minidom.parse(sys.argv[1])

content = ""
TargetFile = sys.argv[1].split(".", 1)[0] + ".csv"
numberOfQueryNodes = 0

queryNodes = xmldoc.getElementsByTagName('Query')
numberOfQueryNodes = queryNodes.length -1


while (numberOfQueryNodes > -1):
    content = content + os.path.abspath(sys.argv[1])+ '|'+ sys.argv[1].split(".", 1)[0]+ '|' 
    outputNode = queryNodes.__getitem__(numberOfQueryNodes)
    children = [child for child in outputNode.childNodes if child.nodeType==1]
    numberOfQueryNodes = numberOfQueryNodes - 1
    for node in children:
        if node.firstChild.nodeValue != '\n          ':
            if node.firstChild.nodeValue != 'true':
                content = content + node.firstChild.nodeValue + '|'
    content = content + '\n'

fp = open(TargetFile, 'wb')
fp.write(content)
fp.close()

Tags: 文件数据nodechildif报告sysxml
1条回答
网友
1楼 · 发布于 2024-09-29 23:29:40

我知道您要求使用Python;但我认为Powershell内置的xml处理功能会使这一点变得相当简单。虽然我确定它不是大师级的,但我认为它的效果相当不错(以#开头的行是注释):

# The directory to search 
$searchpath = "C:\"

# List all rdl files    from the given search path recusrivley searching sub folders, store results into a variable
$files = gci $searchpath -recurse -filter "*.rdl" | SELECT FullName, DirectoryName, Name 

# for each of the found files pass the folder and file name  and the xml content
$files | % {$Directory = $_.DirectoryName; $Name = $_.Name; [xml](gc $_.FullName)}
            # in the xml content navigate to the the DataSets Element
            | % {$_.Report.DataSets} 
                    # for each query retrieve the Report directory , File Name, DataSource Name, Command Type, Command Text output thwese to a csv file
                    | % {$_.DataSet.Query} | SELECT  @{N="Path";E={$Directory}}, @{N="File";E={$Name}}, DataSourceName, CommandType, CommandText | Export-Csv Test.csv -notype   

相关问题 更多 >

    热门问题