我试图找到一种方法来"散列"XML文件的内容.从根本上说,需要比较一些传入文本节点的文本节点,我期望确保校验和是相同的.传入的文本节点已从表单提交返回,我需要确保它们不会被更改(在合理范围内,排除冲突).
这个架构非常糟糕,所以请不要问它!我被一些非常糟糕的自定义代码锁定在一个给定的sharepoint实现中,我需要解决这个问题.
是否有可以实现的良好的校验和/哈希函数?我需要检查大约100个文本节点.
Lar*_*rsH 14
听起来你需要一个依赖于位置的校验和.您要求XSLT实现,还是仅仅是算法?
下面是C 中Fletcher校验和的实现,不应该很难移植到XSLT.
更新:下面是Fletcher校验和的XSLT 2.0改编版.它是否足够快,取决于您的数据大小和您拥有的时间.我很想知道你的考试是怎么回事.为了优化,我会尝试xs:integer改为xs:int.
请注意,我已将|上面链接的实现的按位OR()替换为普通加法.我不是真的有资格分析这种变化在统一性或不可逆性方面的影响,但只要你没有一个聪明的黑客试图恶意绕过你的校验和检查就好了.
请注意,由于上述更改,此实现将不会提供与Fletcher校验和(@MDBiker)的真实实现相同的结果.因此,您无法将此函数的输出与Java的Fletcher16的输出进行比较.然而,它会始终返回相同的结果对于相同的输入(这是确定的),这样你就可以在两个文本字符串比较这函数的输出.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="2.0" xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:foo="my.foo.org">
<xsl:variable name="str1">The quick brown fox jumps over the lazy dog.</xsl:variable>
<xsl:variable name="str2">The quick frown box jumps over the hazy frog.</xsl:variable>
<xsl:template match="/">
Checksum 1: <xsl:value-of select="foo:checksum($str1)"/>
Checksum 2: <xsl:value-of select="foo:checksum($str2)"/>
</xsl:template>
<xsl:function name="foo:checksum" as="xs:int">
<xsl:param name="str" as="xs:string"/>
<xsl:variable name="codepoints" select="string-to-codepoints($str)"/>
<xsl:value-of select="foo:fletcher16($codepoints, count($codepoints), 1, 0, 0)"/>
</xsl:function>
<!-- can I change some xs:integers to xs:int and help performance? -->
<xsl:function name="foo:fletcher16">
<xsl:param name="str" as="xs:integer*"/>
<xsl:param name="len" as="xs:integer" />
<xsl:param name="index" as="xs:integer" />
<xsl:param name="sum1" as="xs:integer" />
<xsl:param name="sum2" as="xs:integer"/>
<xsl:choose>
<xsl:when test="$index gt $len">
<xsl:sequence select="$sum2 * 256 + $sum1"/>
</xsl:when>
<xsl:otherwise>
<xsl:variable name="newSum1" as="xs:integer"
select="($sum1 + $str[$index]) mod 255"/>
<xsl:sequence select="foo:fletcher16($str, $len, $index + 1, $newSum1,
($sum2 + $newSum1) mod 255)" />
</xsl:otherwise>
</xsl:choose>
</xsl:function>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
输出:
Checksum 1: 65256
Checksum 2: 25689
Run Code Online (Sandbox Code Playgroud)
关于用法的说明:你说你需要对"XML文件的内容运行校验和.根本需要比较一些文本节点".如果将文本节点传递给foo:checksum(),它将正常工作:将提取其字符串值.
仅供参考,我进行了性能测试,以计算535KB XML输入文件中文本节点的校验和.这是我使用的初始模板:
<xsl:template match="/">
Checksum of input: <xsl:value-of
select="sum(for $t in //text() return foo:checksum($t)) mod 65536"/>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)
它使用Saxon PE完成了0.8秒.
或者:
如果文本量不是很大,那么简单地将字符串本身(而不是校验和)相互比较可能会更快更准确.但是,由于您的体系结构限制,您可能无法同时访问这两个文本节点...我不清楚您的描述.