Trending February 2024 # How Regex Work In Scala? # Suggested March 2024 # Top 5 Popular

You are reading the article How Regex Work In Scala? updated in February 2024 on the website Kientrucdochoi.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested March 2024 How Regex Work In Scala?

Introduction to Scala Regex

This is a guide to Scala Regex. Regex stands for regular expression. We can define some pattern using regular expression and we can use this regular expression to test our input parameter passed. Regular expression is used in so many different programming languages. In scala they work in the same way like Java. We write our regular expression in some pattern or it is a sequence of character to check our string or integer passed is valid or not.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

How Regex work in Scala? 1. Convert string to regex object

To convert our string to regex object we can call r() method of scala to again recast it to regex object.

Syntax:

valstr = "Here is some string".r

In this above code what is happening like we are casting our string to regex object by calling r() method on it.

2. Direct assign to regex object

In this approach we can directly assign our string to regex object only without need of calling the r() method explicitly.

Syntax:

Scala Regex Functions

We have so many different functions available in scala regex class to handle our string or input passed.

Given below is the list of various functions with example:

1. findAllIn(source: CharSequence)

This will find the substring into the source string.

Example:

Code:

import scala.util.matching.Regex object Main extends App{ valstr = "Hello to all".r val source = "Hello to all from world" println(strfindFirstIn source) }

Output:

2. findAllMatchIn(source: CharSequence)

Find all non-overlapping. Print those string as output.

Example:

Code:

import scala.util.matching.Regex object Main extends App{ valstr = "Hello to all to test regularexpression".r val source = "Hello to all from world" println(strfindAllMatchIn source) }

Output:

3. findFirstIn(source: CharSequence)

This method will find the first occurrence of string from source and print it.

Example:

Code:

import scala.util.matching.Regex object Main extends App{ valstr = "to".r val source = "Hello to all from world" println(strfindFirstIn source) }

Output:

4. replaceAllIn()

It will replace the string with specified input.

Example:

Code:

import scala.util.matching.Regex object Main extends App{ valstr = "replacetest" valfinalstr = "replacetest".replaceAll(".test", "**") println("befor ::" + str) println("aftre ::" + finalstr) }

Output:

5. replaceFirst()

replace first occurrence.

Example:

Code:

import scala.util.matching.Regex object Main extends App{ valstr = "replacetest" valfinalstr = "replacetest".replaceFirst(".test", "**") println("befor ::" + str) println("aftre ::" + finalstr) }

6. matches()

This method is going to match the string with pattern we pass and it will return true or false based on the result or if it got the string matches with the pattern.

Example:

Code:

import scala.util.matching.Regex object Main extends App{ varstr = "check" valfinalstr = str.matches(".*k") println(finalstr) }

Output:

7. split(String regex, int limit)

It will give us the array in return, but we can limit the number of objects in the array while returning.

Example:

Code:

import scala.util.matching.Regex object Main extends App{ varstr = "somestring to test the result" valfinalstr = str.split(".ng", 4) for ( s1 <-finalstr ) { println( "Here the array ::"+s1) } }

Output:

Examples of Scala Regex

Given below are the examples mentioned:

Example #1

\d: It matched digit in any input passed [0-9]. This method checks for digit in an input.

Code:

import scala.util.matching.Regex object Main extends App{ valreg = new Regex("\d") valstr = "to check digit 520 in string" println((regfindAllInstr).mkString(", ")) }

Output:

Example #2

\D: This method checks in the input passes whether it contains the non-digit.

Code:

import scala.util.matching.Regex object Main extends App{ valreg = new Regex("\D") valstr = "to check string 520 in string" println((regfindAllInstr).mkString(", ")) }

Example #3

\S: Check the non-white space.

Code:

import scala.util.matching.Regex object Main extends App{ valreg = new Regex("\S") valstr = "to check string 520 in string" println((regfindAllInstr).mkString(", ")) }

Output:

Example #4

\s: This method basically checks for white space present in the string and print them. [tnrf]

Code:

import scala.util.matching.Regex object Main extends App{ valreg = new Regex("\s") valstr = "to check string 520 in string" println((regfindAllInstr).mkString(", ")) }

Output:

Example #5

Code:

import scala.util.matching.Regex object Main extends App{ valstr = "Check regular expression" println((regfindAllInstr).mkString(", ")) }

Output:

Example #6

.: This method is used to check the new line. “.” Check in the string or input parameter if contain any new line.

