Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Groovy XML


May 14, 2021 Groovy


Table of contents


XML is a portable, open source language that allows programmers to develop applications that can be read by other applications, regardless of operating system and/or development language. ns.

What is XML?

Extensable tag language XML is a tag language that is very similar to HTML or SGML. T his is recommended by the World Wide Web Alliance and can be used as an open standard. es.

XML support in Groovy

The Groovy language also provides rich support for the XML language. The two most basic XML classes used are -

  • XML Tag Builder - Groovy supports Tree-based tag builder BuilderSupport, which can be sub-classified to generate various tree structure objects. b30> roovy's tag generator captures calls to pseudo-methods and converts them to elements or nodes of the tree structure. de. losures that are part of a method call are considered nested sub-contents of the resulting tree node.

  • XML Parser - The Groovy XmlParser class uses a simple model to parse XML documents into a tree of Node instances. ng. his model is sufficient for most simple XML processing.

For all the XML code examples, let's use the following simple XML file .xml to build the XML file and then read it.

<collection shelf = "New Arrivals"> 

   <movie title = "Enemy Behind"> 
      <type>War, Thriller</type> 
      <format>DVD</format> 
      <year>2003</year> 
      <rating>PG</rating> 
      <stars>10</stars> 
      <description>Talk about a US-Japan war</description> 
   </movie> 
	
   <movie title = "Transformers"> 
      <type>Anime, Science Fiction</type>
      <format>DVD</format> 
      <year>1989</year> 
      <rating>R</rating> 
      <stars>8</stars> 
      <description>A schientific fiction</description> 
   </movie> 
	
   <movie title = "Trigun"> 
      <type>Anime, Action</type> 
      <format>DVD</format> 
      <year>1986</year> 
      <rating>PG</rating> 
      <stars>10</stars> 
      <description>Vash the Stam pede!</description> 
   </movie> 
	
   <movie title = "Ishtar"> 
      <type>Comedy</type> 
      <format>VHS</format> 
      <year>1987</year> 
      <rating>PG</rating> 
      <stars>2</stars> 
      <description>Viewable boredom </description> 
   </movie> 
	
</collection> 

XML tag generator

Syntactic

public MarkupBuilder()

MarkupBuilder is used to construct the entire XML document. C reate an XML document by first creating objects for the XML document class. nt.

Let's look at an example of how to create a block by creating a movie element from the XML document above -

import groovy.xml.MarkupBuilder 

class Example {
   static void main(String[] args) {
      def mB = new MarkupBuilder()
		
      // Compose the builder
      mB.collection(shelf : 'New Arrivals') {
         movie(title : 'Enemy Behind')
         type('War, Thriller')
         format('DVD')
         year('2003')
         rating('PG')
         stars(10)
         description('Talk about a US-Japan war') 
      }
   } 
}

In the example above, the following points need to be noted:

  • mB.collection() - This is a tag generator that creates the header XML tag for the .lt;collection;/collection?gt;

  • movie (title: 'Enemy Behind') - These pseudo-methods use this method to create sub-tags with value tags. B y specifying a value called title, this actually means that a property needs to be created for the element.

  • Provide a closure to the pseudo-method to create the remaining elements of the XML document.

  • Initialize the default constructor of the class MarkupBuilder to publish the generated XML to the standard output stream

When we run the program above, we will get the following results -

<collection shelf = 'New Arrivals'> 
   <movie title = 'Enemy Behind' /> 
      <type>War, Thriller</type> 
      <format>DVD</format> 
      <year>2003</year> 
      <rating>PG</rating> 
      <stars>10</stars> 
      <description>Talk about a US-Japan war</description> 
   </movie> 
</collection>

In order to create the entire XML document, you need to do the following.

  • You need to create a mapping entry to store the different values of the element.
  • For each element of the map, we assign values to each element.
import groovy.xml.MarkupBuilder 

