26

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?

kpozin
  • 25,691
  • 19
  • 57
  • 76

5 Answers5

33

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()
Harold L
  • 5,166
  • 28
  • 28
  • 4
    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"](http://developer.marklogic.com/blog/text-is-a-code-smell), as well as the Dave Cassel post I linked to below after Oliver's answer and Pavel's reply. – Joe Wicentowski Mar 03 '13 at 03:39
19

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

return string($xml)
Oliver Hallam
  • 4,242
  • 1
  • 24
  • 30
  • 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. – Pavel Minaev Jul 27 '09 at 20:08
  • 3
    Indeed. See David Cassel's explanation of the [differences between text(), fn:string(), and fn:data()](http://blog.davidcassel.net/2011/06/text-fnstring-and-fndata/) -- all three of which have made appearances in the three answers so far. – Joe Wicentowski Mar 03 '13 at 03:36
8

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

return data($xml)
SeeJay
  • 89
  • 1
  • 4
  • 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(). – Joe Wicentowski Mar 03 '13 at 03:43
0

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

savemaxim
  • 377
  • 3
  • 6
0

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

fn-bea:serialize($xml)

Aniruddha Jagtap
  • 383
  • 5
  • 16