将路径标记为字符串序列。同时遍历输入 XML 树和路径树。如果在任何时候路径与源树不同,请创建一个与剩余路径匹配的新子树:
declare function local:make-nested-elements(
$element-names as xs:string*
) as element()*
{
if (empty($element-names)) then ()
else element { $element-names[1] } {
local:make-nested-elements(subsequence($element-names, 2))
}
};
declare function local:add-path(
$xml as node()?,
$paths as xs:string*
) as node()
{
let $first := $paths[1]
let $rest := subsequence($paths, 2)
return
if (empty($first)) then $xml
else if ($xml instance of text()) then $xml
else if (node-name($xml) = xs:QName($first))
then element { $first } {
$xml/@*,
for $n in $xml/node()
return local:add-path($n, $rest)
}
else element { node-name($xml) } {
$xml/@*, $xml/node(),
local:make-nested-elements($paths)
}
};
输入:
let $xml :=
<Document>
<Header>This is a Header
<Body>Body message</Body>
</Header>
</Document>
let $path := "Document/Header/Footer/keep/nesting"
return local:add-path($xml, tokenize($path, '/'))
输出:
<Document>
<Header>This is a Header
<Body>Body message
<Footer>
<keep>
<nesting/>
</keep>
</Footer>
</Body>
</Header>
</Document>