How to minify and pretty print XML in JavaScript

5 months ago codedestine 0

How to minify and pretty print XML in JavaScript

In this tutorial, we will learn how to minify and pretty print XML in JavaScript. We will use vkbeautify java script plugin, it is a small and simple java script plugin to beautify XML, JSON or CSS text.How to minify and pretty print XML in JavaScript

Sample :-

XML for book type :-

<Book>
     <id>01</id>
     <language>Java</language>
     <edition>third</edition>
     <authors>
          <author>Herbert</author>
          <author>Json</author>
          <author>Andrew</author>
     </authors>
     <chapters>
          <Chapter-1>Introduction</Chapter-1>
          <Chapter-2>OOP's Concept</Chapter-2>
     </chapters>
</Book>

Minify :-

To minify XML string, we will use xmlmin ( text [,preserve_comments] ) method of the vkBeautify library.

Method :-   xml ( text [,indent_pattern] )

This method takes two parameters as an argument :-

  1. text :- It is a text, which you like to pretty print.
  2. indent_pattern :- It is a String or a Number, which is used to insert white spaces into the output XML string.

Let’s see the example :- 

<script>

var xmlText = "<Book>
     <id>01</id>
     <language>Java</language>
     <edition>third</edition>
     <authors>
          <author>Herbert</author>
          <author>Json</author>
          <author>Andrew</author>
     </authors>
     <chapters>
          <Chapter-1>Introduction</Chapter-1>
          <Chapter-2>OOP's Concept</Chapter-2>
     </chapters>
</Book>"

var minifyXML = vkbeautify.xmlmin(xmlText, true);
alert(minifyXML);

</script>

Pretty Print :-

To pretty print XML string, we will use xml ( text [,indent_pattern] ) method of the vkBeautify library.

Method :-   xml ( text [,indent_pattern] )

This method takes two parameters as an argument :-

  1. text :- It is a text, which you like to pretty print.
  2. indent_pattern :- It is a String or a Number, which is used to insert white spaces into the output XML string.

Let’s see the example :- 

<script>

var xmlText = "<Book><id>01</id><language>Java</language><edition>third</edition><authors><author>Herbert</author><author>Json</author><author>Andrew</author></authors><chapters><Chapter-1>Introduction</Chapter-1><Chapter-2>OOP's Concept</Chapter-2></chapters></Book>";

var prettyXML = vkbeautify.xml(xmlText, 5);

alert(prettyXML);

</script>

You may also like :-

  1. How to minify and pretty print JSON in JavaScript

References :- 

  1. vkbeautify Docs

That’s all for how to minify and pretty print XML in JavaScript, If you liked it, please share your thoughts in comments section and share it with others too.