如何使文本更快地转换为XML?

如何解决如何使文本更快地转换为XML?

我有一个关于如何使XSLT脚本更快的问题。输入是一个文本文件,其时间测量如下:

67235 | 8 | ecus | Started | ecus
67306 | 2 | step1 | Started | ecus/step1
67384 | 2 | step7 | Started | ecus/step1/step7
67387 | 2 | step28 | Started | ecus/step1/step2/step28
67413 | 28 | step28 | Stopped | ecus/step1/step2/step28
67416 | 3 | step14 | Started | ecus/step1/step2/step14
67431 | 2 | step19 | Started | ecus/step1/step2/step14/step19
67786 | 357 | step19 | Stopped | ecus/step1/step2/step14/step19
67789 | 3 | step57 | Started | ecus/step1/step2/step14/step57
67801 | 15 | step57 | Stopped | ecus/step1/step2/step14/step57
67804 | 2 | step8 | Started | ecus/step1/step2/step14/step8
67805 | 3 | step8 | Stopped | ecus/step1/step2/step14/step8
67807 | 2 | step9 | Started | ecus/step1/step2/step14/step9
67808 | 3 | step9 | Stopped | ecus/step1/step2/step14/step9
67811 | 3 | step12 | Started | ecus/step1/step2/step14/step12
67820 | 12 | step12 | Stopped | ecus/step1/step2/step14/step12
67823 | 2 | step13 | Started | ecus/step1/step2/step14/step13
67824 | 3 | step13 | Stopped | ecus/step1/step2/step14/step13
67827 | 3 | step15 | Started | ecus/step1/step2/step14/step15
69235 | 1411 | step15 | Stopped | ecus/step1/step2/step14/step15
69238 | 3 | step16 | Started | ecus/step1/step2/step14/step16
69238 | 3 | step16 | Stopped | ecus/step1/step2/step14/step16
69241 | 2 | step18 | Started | ecus/step1/step2/step14/step18
69373 | 134 | step18 | Stopped | ecus/step1/step2/step14/step18
69404 | 2 | step30 | Started | ecus/step1/step2/step14/step30
69722 | 320 | step30 | Stopped | ecus/step1/step2/step14/step30
69736 | 3 | step31 | Started | ecus/step1/step2/step14/step31

[...]

我有一个XSLT模板,可以分两步转换此数据。第一步是从文本创建一个“扁平的” XML结构。输出看起来像这样:

<profile>
  <step ord="1" ts="67235" time="8" info="Started" path="ecus" root="ecus" level="0"/>
  <step ord="2" ts="67306" time="2" info="Started" path="ecus/step1" root="step1" level="1"/>
  <step ord="3" ts="67384" time="2" info="Started" path="ecus/step1/step7" root="step7" level="2"/>
  <step ord="4" ts="67387" time="2" info="Started" path="ecus/step1/step2/step28" root="step28" level="3"/>
  <step ord="5" ts="67413" time="28" info="Stopped" path="ecus/step1/step2/step28" root="step28" level="3"/>
  <step ord="6" ts="67416" time="3" info="Started" path="ecus/step1/step2/step14" root="step14" level="3"/>
  <step ord="7" ts="67431" time="2" info="Started" path="ecus/step1/step2/step14/step19" root="step19" level="4"/>
  <step ord="8" ts="67786" time="357" info="Stopped" path="ecus/step1/step2/step14/step19" root="step19" level="4"/>
  <step ord="9" ts="67789" time="3" info="Started" path="ecus/step1/step2/step14/step57" root="step57" level="4"/>
  <step ord="10" ts="67801" time="15" info="Stopped" path="ecus/step1/step2/step14/step57" root="step57" level="4"/>
  <step ord="11" ts="67804" time="2" info="Started" path=" ecus/step1/step2/step14/step8" root="step8" level="4"/>
  <step ord="12" ts="67805" time="3" info="Stopped" path=" ecus/step1/step2/step14/step8" root="step8" level="4"/>
  <step ord="13" ts="67807" time="2" info="Started" path="ecus/step1/step2/step14/step9" root="step9" level="4"/>
  <step ord="14" ts="67808" time="3" info="Stopped" path="ecus/step1/step2/step14/step9" root="step9" level="4"/>
  <step ord="15" ts="67811" time="3" info="Started" path="ecus/step1/step2/step14/step12" root="step12" level="4"/>
[...]

...第二步,将平面XML转换为XML树,其中path属性值表示为结构:

<?xml version="1.0" encoding="UTF-8"?>
<profile>
   <ecus start="67235" time="3105043">
      <step1 start="67306" time="2363792">
         <step7 start="67384" time="9952">
            <step28 start="67387" time="28"/>
            <step14 start="67416" time="9920">
               <step19 start="67431" time="357"/>
               <step57 start="67789" time="15"/>
               <step8 start="67804" time="3"/>
               <step9 start="67807" time="3"/>
               <step12 start="67811" time="12"/>
               <step13 start="67823" time="3"/>
               <step15 start="67827" time="1411"/>
               <step16 start="69238" time="3"/>
               <step18 start="69241" time="134"/>
               <step30 start="69404" time="320"/>
               <step31 start="69736" time="3"/>
               <step16 start="69736" time="1"/>
               <step29 start="69755" time="35"/>
               <step6 start="69808" time="917">
                  <step20 start="70084" time="641">
                     <step23 start="70099" time="9"/>
                     <step26 start="70114" time="3"/> 
