我正在尝试更改从 Web 表单加载到内存中的一个非常大的 XML 文件中几个节点的值。
文件是这样获取的:
let $file := xdmp:get-request-field("xml_to_upload")
因此,如您所见,该文件在内存中。
现在,我需要更改数千个节点的值,但到目前为止我还无法以最佳方式进行。
有什么想法吗?
到目前为止我尝试过的一些事情:
let $auxVar :=
if($fileStructureIsValid) then
(
for $currentNode in xdmp:unquote($file)//ID
let $log := xdmp:log( fn:concat( "newNodeValue", ": ", mem:replace( $currentNode, element ID{ fn:concat( $subject, "-", fn:data( $currentNode ) ) } ) ) )
return fn:concat( $subject, "-", fn:data( $currentNode ) )
)
else
(
)
mem 库是自定义下载的。
最佳答案
如果可能,将文档插入数据库,并在单独的事务中使用 xdmp:node-replace
更新节点。
xquery version "1.0-ml";
...
xdmp:document-insert('file.xml', $file) ;
xquery version "1.0-ml";
for $currentNode in doc('file.xml')//ID
return xdmp:node-replace($currentNode,
element ID{ concat($subject, "-", $currentNode) });
或者,如果您必须更新内存中的文档,最好只遍历树一次(在该操作中进行所有更新),而不是多次 mem:replace
操作(这可能每次都重新走树)。
declare function local:update-ids(
$n as item(),
$subject as xs:string
) as item()
{
typeswitch ($n)
case element(ID) return
element ID { concat($subject, "-", $n) }
case element() return
element { node-name($n) } {
@*, $n/node()/local:update-ids(., $subject) }
default return $n
};
let $xml := xdmp:unquote($file)
let $xml-with-updated-ids := local:update-ids($xml, $subject)
...
更新:
正如 Erik 在评论中建议的那样,您还可以在 XSLT 中编写 local:update-ids
的逻辑(使用 xdmp:xslt-eval
或 xdmp :xslt-invoke
执行),它们在性能方面应该大致相当。事实上,MarkLogic 有一篇关于这个主题的博客文章:
关于xml - 使用 xQuery 更改内存中的 XML 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18622286/