我是Xquery的新手,我想将给定的xml更改为另一种xml格式。
鉴于XML:
<?xml version="1.0" encoding="UTF-8"?>
<Store>
<consumer id="H01">
<name>John Doe</name>
<items>
<item type = "Torch">
<price>$3</price>
</item>
<item type = "Gas">
<price>$4</price>
</item>
</items>
</consumer >
<consumer id="H05">
<name>Jane Doe</name>
<items>
<item type = "Cell">
<price>$8</price>
</item>
<item type = "Shirt">
<price>$12</price>
</item>
</items>
</consumer>
所需的XML格式:
<Store>
<user>
<number><id>H01</id><name>John Doe</name></number>
<number><id>H05</id><name>Jane Doe</name></number>
</user>
<inventory>
<number><type>Torch</type><price>$3</price></number>
<number><type>Gas</type><price>$4</price></number>
<number><type>Cell</type><price>$8</price></number>
<number><type>Shirt</type><price>$12</price></number>
</inventory>
</Store>
我做的Xquery:
for $customer in distinct-values(doc("../xml/store.xml")/store/consumer/@id)
let $name := doc("../xml/store.xml")/store/consumer[@id=$customer]/name
for $object in distinct- values(doc("../xml/store.xml")/store/consumer[@id=$customer]/items/item/@type)
return
<store>
<user>
<number>
<id>{$customer}</id>
{$name}
</number>
</user>
<inventory>
<number>
<type>{$object}</type>
</number>
</inventory>
</store>
我到底哪里错了?有没有办法让属性成为新的节点元素。
答案 0 :(得分:0)
你的两个for子句是嵌套的,在这种情况下你不希望这样。我会做这样的事情:
let $doc := doc("../xml/store.xml")
let $customerIds := distinct-values($doc/store/consumer/@id)
return
<store>
<user>{for $customerId in $customerIds
let $consumer := $doc/store/consumer[@id=$customerId]
return <number><id>{data($consumer/@id)}</id><name>{$consumer/name}</name></number>
}
</user>
<inventory>
similar thing for items
</inventory>
</store>
我们是否可以将属性作为新节点元素。
是的,您可以使用data()函数来提取文本。见上面的例子。