XQuery - 动态交换属性和元素值(反向结构)
XQuery - Swap attribute and element values (inverse structure) dynamically
所以我有这个(不寻常的)任务
"Write a query that inverts all the sub elements of the /music element
so that their own sub elements become attributes and their attributes
become sub elements. For those sub elements that lack sub elements of
their own, their data content should become an attribute with the name
'value'."
我在哪里使用这个数据库:https://gist.githubusercontent.com/Schytheron/0a5c4756db62a1f43fc40226659c12cf/raw/71378ab9cede19e3f5bb33e948177a9fccfcc132/songs.xml 我真的不知道从哪里开始。我完全迷路了。这只能递归解决还是有其他方法(因为我从未尝试过在 Xquery 中进行递归)?您是否有任何 tips/strategies 可以解决这个问题或任何有用的功能(我对 Xquery 很陌生,所以我真的不知道那么多有用的功能)我可以使用吗?
想法?想法?
谢谢!
编辑:只是为了把事情说清楚。我知道我可能只是为每个元素及其子元素手动执行此操作,其中包含 x 个嵌套 for 循环,但我想知道是否有办法使此动态化,以便它可以与任何 XML 一起使用数据库。
对于根据需要转换根元素的子元素的有限用例,您可以使用一些函数:
declare function local:transform($element as element()) as element() {
element {name($element)} {
$element/node() ! local:attribute(.),
$element/@* ! local:element(.)
}
};
declare function local:attribute($node as node()) as attribute() {
typeswitch ($node)
case element() return attribute {name($node)} {data($node) }
case text() return attribute value { $node }
default return ()
};
declare function local:element($att as attribute()) as element() {
element {name($att)} { data($att) }
};
/*!element {name()} { *!local:transform(.) }
所以我有这个(不寻常的)任务
"Write a query that inverts all the sub elements of the /music element so that their own sub elements become attributes and their attributes become sub elements. For those sub elements that lack sub elements of their own, their data content should become an attribute with the name 'value'."
我在哪里使用这个数据库:https://gist.githubusercontent.com/Schytheron/0a5c4756db62a1f43fc40226659c12cf/raw/71378ab9cede19e3f5bb33e948177a9fccfcc132/songs.xml 我真的不知道从哪里开始。我完全迷路了。这只能递归解决还是有其他方法(因为我从未尝试过在 Xquery 中进行递归)?您是否有任何 tips/strategies 可以解决这个问题或任何有用的功能(我对 Xquery 很陌生,所以我真的不知道那么多有用的功能)我可以使用吗?
想法?想法?
谢谢!
编辑:只是为了把事情说清楚。我知道我可能只是为每个元素及其子元素手动执行此操作,其中包含 x 个嵌套 for 循环,但我想知道是否有办法使此动态化,以便它可以与任何 XML 一起使用数据库。
对于根据需要转换根元素的子元素的有限用例,您可以使用一些函数:
declare function local:transform($element as element()) as element() {
element {name($element)} {
$element/node() ! local:attribute(.),
$element/@* ! local:element(.)
}
};
declare function local:attribute($node as node()) as attribute() {
typeswitch ($node)
case element() return attribute {name($node)} {data($node) }
case text() return attribute value { $node }
default return ()
};
declare function local:element($att as attribute()) as element() {
element {name($att)} { data($att) }
};
/*!element {name()} { *!local:transform(.) }