Code:

import scala.util.matching.Regex object Main extends App{ valreg = new Regex(".") valstr = "check for new line " println((regfindAllInstr).mkString(", ")) }

Output:

Conclusion

So Scala Regex is similar to any other regular expression. It is basically used for searching and parsing in our input parameters that we passed for validation purpose. We can create different type of pattern and validate our input against them. Regular expression provides us many unbuild expression as well.

Recommended Articles

We hope that this EDUCBA information on “Scala Regex” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

You're reading How Regex Work In Scala?

Learn The Working For Arraybuffer In Scala

Introduction to Scala ArrayBuffer

Scala ArrayBuffer is an indexed Sequence mutable data structure that allows us to add or change elements at a specific index. In ArrayBuffer we need not worry about the size; the size of an array buffer can be changed. It is mutable in nature. Random access to elements with the help of Array Buffer is high-speed. ArrayBuffer provides all the common methods for Sequence.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax and Parameters

For defining an Array Buffer, we use the following syntax.

We need to import the scala mutable Arraybuffer like this:-

import scala.collection.mutable.ArrayBuffer Val a = ArrayBuffer[datatype]()

// We define the datatype whatever we want to use over making a scala Array Buffer. It can be int, String, double, etc.

Scala ArrayBuffer Working with Examples

Also, if we want to access the element, the index is traversed and checked for that element to see if it is present, and then only the element is traversed.

The Keyword new is not necessary to invoke an object for ArrayBuffer because it has an apply method with it. So we can create an object for an ArrayBuffer directly.

Let us check out an example:

1. Ways to create an ArrayBuffer:

import scala.collection.mutable.ArrayBuffer import scala.collection.mutable.ArrayBuffer

2. Without the use of a new keyword.

val a = ArrayBuffer[Int]() a: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer()

3. With the use of a new keyword.

val b = new ArrayBuffer[Int]() b: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer()

4. String type array buffer.

val b = new ArrayBuffer[String]() b: scala.collection.mutable.ArrayBuffer[String] = ArrayBuffer()

5. Double-type array buffer.

val b = new ArrayBuffer[Double]() b: scala.collection.mutable.ArrayBuffer[Double] = ArrayBuffer()

We can also use the .toBuffer method to create an ArrayBuffer. Also, the ArrayBuffer.range function will generate the ArrayBuffer as given.

Let us check that with an example:

(1 to 5).toBuffer res16: scala.collection.mutable.Buffer[Int] = ArrayBuffer(1, 2, 3, 4, 5) (1 until 5).toBuffer res17: scala.collection.mutable.Buffer[Int] = ArrayBuffer(1, 2, 3, 4) ('a' to 'c').toBuffer res18: scala.collection.mutable.Buffer[Char] = ArrayBuffer(a, b, c) ("String1").toBuffer res19: scala.collection.mutable.Buffer[Char] = ArrayBuffer(S, t, r, i, n, g, 1) ArrayBuffer.range(1,5) res22: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 3, 4)

Even fill and tabulate methods can also be used to create an ArrayBuffer.

Example #1 – ADDING elements in an ArrayBuffer b+="This" res4: chúng tôi = ArrayBuffer(String1, This) b+="is" res5: chúng tôi = ArrayBuffer(String1, This, is) b+="a" res6: chúng tôi = ArrayBuffer(String1, This, is, a) b+="sample string" res7: chúng tôi = ArrayBuffer(String1, This, is, a, sample string) b+="Arraybuffer" res8: chúng tôi = ArrayBuffer(String1, This, is, a, sample string, Arraybuffer) println(b) ArrayBuffer(String1, This, is, a, sample string, Arraybuffer)

Code Snippet:

Example #2 – Adding Two or More Elements

We can use the append method to append two or more elements in an ArrayBuffer simultaneously. Let us check with an example:

val c = ArrayBuffer[String]() c: scala.collection.mutable.ArrayBuffer[String] = ArrayBuffer() c+=("Adding","more","than","one","elements") res10: chúng tôi = ArrayBuffer(Adding, more, than, one, elements) c.append("Other Method!","for Adding") println(c) ArrayBuffer(Adding, more, than, one, elements, Other Method!, for Adding)

Code Snippet:

Example #3 – Accessing Elements in ArrayBuffer

We can access the elements from an array buffer by traversing the index of an ArrayBuffer.

Let us check that with an example:

