XQuery: Return value of an element rather the element itself
Asked Answered
T

5

27

I have an XML document that contains the following

...
<foo>abc</foo>
...

If I evaluate

return $xml//foo

I get back

<foo>abc</foo>

Is there any way to get just abc instead?

Topsyturvy answered 20/7, 2009 at 18:51 Comment(0)
P
34

Yes, you want the text() function for selecting the child text:

return $xml/text()

Be careful if you will have nested tag structure inside $xml though, because this will only go one level deep for text nodes. If you want all of the text nodes together, stripping out other XML structure, this will do arbitrarily deep:

return $xml//text()
Placatory answered 20/7, 2009 at 18:54 Comment(1)
text() is not a function. It is a node test. Before you go text() crazy, see Evan Lenz's post "text() is a code smell", as well as the Dave Cassel post I linked to below after Oliver's answer and Pavel's reply.Subheading
S
20

Use the string function to get the string content of a node.

return string($xml)
Slope answered 21/7, 2009 at 13:39 Comment(2)
This is actually a more idiomatic and better alternative than the preferred answer above. It will also handle any nesting of child nodes correctly.Insectarium
Indeed. See David Cassel's explanation of the differences between text(), fn:string(), and fn:data() -- all three of which have made appearances in the three answers so far.Subheading
H
9

To return only the data inside an element you can use:

return data($xml)
Hyps answered 19/9, 2009 at 9:14 Comment(1)
More precisely, fn:data() is a function that gives you the atomized value of a node sequence, i.e., each node's typed value; whereas fn:string() gives you the string-value of a node. See the links I've sprinkled through the comments above for more on the differences between text(), fn:string(), and fn:data().Subheading
M
0

Cast to xs:string {xs:string($xml/foo)}

Mastoiditis answered 20/5, 2013 at 11:29 Comment(0)
E
0

OSB (oracle service bus) users can use following function.

fn-bea:serialize($xml)

Eudora answered 15/12, 2014 at 10:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.