XQuery: Create a new element with a given name?
Asked Answered
S

2

13

I have data like:

    <td>USERID</td>

    <td>NAME</td>

    <td>RATING</td>

I want to transform it into:

<userid></userid>
<name></name>
<rating></rating>

How can I do this?

Southwestwardly answered 30/3, 2010 at 1:1 Comment(0)
N
24

Use a computed element constructor to generate an element with the lower-case value of the text nodes for each of the td elements.

A computed element constructor creates an element node, allowing both the name and the content of the node to be computed.

For the sake of the example, assuming that your XML is in a file called foo.xml, you could do something like this:

<doc>
{
for $name in doc('foo.xml')//td/text()
return element {lower-case($name)} {''}
}
</doc>

to produce this:

<?xml version="1.0" encoding="UTF-8"?>
<doc>
 <userid/>
 <name/>
 <rating/>
</doc>

You could also evaluate the lower-case() function as part of the XPATH expression instead of the element constructor, like this:

<doc>
{
for $name in doc('foo.xml')//td/text()/lower-case(.)
return element {$name} {''}
}
</doc>
Necklace answered 30/3, 2010 at 2:13 Comment(0)
A
0
return <doc>{
for $d in $doc/element()/text()
return element{fn:lower-case($d)} {}}</doc>  

where $doc stores the Xml.

Abeu answered 25/4, 2017 at 15:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.