1
votes

I have an XQuery return statement like:

return
 <li>
 <h3>{ string($TELECAST/title/maintitle) }</h3>
 <h4>{ string($TELECAST/title/subtitle) }</h4>
 <h5>{ string($TELECAST/title/description) }</h5>
 </li>

Sometimes, there is no subtitle or description, still the HTML tags will be output. How can I easily check for empty strings and omit the unnecessary tags?

3

3 Answers

3
votes

For example, like this:

return
 <li> {
 for $i in $TELECAST/title/maintitle return <h3>{ string($i) }</h3>,
 for $i in $TELECAST/title/subtitle return <h4>{ string($i) }</h4>,
 for $i in $TELECAST/title/description return <h5>{ string($i) }</h5>
 } </li>
1
votes

Without using a function, this XQuery expression:

<ul>{
   for $TELECAST in /root/telecast
   return
      <li>{
         for $item in $TELECAST/title/*
         return
            typeswitch($item)
            case element(maintitle) return <h3>{string($item)}</h3>
            case element(subtitle) return <h4>{string($item)}</h4>
            case element(description) return <h5>{string($item)}</h5>
            default return ()
      }</li>
}</ul>

With this input:

<root>
    <telecast>
        <title>
            <maintitle>Title</maintitle>
            <subtitle>Subtitle</subtitle>
            <description>Description</description>
        </title>
    </telecast>
    <telecast>
        <title>
            <maintitle>Title2</maintitle>
            <description>Description2</description>
        </title>
    </telecast>
</root>

Output:

<ul>
    <li>
        <h3>Title</h3>
        <h4>Subtitle</h4>
        <h5>Description</h5>
    </li>
    <li>
        <h3>Title2</h3>
        <h5>Description2</h5>
    </li>
</ul>
0
votes

You could use the fn:string-length function. However, keep in mind that the function does not automatically trim white space.