println(c) ArrayBuffer(Adding, more, than, one, elements, Other Method!, for Adding) for(i<- 0 to c.length-1){ | println(c(i)) | } Adding more than one elements Other Method! for Adding c(0) res33: String = Adding c(1) res34: String = more c(2) res35: String = than c(3) res36: String = one

Example #4 – Deleting Elements from Array Buffer

We can remove elements from an Array Buffer using the (-) operator. This removes the elements from an ArrayBuffer.

Even we can use remove and clear to remove an element or clear it from an ArrayBuffer.

val a = ArrayBuffer("Arpit","Anand","String1") a: scala.collection.mutable.ArrayBuffer[String] = ArrayBuffer(Arpit, Anand, String1) a-= "Arpit" res0: chúng tôi = ArrayBuffer(Anand, String1) a.remove(0) res1: String = Anand a.clear println(a) ArrayBuffer()

We can use the reducetoSize function to reduce the length of ArrayBuffer, whatever length we want to.

Let us check that with an Example:

val a = ArrayBuffer("Arpit","Anand","String1","String2") a: scala.collection.mutable.ArrayBuffer[String] = ArrayBuffer(Arpit, Anand, String1, String2) a.reduceToSize(2) println(a) ArrayBuffer(Arpit, Anand)

This reduces the size of ArrayBuffer to the length of 2.

Example #5 – Updating Elements in Array Buffer

You can update an array of buffer elements within an ArrayBuffer by using the “update” method on the elements.

val a = ArrayBuffer("Arpit","Anand","String1","String2") a: scala.collection.mutable.ArrayBuffer[String] = ArrayBuffer(Arpit, Anand, String1, String2) a.update(0,"UpdatedString") println(a) ArrayBuffer(UpdatedString, Anand, String1, String2)

So this gives an updated ArrayBuffer over.

The Head and Tail Function will provide the Head and Tail of an array buffer.

ArrayBuffer(UpdatedString, Anand, String1, String2) a.head res8: String = UpdatedString a.tail res9: scala.collection.mutable.ArrayBuffer[String] = ArrayBuffer(Anand, String1, String2)

The .take() function will take the elements inside it.

a.take(2) res10: scala.collection.mutable.ArrayBuffer[String] = ArrayBuffer(UpdatedString, Anand)

The .isEmpty() function checks whether the Arraybuffer is Empty or not.

a.isEmpty res12: Boolean = false

The .toArray function is used to change the Arraybuffer into Array.

a.toArray res13: Array[String] = Array(UpdatedString, Anand, String1, String2)

From the above method and function, we saw how ArrayBuffers works and its associated function.

Conclusion – Scala ArrayBuffer

From the above article, we came across the working and various concepts for ArrayBuffer in Scala. We came across the multiple functions and methods used by the ArrayBuffer class and learned the functionalities there. With the multiple examples, we saw how ArrayBuffer could be used with different data types and the idea behind using it.

So the above article concludes the proper usage, syntax, and functionalities of ArrayBuffer.

Recommended Articles

We hope that this EDUCBA information on “Scala ArrayBuffer” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

How Expose Work In Docker

Introduction to Docker EXPOSE

Docker EXPOSE is a Dockerfile directive or instruction specified in the Dockerfile to inform that the image created by this Dockerfile will listen on this port when running a container. It does not expose the mentioned port; rather, it is just a type of documentation that tells a person who runs the container about the port that needs to be exposed or published to allow communication to the container from outside. We have to use the ‘-p’ option while running the container to publish the port so that the application hosted inside the container can be accessed externally.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax:

Here is the syntax for the ‘EXPOSE’ instruction in Dockerfile:

We have to specify at least one port. The protocol is optional, we can specify whether the application is going to listen on TCP or UDP port, and protocol is not specified, then TCP is going to use by default.

How EXPOSE works in Docker?

As we know, it is only used for documentation; there is no special functionality included in this instruction which means if we don’t include this instruction in the Dockerfile, the image created using Dockerfile is still going to work in the same way, but yes, if Docker image is created by someone else and the container is getting created by someone else then who is going to create the container will get confused that on which port application is listening.

Example of Docker EXPOSE

Given below is the example of Docker EXPOSE:

We will create two nginx images with and without the ‘EXPOSE’ instruction mentioned in the Dockerfile and try to access the nginx within the container, from different containers, and from the host.

Dockerfile with ‘EXPOSE’ instruction:

Code:

EXPOSE 80

Dockerfile without ‘EXPOSE’ instruction:

