XML/XSLT stylesheet/normalize space
Содержание
normalize-space
File: Data.xml
<test>
<sample eid="A" />
<sample eid="B"></sample>
<sample eid="C"></sample>
<sample eid="D"></sample>
<sample eid="E">some text</sample>
<sample eid="F">
<color>blue</color>
</sample>
<sample eid="G">
<color>red</color>
more text
</sample>
</test>
File: Transform.xslt
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output method="xml" omit-xml-declaration="yes" indent="no" />
<xsl:template match="sample">
<xsl:choose>
<xsl:when test="normalize-space(.)">
Sample element
<xsl:value-of select="@eid" />
isn"t empty.
</xsl:when>
<xsl:otherwise>
Sample element
<xsl:value-of select="@eid" />
is empty.
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
Output:
Sample element
A
is empty.
Sample element
B
is empty.
Sample element
C
is empty.
Sample element
D
is empty.
Sample element
E
isn"t empty.
Sample element
F
isn"t empty.
Sample element
G
isn"t empty.
normalize-space demo
File: Data.xml
<poem>
<verse>line 1</verse>
<verse>
line 2
</verse>
</poem>
File: Transform.xslt
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output method="xml" omit-xml-declaration="yes" indent="no" />
<xsl:template match="verse">
<xsl:value-of select="concat("length: ",string-length(.))" />
<xsl:if test="contains(.,"light")">
<xsl:text>light: yes!</xsl:text>
</xsl:if>
<xsl:if test="starts-with(.,"Seest")">
<xsl:text>Yes, starts with "Seest"</xsl:text>
</xsl:if>
<xsl:value-of select="normalize-space(.)" />
<xsl:value-of select="translate(.,"abcde","ABCD")" />
</xsl:template>
</xsl:stylesheet>
Output:
length: 6line 1lin 1
length: 13line 2
lin 2
normalize-space() function and if statement
File: Data.xml
<poem>
<a>line 1</a>
<b>line 1</b>
<c>line 1</c>
<d>
line 1
</d>
</poem>
File: Transform.xslt
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output method="xml" omit-xml-declaration="yes" indent="no" />
<xsl:template match="a">
<xsl:if test="normalize-space(.) = normalize-space(../d)">
a = normalize-space(../d)
</xsl:if>
</xsl:template>
<xsl:template match="b|c|d" />
</xsl:stylesheet>
Output:
a = normalize-space(../d)
Use normalize-space() function to normalize space for elements and attributes
File: Data.xml
<employees>
<employee hireDate="09/01/1998">
<last>A</last>
<first>B</first>
<salary>95000</salary>
</employee>
<employee hireDate=" 04/23/1999">
<last>C</last>
<first>D</first>
<salary>100000</salary>
</employee>
</employees>
File: Transform.xslt
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output method="xml" omit-xml-declaration="yes" />
<xsl:template match="employee">
<xsl:value-of select="normalize-space(@hireDate)" />
<xsl:text>,</xsl:text>
<xsl:value-of select="normalize-space(first)" />
<xsl:text>,</xsl:text>
<xsl:value-of select="normalize-space(last)" />
</xsl:template>
</xsl:stylesheet>
Output:
09/01/1998,A,B
04/23/1999,C,D