[...]

作为第二步的代码,我正在使用此代码:

<xsl:template match="step" mode="unflatten1">
    <xsl:variable name="start" select="current()"/>
    <xsl:variable name="stop" select="$start/following-sibling::step[@info='Stopped' and @path = $start/@path][1]"/>
    <xsl:element name="{$start/@root}">
        <xsl:attribute name="start" select="$start/@ts"/>
        <xsl:attribute name="time" select="$stop/@time"/>
        <xsl:apply-templates select="key('startedthreads',@level + 1)[number(@ord) &gt; number($start/@ord) and number(@ord) &lt; number($stop/@ord)]" mode="unflatten1"/>
    </xsl:element>
</xsl:template>

工作正常,但使用此模板的性能似乎很差。

我希望使用大约30000行的原始输入文件对步骤2花费1到2秒的时间(请参阅下面的项目链接),但是在第10代i7处理器上,它可持续4到5秒。平台:-/

我的问题:XPath或XSLT中是否存在设置或其他方法或技术(如索引ord或属性的组合)或函数,可以帮助使步骤2的运行速度更快?

您将在此处找到代码:https://gitlab.com/ms452206/socode20200906

解决方法

我已经使用for-each-group group-starting-with/group-ending-with和XSLT 3进行了尝试:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:mf="http://example.com/mf"
    exclude-result-prefixes="#all"
    version="3.0">
    
  <xsl:output indent="yes"/>

  <xsl:mode on-no-match="shallow-copy"/>

  <xsl:function name="mf:group" as="element()*">
      <xsl:param name="steps" as="element()*"/>
      <xsl:param name="level" as="xs:integer"/>
      <xsl:for-each-group
        select="$steps" group-starting-with="step[@level = $level and @info = 'Started']">
          <xsl:variable name="start" select="."/>
          <xsl:for-each-group 
             select="current-group() except ." 
             group-ending-with="step[@level = $level and @info = 'Stopped' and @path = $start/@path]">
             <xsl:variable name="stop" select="current-group()[last()]"/>
          <xsl:element name="{normalize-space($start/@root)}">
              <xsl:attribute name="start" select="$start/@ts"/>
              <xsl:attribute name="time" select="$stop/@time"/>
              <xsl:sequence select="mf:group(current-group()[position() lt last()],$level + 1)"/>
          </xsl:element>              
          </xsl:for-each-group>
      </xsl:for-each-group>
  </xsl:function>

  <xsl:template match="profile">
      <xsl:copy>
          <xsl:sequence
            select="mf:group(step,0)"/>
      </xsl:copy>
  </xsl:template>
  
</xsl:stylesheet>

https://xsltfiddle.liberty-development.net/ehW12g8

在笔记本电脑上对扁平化的XML运行Saxon HE 10.2 Java需要Execution time: 854.9807ms

我认为使用unparsed-text-lines而不是xsl:analyze-string的XSLT / XPath 3的第一步也更容易并且性能更好:

   <xsl:variable name="flatprofile">
            <profile>
                <xsl:choose>
                    <xsl:when test="unparsed-text-available($file,$encoding)">
                        <xsl:variable name="content" select="unparsed-text($file,$encoding)"/>
                        <xsl:for-each select="unparsed-text-lines($file,$encoding)">
                                <step>
                                    <xsl:for-each select="tokenize(.,'\|')">
                                        <xsl:variable name="pos" select="position()"/>
                                        <xsl:choose>
                                            <xsl:when test="$pos = 1">
                                                <xsl:attribute name="ts" select="normalize-space(.)"/>
                                            </xsl:when>
                                            <xsl:when test="$pos = 2">
                                                <xsl:attribute name="time" select="normalize-space(.)"/>
                                            </xsl:when>
                                            <xsl:when test="$pos = 4">
                                                <xsl:attribute name="info" select="normalize-space(.)"/>
                                            </xsl:when>
                                            <xsl:when test="$pos = 5">
                                                <xsl:attribute name="path" select="."/>
                                                <xsl:attribute name="root" select="tokenize(.,'/')[last()]"/>
                                                <xsl:attribute name="level" select="string-length(.) - string-length(translate(.,'/',''))"/>
                                            </xsl:when>
                                        </xsl:choose>
                                    </xsl:for-each>
                                </step>                   
                        </xsl:for-each>
                    </xsl:when>
                    <xsl:otherwise>
                        <xsl:variable name="error">
                            <xsl:text>Error reading "</xsl:text>
                            <xsl:value-of select="$file"/>
                        </xsl:variable>
                        <xsl:message><xsl:value-of select="$error"/></xsl:message>
                        <xsl:value-of select="$error"/>
                    </xsl:otherwise>
                </xsl:choose>
            </profile>
       
    </xsl:variable>

然后,主模板将使用