Code:

RUN apt-get install -y curl

Step 2: Let’s build Docker images using the above two Dockerfile.

Code:

docker image ls

Output:

Step 3: Now, start a container using the ‘nginx:expose’ image, connect to it, and access the default page of nginx.

Code:

Output:

In the above snapshot, we can see that the nginx default page is accessible.

Step 4: Let’s check the IP address of this container so that we can connect this from a different container.

Code:

#ip addr

Output:

Step 5: Let’s create another container that has curl already installed and access the nginx default page using the IP address of the nginx:expose container.

Code:

In the above snapshot, we can see that we can successfully access the nginx default page running from a different container.

Note: The ‘ubuntu:curl’ image has been created using the below Dockerfile:

FROM ubuntu

RUN apt-get update && apt-get install curl -y

Step 6: Finally, let’s try to access it from the host.

Code:

Output:

Step 7: So, we are unable to access the nginx default page because the port has not been exposed while running the container in step 3. Let’s run another container with the same image ‘nginx:expose’ but expose the port 80 this time.

Code:

docker run -d  -p 80:80 nginx:expose

Output:

In the above snapshot, we can see that we can access the nginx default page from the host on port 80 as well.

Step 8: Let’s create a new container using the ‘nginx:no_expose’ image and expose the port 8080 on the host as we have already used port 80.

Code:

In the above snapshot, we are able to access the default page from inside the container.

Step 9: Let’s check the container’s IP address and access it from a different container that we have used above.

Code:

#ip addr

Output:

Code:

Output:

In the above snapshot, we can see that the nginx default is accessible from the different container as well.

Step 10: Finally, access it from the host, but this time we have to use port 8080.

Code:

Output:

Advantages of Docker EXPOSE

It is a useful instruction to document the ports in the Dockerfile itself, on which that application will listen if a container is got created using that image.

It clarifies the confusion that might occur between who has created the Docker image and who is going to run the container using that image.

Conclusion

Sure enough, the above scenario has clarified that the ‘EXPOSE’ instruction is only used for documentation in the Dockerfile as we have seen that both containers are behaving in the same way in terms of functionality whether we have mentioned the ‘EXPOSE’ instruction or not.

Recommended Articles

Docker system prune

Docker Start

Docker Stack

Docker Stop Container

How Does Annotation Work In Kubernetes?

Kubernetes Annotations

Web development, programming languages, Software testing & others

How does Annotation Work in Kubernetes?

Annotations have key/value pairs same as labels. Annotation key consists of two parts, a prefix which is optional, and a name. These two parts are separated by a slash ‘/’. The name part is mandatory and it is not longer than 63 characters. It starts and ends with alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and alphanumeric in between. The prefix is optional however if specified it must be a DNS subdomain and length must be 253 characters or less and ends with a slash (/) If automated system components such as kube-controller-manager, kube-scheduler, kube-apiserver, kubectl or any other third party automation) add annotations to the end-user Kubernetes objects, it must specify a prefix. There are two reserved prefixes ‘kubernetes.io/’ and ‘k8s.io/’ for Kubernetes core components.

We use the “annotations” keyword to add an annotation to the object. Annotations are also key/value pairs like labels as shown below:

"metadata": { "annotations": { "key1" : "value1", "key2" :  "value2", "key3" :"value3" } } Examples of Kubernetes Annotations

Let’s understand the examples of Kubernetes Annotations with Syntax.

Example 1

We have an nginx pod and we want to attach annotations like on-call person pager number, URL or name of the image registry and link of knowledge base article, etc. We can add these details under annotations under metadata primitives. There are default annotations attached by the ‘kubectl’ to every Kubernetes objects whether we attach annotations to the Kubernetes object or not. This annotation is the ‘kubectl.kubernetes.io/last-applied-configuration’. Let’s create a pod using below yaml file.

apiVersion: v1 kind: Pod metadata: name: nginx-web-server labels: env: prod app: nginx-web spec: containers: - name: nginx image: nginx ports: - containerPort: 80

After creating the pod, we use below two commands to check the attached annotation:

Syntax: 

Example 2 $kubectl describe pod nginx-web-server

$kubectl get pods nginx-web-server -o custom-columns=ANNOTATIONS:.metadata.annotations

