Search code examples
xslt

How i can get text value from body node?


I need get node if it contains text. So when i process <p> tag - i need to check previous <topic> if it has text in body or in any child tag in <body>

With next XSL code

 ancestor::topic[1]/preceding-sibling::topic[1]/body/child::node()[(self::text() and normalize-space()) or self::*][position() = last()]

But it's for some reasons not working... Why?

<topic>
   <body>Topic 3 with only a paragraph, no topic title</body>
</topic>

<topic>
    <body>
        <p> <!-- from here -->
         <image href="" />
      </p> <!-- and from here -->
      </body>
</topic>
      
<topic>       
 <body>Topic 5 with only a paragraph, no topic title</body>
</topic>

Solution

  • I think you need to tell us in more detail what you are trying and how it exactly it fails for your; when I convert your input snippet into a well-formed input document

    <root>
    <topic>
       <body>Topic 3 with only a paragraph, no topic title</body>
    </topic>
    
    <topic>
        <body>
            <p> <!-- from here -->
             <image href="" />
          </p> <!-- and from here -->
          </body>
    </topic>
          
    <topic>       
     <body>Topic 5 with only a paragraph, no topic title</body>
    </topic>
    </root>
    

    and run it through a stylesheet matching on a p with your posted condition in a predicate it obviously finds that single p you have i.e.

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
        xmlns:xs="http://www.w3.org/2001/XMLSchema"
        exclude-result-prefixes="#all"
        version="3.0">
    
      <xsl:mode on-no-match="shallow-skip"/>
    
      <xsl:template match="p[ancestor::topic[1]/preceding-sibling::topic[1]/body/child::node()[(self::text() and normalize-space()) or self::*][position() = last()]]">
        found
      </xsl:template>
      
    </xsl:stylesheet>
    

    outputs found as the match happens.

    So explain with minimal but complete samples what your are trying, which output you expect and how it fails (i.e. which error you get or which wrong output), then we can tell perhaps what is wrong.

    Sorry for the non-answer, but I couldn't stuff the code example that shows your expression does seem to work into a comment.