Querying XML Datastores with XPath – 7 – HackerRank Solution

In this post, we will solve Querying XML Datastores with XPath – 7 HackerRank Solution. This problem (Querying XML Datastores with XPath – 7) is a part of HackerRank Databases series.


XPath is a very valuable tool, often used for querying XML databases. XPath queries (or close variants) are also used in the process of Web Scraping while retreiving data from structured XHTML-compliant web pages, specially those with tabulated data.

A quick XPath tutorial is available here.

Provided XML Fragment and Task Description

Assume that you have been provided the fragment of XML, shown below. Your task is to write the XPath selector to compute the average popularity of movies, correct to 2 places of decimal.

The Ruby code for handling input, output and document construction has already been provided. You only need to fill up the required blanks as indicated in the template code provided. This challenge is agnostic to language-specific knowledge and you do not require to know ruby – as only the XPath selector needs to be completed by you.

<collection shelf="Classics">
<movie title="The Enemy" shelf="A">
   <type>War, Thriller</type>
   <description>Talk about a war</description>
<movie title="Transformers" shelf="B">
   <type>Science Fiction</type>
   <description>Science Fiction</description>
   <movie title="Trigun" shelf="B">
   <description>Quite a bit of action!</description>
<movie title="Ishtar" shelf="A">

Expected Output


Your code will also be run against a hidden test case, which is similar in schema and format to the XML fragment shown above – only some of the values in the fields will be changed. This is to prevent the submission of hard-coded answers.

Solution – Querying XML Datastores with XPath – 7 – HackerRank Solution

# Standard ruby library for XML parsing
require 'rexml/document'
include REXML

# Enter your code here. Read input from STDIN. Print output to STDOUT
xmlText = "" 

# Read the input XML Fragment
while line = gets()
   xmlText += line

doc = Document.new xmlText
# XPath Selector for computing the average popularity of the movies in the given XML fragment.
# Fill in the blanks to complete the required XPath selector query
puts XPath.match(doc,"sum(collection/movie/popularity) div count(collection/movie/popularity)")

Note: This problem (Querying XML Datastores with XPath – 7) is generated by HackerRank but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.

Leave a Comment

Your email address will not be published. Required fields are marked *