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

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

我今天打算使用 Python 解析 SSRS RDL 文件 (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()
python xml reporting-services rdl minidom
1个回答
0
投票

我知道你问的是 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   
© www.soinside.com 2019 - 2024. All rights reserved.