Explanation: In the above example, there is no annotation attached to the pod however, there is an annotation attached to the pod and that is attached by Kubernetes core components as it has reserved prefix ‘kubernetes.io’ and name of the annotation is ‘last-applied-configuration’ which means it holds the last configuration applied to that object. The value of the annotation is truncated in the output we get from the first command. If we want to know or extract full value, we use the second command which output only key/value pairs of annotations.

Let’s create a pod and attach the annotations ‘oncallPager’, ‘imageregistry’, and ‘kbArticle’ as we discussed above. Below is the YAML configuration file for the same: –

apiVersion: v1 kind: Pod metadata: name: nginx-web-server labels: env: prod app: nginx-web annotations: oncallPager: 111-222-3333 spec: containers: - name: nginx image: nginx ports: - containerPort: 80

After deploying the above pod, we use the ‘kubectl describte’ command to see the attached annotations as shown in the below snapshot: –

Let’s output only annotations and see how it looks like. Here is the output: –

Explanation: In the above snapshot, the key/value pairs are not that much clear as compare to earlier output and it will be difficult to find the key/value pairs if there are many annotations attached to a Kubernetes object.

Scenarios of Kubernetes Annotations

There are many scenarios where annotations are very useful. Some use cases are as below:

We can add application build, release, or image information build number, release ID, git branch, registry address, image hashes, etc.

We can attach name, version, and build information of client library or tool for debugging purposes.

We can add user or tool/system information from where the objects originated. For example, objects can be created by automation tools like Jenkins in CI/CD model. It is very useful information who has created the Kubernetes object.

Attaching fields managed by a declarative configuration layer as annotations help to differentiate them from default values set by clients or servers, and from auto-generated fields and fields set by auto-sizing or auto-scaling systems.

We can also attach phone or pager numbers of the responsible person or directories or link where one can find that information if something bad happens.

The link of the knowledge base article or article number can be also attached to troubleshoot known issues related to that object.

We can add pointers to logging, monitoring, analytics, or audit repositories.

Conclusion

Kubernetes are similar to labels as it also has key/value pairs, however, it cannot be queried by Kubernetes itself but there are many tools that are configured to query objects based on their annotations, for example, Prometheus, third party tools, etc. Huge annotations do not the impact internal performance of Kubernetes so there are no keys and values constrained like labels.

Recommended Articles

We hope that this EDUCBA information on “Kubernetes Annotations” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

How Does Size Command Work In Linux?

Definition of Linux Size

The size command in Linux will allow listing the section size and the total size of the object files or the archived files in its argument list. In this tutorial, we will discuss its syntax, how to size command is used in Linux, its options, and its usages with different examples.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax of size command in Linux:

We can use the size command in Linux in a different format with different options, as shown below:

[–help] [–common] [objfile…]

How Does Size Command Work in Linux?

Size commands in Linux can be used in different ways with its options. Below are the options that can be used with the size command in Linux and its description.

Options Description

We can select the output style by mentioning the format either in SysV or Berkeley.

To display the numbers in order of octal, decimal, or hex.

-t        –totals To print the total size for Berkeley format only.

–common To print the total size of *COM* syms

 To set the binary object file format

 To scan the options from object-file

-h        –help To display the list of options available in the size command.

-v        –version To display the version of the program.

Examples of Linux Size Command

Following are the examples are given below:

1. To Get the Default Size Output

Syntax:

size directory_name

Example:

size /usr/var/log

The above result is in Berkeley format, and we can also get the same output in three different commands, as shown below:

2. Default File Option

In the current directory, it will check for ‘a.out’ file and calculate the size, displaying the result in Berkeley format.

Syntax:

size

Example:

size

3. To Get the Output in SysV Format

The output, when generated in SysV format, will print different sections along with the size and address of each section name.

Syntax:

size –format=SysV dir_name

Example:

size --format=SysV /usr/var/log

4. To Specify the Output Value in Decimal

When we pass the option ‘-d’ with the argument list, we will get the result in decimal value format as given in the example below.

Syntax:

size -d dir_name

Example:

size -d /usr/var/log

5. To Specify the Output Value in Octal Format

When we pass the option ‘-o’ with the argument list, we will get the result in octal value format as given in the example below.

Syntax:

size -o dir_name

Example:

size -o /usr/var/log

6. To Specify the Output Value in Hex Format

When we pass option ‘-x’ with the argument list, we will get the result in hex value format as given in the example below.

Syntax:

size -x dir_name

Example:

size -x /usr/var/log

7. Option –radix

For decimals, we can use the number format as –radix=10.

Syntax:

size –radix=10 /dir_name

