kvetjo
kvetjo

Reputation: 55

If condition with and without the square brackets XSLT

I am learning XSLT and I came to an aspect of XSLT/XPath which is not clear to me.

I want to check if there is at least one element namePart with a value inside.

There can be something like this in XML:

<mods:name type="personal">
      <mods:namePart type="family">Salamonis</mods:namePart>
      <mods:namePart type="given"/>
</mods:name>

But also this due to any reason:

<mods:name type="personal">
      <mods:namePart/>
</mods:name>

I think I have found out the solution for my problem. Actually I found two similar solutions but I do not understand the difference:

first:

<xsl:for-each select="mods:name">
                 <xsl:if test="mods:namePart/text() != ''"> ..... </xsl:if>
<xsl:for-each>

second:

<xsl:for-each select="mods:name">
                 <xsl:if test="mods:namePart[text() != '']"> ..... </xsl:if>
<xsl:for-each>

Apparently, both of them are working fine. But I am still thinking what is better to use or if there are some minor differences. My solution is taken from this comment: https://stackoverflow.com/a/7660915/14163073 So are both of these solution working in accordance with the comment? (operator returns true if at least one item on the left side "matches" one item on the right side)

Thanks for any explanation!

Upvotes: 0

Views: 520

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167696

Well, take a tour through an XPath tutorial, I would say. Preferences are often a personal choice and style. For the last test I would simply use e.g. <xsl:if test="mods:namePart = 'foo'"> as that works for any contents of the mods:namePart elements. It doesn't really matter for your simple example but in the end you might end up using XPath against e.g. some mixed contents HTML paragraph element and want to check its whole content (e.g. test="p = 'This is an example text.'") and the p could be anything from a simple <p>This is an example text.</p> to <p>This is an <b>example</b> text.</p>.

Upvotes: 1

Related Questions