and 080...">

How to check for XML value in XSLT

In the XML document, I have some address data.

<zip>08001</zip> <zipPlus xsi:nil="true" /> 

and

 <zip>08002</zip> <zipPlus>4512</zipPlus> 

Just to worry about displaying the zip plus value if there is a value to use. (for the purposes of this example, I don't care if it has the correct zip plus format or not)

Trying to use the following snippet in XSLT never works correctly, and I think this is due to the way I check the xsl: nil value

 <EmployerZipCode> <xsl:value-of select="zip"/> <xsl:if test="zipPlus != @xsl:nil"> <xsl:value-of select="'-'"/> <xsl:value-of select="zipPlus"/> </xsl:if> <xsl:value-of select="$sepChar"/> <!--this is a comma --> </EmployerZipCode> 

The results that I get are always

 08001, 08002, 

not

 08001, 08002-4512, 

What is the correct way to test elements with Nil-led in XSLT? Are there any other ways to get around this problem and get the result I want?

+6
source share
5 answers

After another test, none of the answers that require checking the nil attribute works reliably.

I had to resort to using string-length () to get the result I needed.

 <EmployerZipCode> <xsl:value-of select="zip"/> <xsl:if test="string-length(zipPlus) &gt; 0"> <xsl:value-of select="'-'"/> <xsl:value-of select="zipPlus"/> </xsl:if> <xsl:value-of select="$sepChar"/> </EmployerZipCode> 
+2
source
 <xsl:if test="not(zipPlus/@xsi:nil='true')"> 
+6
source

In XSLT 2.0, for reasons that I never fully understood, there is a user-defined function

 test="not(nilled(zipPlus))" 
+5
source

It is very strange that you did not get him to work. Maybe you are missing a namespace declaration, or the xsi - xsl prefix change is an invisible typo in your conversion. Check it out better. Here is my test:

XSLT 1.0 with Saxon 6.5

 <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xsi="test"> <xsl:output method="text" indent="yes"/> <xsl:template match="EmployerZipCode"> <EmployerZipCode> <xsl:value-of select="zip"/> <xsl:if test="not(zipPlus/@xsi:nil)"> <xsl:value-of select="'-'"/> <xsl:value-of select="zipPlus"/> </xsl:if> <xsl:value-of select="','"/> <!--this is a comma --> </EmployerZipCode> </xsl:template> </xsl:stylesheet> 

Given input:

 <?xml version="1.0" encoding="utf-8"?> <test xmlns:xsi="test"> <EmployerZipCode> <zip>08001</zip> <zipPlus xsi:nil="true" /> </EmployerZipCode> <EmployerZipCode> <zip>08002</zip> <zipPlus>4512</zipPlus> </EmployerZipCode> </test> 

It produces:

 08001, 08002-4512, 
+1
source

It works for me

XML source:

  <zipPlus xsi:nil="true"/> or <zipPlus>123456</zipPlus> 

XSLT:

  <xsl:if test="not(zipPlus/@xsl:nil='true')"> <xsl:value-of select="zipPlus"/> </xsl:if> 

XML result

  <zipPlus/> or <zipPlus>123456</zipPlus> 
+1
source

Source: https://habr.com/ru/post/890163/


All Articles