Example:

size --radix=10 /usr/var/log

Radix option in the size command is used to specify the format number instead of using decimal, hex, or octal. For decimals, we can use the number format as –radix=10.

Syntax:

size –radix=10 /dir_name

Example:

Radix option in the size command is used to specify the format number instead of using decimal, hex or octal. For octal, we can use the number format as –radix=8.

Syntax:

size –radix=8 /dir_name

Example:

size -o /usr/var/log

Radix option in the size command is used to specify the format number instead of using decimal, hex, or octal. For hex, we can use the number format as –radix=16.

size --radix=16 /dir_name

Example:

size --radix=16 /usr/var/log

We can use only format numbers as 10,8,16 for decimal, octal, and hex, respectively. When we use other format numbers, we will get an error saying “Invalid radix.” Below is an example of an invalid radix format.

size --redix=12 /usr/var/log

8. To Display the Common Symbol Count

The common option allows printing the total number of all common symbols in the object file. By default, the format will take Berkeley file format; this will also be used to include in the value for column “bss.”

Syntax:

size -A --common /dir_name

Example:

size -A --common /usr/var/log

Option -A is used for SysV format. In the above example, the last line having *COM* will give the value.

9. To Display the Total in Berkeley Format

The option -t (or –totals) allows in displaying the new line at the end of the result that will print the value of all the object files that are in the list.

Syntax:

size -t /dir_name

Example:

size -t /usr/var/lo*

Conclusion

The size command in Linux is a very important command that will allow listing the section size and the total size of the object files or the archived files in its argument list. When the object file is not specified in the parameter list, the default file name used is ‘a.out’. The output formats can be displayed in different formats, such as decimal, octal, or hexadecimal. The tutorial above explains various options and provides examples to enhance understanding of these output formats.

Recommended Articles

We hope that this EDUCBA information on “Linux Size” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

How Do Variables Work In Xslt With Examples?

Definition of XSLT Variable

XSLT variable is defined as special tags used to declare a local or global variable that we make use of to store any values. The declared variables are referenced within an Xpath expression. Once it is set we cannot overwrite or update the variables. The scope of the element is done by the element that contains it. While we are setting a variable it could be done as global and local variables. The top-level element declared in the file is named as a global variable and the local variables are assigned within the template section.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax:

Following is the syntax declaration of the variable element.

How do variables work in XSLT?

The following templates assign the variable which includes both text and parameter values. The output is generated by referring to the value of the variable.

A variable takes a lot of types of values like integer or declared within XPath type expressions.

With Integer

With String

With Input document

For instance, let’s take a scenario like we need to output the book title of a respective Document in various places. We can do with the XSL variable and the book title is changed provided the changes done in one preferred location in the XSLT file. For example, we may need to use the value of current-time twenty times. Instead of passing a call to current-time(), we can call once and the corresponding value is stored in a variable.

Examples

Below example create a demo on two files  XSL and XML  with their elements and their child elements in the XML file and matches them with the XSL variable name. Let’s get started with the first demo.

Example #1 – Here is our XML file taking Book details

Following this file we have XSL style sheets with a template match by assigning a variable name to the values.

Explanation

Here an XML file is converted into a new XML file by assigning a variable name simultaneously  I have incremented the variable many times when need with the new variable.  The above code uses a global variable and could be accessed throughout the chúng tôi supports three modes of Output methods XML, HTML and Text. Here I have used HTML to show. Well, we can see the output like this:

Output:

Example #2

XML file

Xslt file

Explanation

As a result of adding this stylesheet and applying this rule of variable assignments, the output is generated. The resulting Output is given as follows:

Output:

Example #3

Xml file

XSL file

Here is a page

Explanation:

The above code uses three variable names and all the values are been assigned.

Output:

Advantages

XSL variables are very useful in many circumstances.

Variables help in avoiding long typing of XPath expression in case of complicated instructions.

XSL Being a Formatting language used for many XML Applications by providing elements and variable names with local or global declarations where they exclusively focus on formatting Objects.

Conclusion

XSLT is gaining much importance in business logic and produces a few best practices in achieving a good result in XSL. Therefore in this article, we have seen how variables are declared with the example.

Recommended Articles

This is a guide to XSLT Variable. Here we discuss the definition, syntax, How do variables work in XSLT? examples with code implementation. You may also have a look at the following articles to learn more –

Update the detailed information about How Regex Work In Scala? on the Kientrucdochoi.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!