微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

xml – xslt优化:多次访问子进程或使用变量

我需要一个信息来优化我的xslt.

在我的模板中,我多次访问一个孩子,例如:

<xsl:template match="user">
 <h1><xsl:value-of select="address/country"/></h1>
 <p><xsl:value-of select="address/country"/></p>
 <p><xsl:value-of select="address/country"/></p>
  ... more and more...
 <p><xsl:value-of select="address/country"/></p>
</xsl:template>

将子元素的内容存储在变量中并直接调用变量以避免每次解析树是否更好:

<xsl:template match="user">
 <xsl:variable name="country" select="address/country"/>
 <h1><xsl:value-of select="$country"/></h1>
 <p><xsl:value-of select="$country"/></p>
 <p><xsl:value-of select="$country"/></p>
  ... more and more...
 <p><xsl:value-of select="$country"/></p>
</xsl:template>

或者,使用变量会比多次解析树消耗更多资源吗?

解决方法

通常,XML文件作为一个整体进行解析,并在内存中保存为 XDM.所以,我想通过

than parsing the tree multiple times

实际上,您需要多次访问XML输入的内部表示.下图说明了这一点,我们讨论的是源代码树:

enter image description here



(taken from Michael Kay’s XSLT 2.0 and XPath 2.0 Programmer’s Reference,page 43)

同样,xsl:variable创建一个节点(或更确切地说,一个临时文档),该节点保存在内存中并且也需要访问.

现在,您的优化究竟是什么意思?你的意思是执行转换或cpu和内存使用所花费的时间(正如你在问题中提到的“资源”)?

此外,性能取决于您的XSLT处理器的实现.找到答案的唯一可靠方法是实际测试这个.

写两个仅在这方面不同的样式表,也就是说,它们是相同的.然后,让它们转换相同的输入XML并测量它们所花费的时间.

我的猜测是,访问变量更快,重复变量名称比在编写代码时重复完整路径更方便(这有时称为“便利变量”).

编辑:替换为更合适的内容,作为对您的评论回复.

如果您实际测试了这个,请编写两个样式表:

样式表与变量

<?xml version="1.0" encoding="utf-8"?>

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

   <xsl:output method="xml" indent="yes"/>

   <xsl:template match="/root">
      <xsl:copy>
         <xsl:variable name="var" select="node/subnode"/>
         <subnode nr="1">
            <xsl:value-of select="$var"/>
         </subnode>
         <subnode nr="2">
            <xsl:value-of select="$var"/>
         </subnode>
      </xsl:copy>
   </xsl:template>

</xsl:stylesheet>

没有变量的样式表

<?xml version="1.0" encoding="utf-8"?>

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

   <xsl:output method="xml" indent="yes"/>

   <xsl:template match="/root">
      <xsl:copy>
         <subnode nr="1">
            <xsl:value-of select="node/subnode"/>
         </subnode>
         <subnode nr="2">
            <xsl:value-of select="node/subnode"/>
         </subnode>
      </xsl:copy>
   </xsl:template>

</xsl:stylesheet>

应用于以下输入XML:

<root>
   <node>
      <subnode>helloworld</subnode>
   </node>
</root>

编辑:正如@Michael Kay所建议的那样,我测量了100次运行所需的平均时间(“-t和-repeat:Saxon命令行上的100”):

with variable: 9 ms
without variable: 9 ms

这并不意味着结果与您的XSLT处理器相同.

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