如何有效地替换XML的多个节点?

时间:2018-09-06 09:40:58

标签: xquery marklogic

我正在尝试一次替换单个文档中的大约500个节点,并且我的数据库中有5000多个文档。

我使用的代码与我之前问过的这个SO问题有关- Link

有什么建议可以提高我的代码效率?

1 个答案:

答案 0 :(得分:5)

通常应避免使用内存中更新库,尤其是在对同一文档进行大量方法调用时。由于每种方法都会遍历整个节点树并生成一个全新的文档,因此如果您针对大型文档运行和/或在这些文档上进行一堆mem:*方法调用,则可能会很慢且成本很高。

更好的替代方法是使用Ryan Dew的XQuery XML Memory Operations library,或使用XSLT。

下面是一个示例,说明如何使用XSLT执行这种“合并”,该执行应该比in-mem-update方法更好。

declare variable $STAGING := document{
<root>
 <ID>1</ID>
 <value1>India</value1>
 <value2>USA</value2>
 <value3>Russia</value3>
 <value4>Srilanka</value4>
 <value5>Europe</value5>
 <value6>Antartica</value6>
 <value7>Spain</value7>
</root>
};

declare variable $FINAL := document{
<root>
 <ID>1</ID>
 <value1></value1>
 <value2></value2>
 <value3></value3>
 <value4></value4>
 <value5>Europe</value5>
 <value6>Antartica</value6>
</root>
};

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

  <xsl:param name="staging-doc"/>
  <xsl:param name="element-names"/>

  <xsl:variable name="final-doc" select="/"/>

  <xsl:key name="staging-elements" match="root/*[local-name() = $element-names]" use="local-name()"/>

  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="root/*[local-name() = $element-names]">
    <!--if there is an element in the staging-elements doc with this name, use it. Otherwise, use the matched element from this doc -->
    <xsl:copy-of select="(key('staging-elements', local-name(.), $staging-doc), .)[1]"/>
  </xsl:template>

  <xsl:template match="root">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
      <!-- also copy any other elements with the specified names from the staging document that were not already in the final -->
      <xsl:apply-templates select="$staging-doc/root/*[local-name() = $element-names and not(key('staging-elements', local-name(), $final-doc))]"/>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>;

declare variable $PARAMS := map:new((
    map:entry("staging-doc", $STAGING), 
    map:entry("element-names", tokenize(("value1,value2,value3,value4,value7"), ",") )
  ));

xdmp:xslt-eval($XSLT, $FINAL, $PARAMS)
相关问题