Saxon、XSLT:处理复杂树结构中的数千个 xml 文件

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

我使用 python 脚本迭代复杂的树结构中的数千个 xml 文件,并执行以下 Saxon 命令:

java -cp C:\saxon\SaxonHE10-6J\saxon-he-10.6.jar net.sf.saxon.Transform -t -s:{input} -xsl:{xslt} -o:{output}

我的最终输出是一个txt文件;每一行对应一个 xml 文件,并且是从中选择的 xml 元素值。

这运行良好,但性能非常低。我想这是因为每次迭代中处理新的 xml 文件时,我的 python 脚本都会调用 Saxon 命令。

如果可能的话,加速这一过程的正确方法是什么?

亲切的问候。

摘自python文件:

for root, dirs, files in os.walk(folderXmlSource):

    for file in files:
        if file.endswith('.xml'):
            input = '"\\\\?\\' + str(os.path.join(root, file)) + '"'
            output = '"' + os.path.join(folderTxtTemp, file[:-4] + '.txt') + '"'
            try:
                transform(input, output)
                print(input, 'jjjjj', output)
                finalize(output)
            except:
                errorLog.write(input + '\n')

transform
函数调用 Saxon 并处理 XSLT 转换。
finalize
函数将每个 xml 文件的 XSLT 转换获得的所有结果连接到最终结果文件中。

XSL 文件摘录:

<!--  //System:FileName  -->

    <xsl:variable name="System:FileName">
        <xsl:choose>
            <xsl:when test="//System:FileName">
                <xsl:choose>
                    <xsl:when test="//System:FileName !=''">
                        <xsl:value-of select="//System:FileName"/>
                    </xsl:when>
                    <xsl:otherwise>
                        <xsl:text>System:FileName VIDE</xsl:text>
                    </xsl:otherwise>
                </xsl:choose>
            </xsl:when>
            <xsl:otherwise>
                <xsl:text>System:FileName ABSENT</xsl:text>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:variable>

XSL 文件查找特定元素,例如

System:FileName
。如果该元素存在,则将其值放入变量中。然后将从不同元素获得的所有变量内容连接到一个 txt 文件中。

python xml xslt saxon
1个回答
0
投票

我建议尝试使用 SaxonC 12(例如使用 PyPi 包 saxonche)并将 Python 代码更改为例如

from saxonche import PySaxonProcessor

def transform(saxon_proc, xslt30_executable, input, output):
    xdm_input = saxon_proc.parse_xml(xml_file_name=input)
    xslt30_executable.set_global_context_item(xdm_item=xdm_input)
    xslt30_executable.apply_templates_returning_file(xdm_value=xdm_input, output_file=output)


with PySaxonProcessor() as saxon_proc:
    xslt30_processor = saxon_proc.new_xslt30_processor()
    xslt30_executable = xslt30_processor.compile_stylesheet(stylesheet_file='yourXsltStylesheet.xsl')

    for file in files:
        if file.endswith('.xml'):
            input = '"\\\\?\\' + str(os.path.join(root, file)) + '"'
            output = '"' + os.path.join(folderTxtTemp, file[:-4] + '.txt') + '"'
            try:
                transform(saxon_proc, xslt30_executable, input, output)
                print(input, 'jjjjj', output)
                finalize(output)
            except:
                errorLog.write(input + '\n')`

看看仅此一项是否已经带来性能的显着提升。

然后,您还可以考虑使用 Python 和 SaxonC 的多线程,如 https://github.com/martin-honnen/SaxonC12ThreadPoolExecutorXSLTTransformation 中所做的那样,以进一步提高性能。

接下来我将研究 XSLT 以及是否可以将所有任务委托给单个 XSLT。

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