Pietro
Pietro

Reputation: 13172

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

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!

Upvotes: 4

Views: 146

Answers (3)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243529

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])"/>"

Upvotes: 3

Torx
Torx

Reputation: 138

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

Upvotes: 2

Mads Hansen
Mads Hansen

Reputation: 66783

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()"/>

Upvotes: 3

Related Questions