class Example {
   static void main(String[] args) {
      def mp = [1 : ['Enemy Behind', 'War, Thriller','DVD','2003', 
         'PG', '10','Talk about a US-Japan war'],
         2 : ['Transformers','Anime, Science Fiction','DVD','1989', 
         'R', '8','A scientific fiction'],
         3 : ['Trigun','Anime, Action','DVD','1986', 
         'PG', '10','Vash the Stam pede'],
         4 : ['Ishtar','Comedy','VHS','1987', 'PG', 
         '2','Viewable boredom ']] 
			
      def mB = new MarkupBuilder()  
		
      // Compose the builder
      def MOVIEDB = mB.collection('shelf': 'New Arrivals') {
         mp.each {
            sd -> 
            mB.movie('title': sd.value[0]) {  
               type(sd.value[1])
               format(sd.value[2])
               year(sd.value[3]) 
               rating(sd.value[4])
               stars(sd.value[4]) 
               description(sd.value[5]) 
            }
         }
      }
   } 
} 

When we run the program above, we will get the following results -

<collection shelf = 'New Arrivals'> 
   <movie title = 'Enemy Behind'> 
      <type>War, Thriller</type> 
      <format>DVD</format> 
      <year>2003</year> 
      <rating>PG</rating> 
      <stars>PG</stars> 
      <description>10</description> 
   </movie> 
   <movie title = 'Transformers'> 
      <type>Anime, Science Fiction</type> 
      <format>DVD</format> 
      <year>1989</year>
	  <rating>R</rating> 
      <stars>R</stars> 
      <description>8</description> 
   </movie> 
   <movie title = 'Trigun'> 
      <type>Anime, Action</type> 
      <format>DVD</format> 
      <year>1986</year> 
      <rating>PG</rating> 
      <stars>PG</stars> 
      <description>10</description> 
   </movie> 
   <movie title = 'Ishtar'> 
      <type>Comedy</type> 
      <format>VHS</format> 
      <year>1987</year> 
      <rating>PG</rating> 
      <stars>PG</stars> 
      <description>2</description> 
   </movie> 
</collection> 

XML parsing

The Groovy XmlParser class uses a simple model to parse the XML document into a tree of Node instances. ng. his model is sufficient for most simple XML processing.

Syntactic

public XmlParser() 
   throws ParserConfigurationException, 
      SAXException

The following code shows an example of how to read an XML document using an XML parser.

Let's assume that we have the same document, called .xml, and we want to parse the XML document and show the user the correct output. de.

import groovy.xml.MarkupBuilder 
import groovy.util.*

class Example {

   static void main(String[] args) { 
	
      def parser = new XmlParser()
      def doc = parser.parse("D:Movies.xml");
		
      doc.movie.each{
         bk->
         print("Movie Name:")
         println "${bk['@title']}"
			
         print("Movie Type:")
         println "${bk.type[0].text()}"
			
         print("Movie Format:")
         println "${bk.format[0].text()}"
			
         print("Movie year:")
         println "${bk.year[0].text()}"
			
         print("Movie rating:")
         println "${bk.rating[0].text()}"
			
         print("Movie stars:")
         println "${bk.stars[0].text()}"
			
         print("Movie description:")
         println "${bk.description[0].text()}"
         println("*******************************")
      }
   }
} 

When we run the program above, we will get the following results -

Movie Name:Enemy Behind 
Movie Type:War, Thriller 
Movie Format:DVD 
Movie year:2003 
Movie rating:PG 
Movie stars:10 
Movie description:Talk about a US-Japan war 
******************************* 
Movie Name:Transformers 
Movie Type:Anime, Science Fiction 
Movie Format:DVD 
Movie year:1989 
Movie rating:R 
Movie stars:8 
Movie description:A schientific fiction 
******************************* 
Movie Name:Trigun 
Movie Type:Anime, Action
Movie Format:DVD 
Movie year:1986 
Movie rating:PG 
Movie stars:10 
Movie description:Vash the Stam pede! 
******************************* 
Movie Name:Ishtar 
Movie Type:Comedy 
Movie Format:VHS 
Movie year:1987 
Movie rating:PG 
Movie stars:2 
Movie description:Viewable boredom

Important things need to be noted in the code above.

  • An XmlParser object is being formed so that it can be used to parse XML documents.

  • The parser is given the location of the XML file.

  • For each movie element, we use a closure to browse through each child node and display relevant information.

For the movie element itself, we use the symbol to display the title properties attached to the movie element.