Xml Basex XQL合并具有相同标记名的内容,而不考虑文档中的位置
例如,给定XML:Xml Basex XQL合并具有相同标记名的内容,而不考虑文档中的位置,xml,xpath,basex,flwor,Xml,Xpath,Basex,Flwor,例如,给定XML: <root> <item> <id>111</id> <description>aisle 12, shelf 3</description> <description>inside the box</description> </item> </root> 我想知道结果: <root&
<root>
<item>
<id>111</id>
<description>aisle 12, shelf 3</description>
<description>inside the box</description>
</item>
</root>
我想知道结果:
<root>
<item>
<id>111</id>
<description>aisle 12, shelf 3 inside the box</description>
</item>
</root>
但是节点可以有任何名称,并且处于任何级别。
我希望相同的查询可以处理不同的XML,只要标记重复:
<root>
<item>
<id>112</id>
<attributes>
<author>Joe Smith</author>
<author>Arthur Clarke</author>
<author>Jeremiah Wright</author>
</attributes>
</item>
</root>
输出:
<root>
<item>
<id>112</id>
<attributes>
<author>Joe Smith Arthur Clarke Jeremiah Wright</author>
</attributes>
</item>
</root>
对于BaseX,这可能吗?
如果没有,我们是否可以在已知元素的情况下(例如,仅针对/root/item/attributes/author)执行此操作?确保只直接合并以下同级元素会使事情稍微复杂一些。我在下面添加了一些关于代码如何工作的注释
let $xml := document{<root>
<item>
<id>112</id>
<attributes>
<author>Joe Smith</author>
<author>Arthur Clarke</author>
<author>Jeremiah Wright</author>
<foo/>
<author>Donald Duck</author>
</attributes>
</item>
</root>}
return
(: Use an XQuery Update transformation :)
copy $copy := $xml
modify (
(: Loop over all leaves (only containing text nodes. :)
(: This might have to be adjusted if you want to merge arbitrary nodes. :)
for $leaf in $copy//*[not(*)]
(: Where the preceding node is not of the same name :)
(: (as it will be merged anyway) :)
where not($leaf/preceding-sibling::*[1 and name(.) eq name($leaf)])
(: Now find following siblings... :)
let $siblings := $leaf/following-sibling::*[
(: ... of the same name ... :)
name(.) eq name($leaf) and
(: ... and that do not have a node with another name in-between :)
not(preceding-sibling::*[name(.) != name($leaf) and $leaf << .])
]
return (
(: Merge text contents into $leaf :)
replace value of node $leaf with string-join(($leaf, $siblings), ' '),
(: And delete all others :)
delete nodes $siblings
)
)
return $copy