4

I have this (token of) XML file of which I want to print just the "Print this" string, ignoring what follows:

<tag1>
   Print this
   <tag2>
      Do not print this
   </tag2>
</tag1>

In my XSL file, with this command I get both the contents of tag1 and the contents of tag2 printed:

<xsl:value-of select="tag1"/>

Thank you!

Pietro
  • 12,086
  • 26
  • 100
  • 193
  • exact duplicate of [Output first string, not all children's strings](http://stackoverflow.com/questions/4227720/output-first-string-not-all-childrens-strings) –  Nov 25 '10 at 16:52
  • Good question, +1. See my answer for an explanation and for a correct and more precise solution than the currently accepted one. – Dimitre Novatchev Nov 25 '10 at 19:41

3 Answers3

3

value-of of an element will give you the value of it's text nodes and that of it's descendants. If you just want the immediate text() node of the element, use this:

<xsl:value-of select="tag1/text()"/>
Mads Hansen
  • 63,927
  • 12
  • 112
  • 147
3

In my XSL file, with this command I get both the contents of tag1 and the contents of tag2 printed:

<xsl:value-of select="tag1"/> 

How can I get just the first, higher level, string?

Your code produces the string value of the tag1 element, which by definition is the concatenation of all text-nodes-descendents of the element.

To produce just

the "Print this" string

you need to specify an XPath expression that selects only the respective text node:

/tag1/text()[1]

Specifying [1] is necessary to select only the first text-node child, otherwise two text-nodes may be selected (this is an issue only in XSLT 2.0 where <xsl:value-of> produces the string values of all nodes specified in the select attribute).

Further, the above expression selects the whole text node and its string value isn't "Print this".

The string value actually is:

"
   Print this
   "

and exactly this would be output if you surround the <xsl:value-of> in quotes.

To produce exactly the wanted string "Print this" use:

"<xsl:value-of select="normalize-space(/tag1/text()[1])"/>"
Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431
2

<xsl:value-of select="tag1/text()"/> will select all text nodes under tag1

Mads Hansen
  • 63,927
  • 12
  • 112
  • 147
Torx
  • 138
  • 1
  • 8