Sometimes, when you have a large XML file and you need to “obtain” certain values in order to create an HTML structure, doing it by hand is just a nightmare… fortunately there is XSLT to save you time.

Requirements

  • Any Linux OS or cygwin
  • xsltproc installed

The XML Data

Let’s pick some XML example from somewhere in the web, like this one, it’s looks like Chemical data for medicines, it’s huge and it may pose some difficulty but it will do.

Our scenarios

A. How do we obtain the list of all chemicals in the XML, and create an HTML dropdown box from it?

First, take a look at the XML and find the path that contains the chemicals.

Looks like the path is /MedlineCitationSet/MedlineCitation/ChemicalList/Chemical, now let’s create the XSLT.

 

This small XSL will use a little of XPath, as you can see, the template starts the HTML select object then it uses a foreach based on the path that we need to read and since the path is not fully filtered, it will cycle all possible elements that matches that path. Now run the following command:

And you will get the following result:

This works smoothly and you didn’t have to create the HTML Select by hand.

B. I would like it to sort the HTML Select alphabetically, is it possible?

Yes, it is.

Just do that tiny adjustment and it will sort the nodes based on child “NameOfSubstance”.

 C. I see a lot of duplicated options, is there a way to clean the result and remove duplicates?

Yes, you can do the following adjustments:

This is a solution for XSLT 1.0, there are better solutions than this in 2.0, but the available XSLT Processor supports 1.0 only. As you can see on line 3, I’m declaring a key that matches all possible chemicals and the select on line 6 will create an ID for each cycle on which no more that 1 ID matches with the key, these makes all results unique.

D. Whoa! I forgot that we require the ID of the chemical as the value of the option, can we add it?

Yes and it’s easy to do:

You will have to tweak the select at the foreach section to grab the previous node after the filtering. With this, you can access the attribute UI (which it looks like the ID) and get the following results:

As you can see, XSL Transformations are really useful when you do manipulates huge XML files in order to obtain prepared structures like an HTML select.

Let me know if you find this post useful.

Follow me

Carlos Alberto Umanzor Arguedas

Web Developer at carlosumanzor.com
Web Developer, QA Engineer and Gamer Enthusiast, Developer of Linkcrawler and Father of a future computer ninja.
Follow me

Pin It on Pinterest

Shares
Share This
Optimization WordPress Plugins & Solutions by W3 EDGE