Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 889
Pietro Avatar asked Feb 26 '23 18:02

Pietro


2 Answers

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])"/>"
like image 131
Dimitre Novatchev Avatar answered Mar 08 '23 00:03

Dimitre Novatchev


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()"/>
like image 39
Mads Hansen Avatar answered Mar 07 '23 23:03

Mads Hansen