Updated April 18, 2023
Introduction to XSLT normalize-space
The following article provides an outline for XSLT normalize-space. The normalize-space function defines a technique used to control whitespace in a given text, and it is a part of the string function in Xpath. The term replaces a sequence of whitespace characters with a single space and returns the string element, and falls in an XPath Function. It is a process that removes consecutive white spaces in a PCDATA into a single space. Its work is to clean up the whitespaces by removing all leading and trailing spaces.
Syntax:
normalize-space(string)
str = " hello world "
normalize-space(string)
The above syntax takes an argument as a string to replace whitespaces.
How normalize-space Function Work in XSLT?
This function is used in XSLT filters for the removal of significant whitespace characters. The normalised-space function being an advanced concept of XPATH makes trim of the whitespaces. If needed globally, a template match is used.
<xsl:template match=”text()”>
<xsl:value-of select=”normalize-space(.)”/>
</xsl:template>
After applying this function, the text become normalized with no line breaks. If the function doesn’t specify any argument, then it takes the current node and normalizes it. This is very normal to the function trim() in java.lang.string.
Let’s take an XML Document:
<text>
A
a character string with parameters
</text>
Suppose we have an XSL template to perform the above space modification:
<xsl: template match = " string ">
+++ <xsl: value-of select = " normalize-space (.) " /> ---
</ xsl: template>
And the result would be:
This function returns an empty string in case of an empty Sequence
Considering different cases where the whitespaces are added before or after the elements, the normalize-space() simplifies the test.
normalize-space('helicopters') --> query
normalize-space(' helicopters ') --> query
normalize-space('USA helicopters') --> USA query
normalize-space('USA helicopters') --> USA helicopters
normalize-space('USA
helicopters') --> USA helicopters
normalize-space('') --> zero-length string
normalize-space(' ') --> zero-length string
normalize-space(()) --> zero-length string
normalize-space( helicopters ) --> helicopters
Even it works well with the attributes which have got new lines.
HTML Code:
<label id='has caffeine choclates '> aaaa</label>
xpath
//label[normalize-space(@id) ='has caffeine choclates']
Even it eliminates spacing in one pass with the HTML tags.
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" omit-xml-declaration="no" encoding="UTF-8"/>
<xsl:strip-space elements="*" />
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Text//*">
<xsl:value-of select="concat('<',fname(),'>')" />
<xsl:apply-templates />
<xsl:value-of select="concat('</',fname(),'>')" />
</xsl:template>
<xsl:template match="text()">
<xsl:value-of select="normalize-space(.)"/>
</xsl:template>
Examples of XSLT normalize-space
Given below are the examples of XSLT normalize-space:
In the below section, we are representing an example where we can use the normalize-space function to build an application. So, this will help us to strip the leading and trailing space.
Example #1
Here we started by creating a normal XML document.
Code:
XML:
<Inventory>
<Goods importDate="07/02/1994">
<cargo>CGM Rivoli</cargo>
<container>France</container>
<Tons>85000</Tons>
</Goods>
<Goods importDate= "06/12/2000">
<cargo>Ever Glory</cargo>
<container>Tiwan</container>
<Tons>1500000</Tons>
</Goods>
</Inventory>
Next, we added lines to create an XSL Stylesheet.
XSL:
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="html" doctype-public="XSLT-compat" omit-xml-declaration="yes" encoding="UTF-8" indent="yes" />
<xsl:template match="Goods">
<xsl:value-of select="normalize-space(@importDate)" />
<xsl:text>,</xsl:text>
<xsl:value-of select="normalize-space(cargo)" />
<xsl:text>,</xsl:text>
<xsl:value-of select="normalize-space (container)" />
</xsl:template>
</xsl:transform>
Explanation:
- When the above stylesheet is applied to the XML file it produces the following output with the normalization under the space to produce a compatible result.
Output:
Example #2
Code:
XML:
<?xml version="1.0" encoding="utf-8"?>
<marine>
<canal path=" All over
World">
<Waterway>Suez Canal</Waterway>
<Waterway>Panama Canal</Waterway>
<Waterway>Baltic Sea</Waterway>
<Waterway>Houston
Ship</Waterway>
</canal>
</marine>
XSL:
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="html" doctype-public="XSLT-compat" omit-xml-declaration="yes" encoding="UTF-8" indent="yes" />
<xsl:template match="/">
<xsl:apply-templates />
</xsl:template>
<xsl:template match="*">
<xsl:copy>
<xsl:for-each select="@*">
<xsl:attribute name="{name()}">
<xsl:value-of select="normalize-space()"/>
</xsl:attribute>
</xsl:for-each>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="text()">
<xsl:value-of select="normalize-space()"/>
</xsl:template>
</xsl:transform>
Explanation:
- Here the main instructions process the root node with the text, and the extra space is completely ignored and identified the element and finally fetches the result of the marine element.
Output:
Example #3
Code:
Teamdemo.java:
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
public class Teamdemo
{
public static void main(String[] args) throws Exception
{
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document d= documentBuilder.parse("D:\team.xml");
XPathFactory xf = XPathFactory.newInstance();
XPath p= xf.newXPath();
//XPath normalize-space example
XPathExpression ex = p.compile("normalize-space(//Game[name='Sidney Crosby']/Members/text())");
String r= (String) ex.evaluate(d, XPathConstants.STRING);
System.out.println("The normalized role-string is : " + r);
}
}
XML:
team.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Players>
<Game type="Gymnastics">
<name>Dipa Karmakar</name>
<Members>Captain</Members>
<place>India</place>
</Game>
<Game type="NetBall">
<name>Marai Tutaia</name>
<Members>Goal Shooter</Members>
<place>New Zealand</place>
</Game>
<Game type="Squash">
<name>Saurav Ghosal</name>
<Members>leader</Members>
<place>Asia</place>
</Game>
<Game type="Cricket">
<name>Vishwa Fernando</name>
<Members>Batsman</Members>
<place>SriLanka</place>
</Game>
<Game type="Hockey">
<name>Sidney Crosby</name>
<Members> Over lap</Members>
<place>Pittsburgh</place>
</Game>
</Players>
Explanation:
- Now we have modified the source code that uses XML file and linking them with the java packages where the Xpath library takes normalize -space () to trim the spaces in the source document. Navigate the files in the same directory and compile using javac. To run the code, use > javac filename.java filename.xml. And the relevant results look this.
Output:
Example #4
Code:
XML:
<?xml version="1.0" encoding="UTF-8"?>
<Policy>
<PNo>46528415</PNo>
<Section>
<Scheme1>JAS</Scheme1>
<Scheme2>SHI</Scheme2>
<Scheme3>### Quatize ikkkkk </Scheme3>
</Section>
</Policy>
XSL:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" />
<xsl:template match="node() | @*">
<xsl:copy>
<xsl:apply-templates select="node() | @*" />
</xsl:copy>
</xsl:template>
<xsl:template match="Policy">
<Policy policyNumber="{PNo}">
<xsl:apply-templates select="Section" />
</Policy>
</xsl:template>
<xsl:template match="Section">
<xsl:copy>
<xsl:value-of select="concat(
normalize-space(Scheme1), '-',
normalize-space(Scheme2), '-',
normalize-space(Scheme3)
)" />
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Explanation:
- Here an attribute value template replaces all the spaces in the XML element under the schema 3 element by eliminating the line breaks, and the output looks like this. But if the XML input happens to contain more spaces or line feed it is necessary to address the mechanism.
Output:
Advantages of XSLT normalize-space
Given below are the advantages mentioned:
- Eliminates the newline around the elements. Multiple spaces are shrunk to a single space.
- It helps in collapsing sequences of white spaces into single spaces. And consistently, it makes rid of the extra whitespaces under the source document.
- Despite his simplicity, it is worth understanding thoroughly.
Conclusion
This article successfully avoids problems caused by whitespaces or newline in the XML document. Finally, we have studied the XSLT namespace example and how to use them in real cases. This function completely strips off the spaces from the starting to the end of the string.
Recommended Articles
This is a guide to XSLT normalize-space. Here we discuss the introduction, how the normalize-space function work in XSLT? and examples. You may also have a look at the following articles to learn more –