<xsl:template match="/" name="txt2xml">
    <profile>
        <xsl:sequence select="mf:group($flatprofile/profile/step,0)"/>
    </profile>
</xsl:template>

然后,使用Java 8和Saxon 10.2 HE,我的系统需要1.1或1.2秒来完成整个转换。

为简化整个方法(并希望可以进一步减少所需的时间),我从两步“文本-> XML”和“ XML的递归分组”切换到了一系列光的递归分组纯文本创建的轻量化地图:

<xsl:stylesheet version="3.0" xmlns:map="http://www.w3.org/2005/xpath-functions/map"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:mf="http://example.com/mf" exclude-result-prefixes="#all">

    <xsl:output indent="yes" method="xml"/>
    
    <xsl:param name="encoding" as="xs:string" select="'utf-8'"/>

    <xsl:param name="file" as="xs:string" select="''"/>

    <xsl:function name="mf:group" as="element()*">
        <xsl:param name="steps" as="map(xs:string,xs:anyAtomicType)*"/>
        <xsl:param name="level" as="xs:integer"/>
        <xsl:for-each-group select="$steps"
            group-starting-with=".[?level eq $level and ?info eq 'Started']">
            <xsl:variable name="start" select="."/>
            <xsl:for-each-group select="current-group() => tail()"
                group-ending-with=".[?level eq $level and ?info eq 'Stopped' and ?path eq $start?path]">
                <xsl:variable name="stop" select="current-group()[last()]"/>
                <xsl:element name="{normalize-space($start?root)}">
                    <xsl:attribute name="start" select="$start?ts"/>
                    <xsl:attribute name="time" select="$stop?time"/>
                    <xsl:sequence
                        select="mf:group(current-group()[position() lt last()],$level + 1)"/>
                </xsl:element>
            </xsl:for-each-group>
        </xsl:for-each-group>
    </xsl:function>

    <xsl:template name="xsl:initial-template">
        <profile>
            <xsl:choose>
                <xsl:when test="unparsed-text-available($file,$encoding)">
                    <xsl:sequence
                        select="
                            mf:group(
                                unparsed-text-lines($file,$encoding)
                                !
                                (let $tokens := tokenize(.,'\|') ! normalize-space(),$token5 := $tokens[5],$token5Tokens := tokenize($token5,'/')
                                return
                                    map {
                                        'ts': $tokens[1],'time': $tokens[2],'info': $tokens[4],'path': $token5,'root': $token5Tokens[last()],'level': count($token5Tokens) - 1
                                    }),0
                            )"
                    />
                </xsl:when>
                <xsl:otherwise>
                    <xsl:variable name="error">
                        <xsl:text>Error reading "</xsl:text>
                        <xsl:value-of select="$file"/>
                    </xsl:variable>
                    <xsl:message>
                        <xsl:value-of select="$error"/>
                    </xsl:message>
                    <xsl:value-of select="$error"/>
                </xsl:otherwise>
            </xsl:choose>
        </profile>
    </xsl:template>

</xsl:stylesheet>

但是,尽管这会稍微减少内存消耗,但它的执行速度似乎要比XML文本和XML方法的递归分组要慢一些。

,

代码逆向工程总是很棘手,但至少在这种情况下,它是有效的代码!

症结似乎是

<xsl:apply-templates select="key('startedthreads',@level + 1)
    [number(@ord) &gt; number($start/@ord) and 
     number(@ord) &lt; number($stop/@ord)]" mode="unflatten1"/>

对key()的调用不会很有用,因为它将为每个键值选择大量元素。 (实际上,我记得一个最近的性能错误,该错误与具有大量重复项的键有关,但是我现在无法找到它。)

第一步,我倾向于按@level对数据进行分组,因此您可以快速选择给定级别的所有步骤。

然后,我认为您需要确保在找到第一个大于@ord的{​​{1}}时停止对给定级别的搜索。您知道数据是经过排序的,但Saxon不会进行排序,因此您需要以某种方式利用这一知识。一种方法是使用$stop/@ord显式搜索数据,这使您可以在遇到相关条件时中断。另一种选择可能是使用(新的)saxon:items-until()扩展功能[1],或者使用范围键[2]。或者,您也可以使用递归函数以旧方法来实现,该函数一次将自己称为一个同级。

[1] https://saxonica.com/documentation/index.html#!functions/saxon/items-until

[2] https://saxonica.com/documentation/index.html#!functions/saxon/key-map

,

使用Saxon扩展功能还可以帮助加快处理速度。

具有样式表输入profile.txt和预期输出profile.xml的当前“模板基准”:

enter image description here

enter image description here

  • 模板txt2xml_s0根本不执行任何操作(因此仅显示了Java和Saxon的加载时间)
  • 模板txt2xml_s1是原始的解决方案(不错,但如上面的答案所示是可改进的)
  • 模板txt2xml_s4实现第一个approach from MH
  • 模板txt2xml_s5是具有Saxon扩展功能,最佳性能和最低内存消耗的方法;现在我首选的解决方案
  • 模板txt2xml_s6实现了第二个更少的内存消耗approach from MH

我已经更新了repository。它包括所有已知的解决方案。扩展功能代码为ScanFile.java

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-