[英]Using XQuery with order by all elements and attribute
I still have a problem about sorting xml by XQuery. 我仍然对通过XQuery对xml进行排序有问题。
Please check below code. 请检查以下代码。
As is : 照原样:
<Main name = "test">
<Sample id="1">
<cal>
<tree abc="123"/>
<tree abc="789/>
<tree-order abc="456/>
</cal>
</Sample>
<Sample id="2">
<cal>
<tree abc="123"/>
<tree abc="789/>
<tree-order abc="456/>
</cal>
</Sample>
<Sample id="3">
<cal>
<tree abc="123"/>
<tree abc="789/>
<tree-order abc="456/>
</cal>
</Sample>
</Main>
I want to order by attribute "abc" 我想按属性“ abc”订购
To be 1: 成为1:
<Main name = "test">
<Sample id="1">
<cal>
<tree abc="123"/>
<tree-order abc="456/>
<tree abc="789/>
</cal>
</Sample>
<Sample id="2">
<cal>
<tree abc="123"/>
<tree-order abc="456/>
<tree abc="789/>
</cal>
</Sample>
<Sample id="3">
<cal>
<tree abc="123"/>
<tree-order abc="456/>
<tree abc="789/>
</cal>
</Sample>
</Main>
after that is it possible to remove attribute?? 之后,可以删除属性吗?
Final. 最后。
<Main name = "test">
<Sample id="1">
<cal>
<tree />
<tree-order />
<tree />
</cal>
</Sample>
<Sample id="2">
<cal>
<tree />
<tree-order />
<tree />
</cal>
</Sample>
<Sample id="3">
<cal>
<tree />
<tree-order />
<tree />
</cal>
</Sample>
</Main>
like this. 像这样。
so attribute abc is only for sorting. 因此属性abc仅用于排序。
I tried to like this 我试图喜欢这个
select @data.query('for $j in * order by number($j/@abc) return $j ')
then it's will show xml format without sorting. 那么它将显示xml格式而不进行排序。
Is there any way to solve this problem? 有什么办法解决这个问题?
Process the XML recursively so that you can perform a sort on the <cal>
element children and preserve its ancestor structure: 递归处理XML,以便您可以对
<cal>
元素子元素执行排序并保留其祖先结构:
declare function local:sort(
$xml as element(cal)
) as element()
{
element cal {
for $e in $xml/*
order by $e/@abc
return local:dispatch($e)
}
};
declare function local:remove-atts(
$xml as element()
) as element()
{
element { node-name($xml) } {
$xml/@* except $xml/@abc,
$xml/node()
}
};
declare function local:dispatch(
$xml as element()
) as element()
{
typeswitch ($xml)
case element(cal) return local:sort($xml)
case element(tree) return local:remove-atts($xml)
case element(tree-order) return local:remove-atts($xml)
default return local:process($xml)
};
declare function local:process(
$xml as element()
) as element()
{
element { node-name($xml) } {
$xml/@*,
for $n in $xml/node()
return local:dispatch($n)
}
};
local:process($xml)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.