使用Xquery创建具有特定模式的XML文件

使用Xquery创建具有特定模式的XML文件,xquery,Xquery,我不熟悉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> <it

我不熟悉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>

无名氏
$3
$4
无名氏
$8
$12

所需的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>

H01无名氏
H05无名氏
火炬3美元
汽油4美元
手机8美元
衬衫12美元
我提出的问题:

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>
用于不同值的$customer(doc(“../xml/store.xml”)/store/consumer/@id)
让$name:=doc(“../xml/store.xml”)/store/consumer[@id=$customer]/name
对于不同值的$object(doc(“../xml/store.xml”)/store/consumer[@id=$customer]/items/item/@type)
返回
{$customer}
{$name}
{$object}

我到底错在哪里?有没有一种方法可以使属性成为新的节点元素。

您的两个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>
let$doc:=doc(“../xml/store.xml”)
let$customerIds:=不同的值($doc/store/consumer/@id)
返回
{对于$customerId中的$customerId
let$consumer:=$doc/store/consumer[@id=$customerId]
返回{data($consumer/@id)}{$consumer/name}
}
同样的事情也发生在物品上
有没有一种方法可以使属性成为新的节点元素

是的,例如,您可以使用data()函数提取文本。见上面的例子