Java Video Tutorial 45

Java XPATH Video TutorialI received a bunch of emails asking me to make a tutorial on Java XPath. I guess you liked my previous XML XPath tutorial?

XPath can be used to easily grab data from an XML file and into your Java code. I’ll cover how to write to an XML file the easy way in my next tutorial on JDOM2.

All of the code follows the video, and it is heavily commented to help you learn.

If you like videos like this, please tell Google

I always appreciate sharing

Code from the Video

JAVALESSON45.JAVA

// Provides everything you need to work with the DOM
// Document, Element, Node, NodeList, Text, Exceptions, etc.

import org.w3c.dom.*;

//XPath makes it easy to grab information from an XML document

import javax.xml.xpath.*;

// All the parsers for working with XML
// DocumentBuilder, DocumentBuilderFactory, SAXParser

import javax.xml.parsers.*;

import java.io.IOException;

// SAX Simple API for XML

import org.xml.sax.SAXException;

public class Lesson45 {

  public static void main(String[] args){

	  		// Allows your app to get a parser that turns a xml doc into a DOM tree
	  
	  		DocumentBuilderFactory domFactory = 
	  				DocumentBuilderFactory.newInstance();
	  		
	  		// Provides support for XML namespaces if needed
	  		
	  		domFactory.setNamespaceAware(true); 
	  		
	  		// Turns xml into a DOM tree
	  		
	  		DocumentBuilder builder;
	  		
	  		Document doc = null;
	  		
			try {
				
				// parses the file supplied
				
				builder = domFactory.newDocumentBuilder();
			
				doc = builder.parse("./src/tvshows5.xml");
			} 
			
			catch (SAXException e) {
				
				e.printStackTrace();
			} 
			
			catch (IOException e) {
				
				e.printStackTrace();
			} 
			
			catch (ParserConfigurationException e) {
				
				e.printStackTrace();
			}
			
			// Allows you to grab data from the document using the codes below
			
	  		XPath xpath = XPathFactory.newInstance().newXPath();
	  		
	  		getNodeNameAndValue(doc, xpath);
	
  }
  
  private static void getNodeNameAndValue(Document doc, XPath xpath){
	  
	  // XPath Query 
		XPathExpression expr;
		
		Object result = null;
		
		try {
			
			// Returns characters with the profession Student
			
			expr = xpath.compile("//show/actors/actor/character[@profession='Student']//text()");
	
			// Returns the result of the query
			
			result = expr.evaluate(doc, XPathConstants.NODESET);
		} 
		
		catch (XPathExpressionException e) {
			
			e.printStackTrace();
		}
		
		// Outputs the results of the query
		
		NodeList nodes = (NodeList) result;
		
		// Cycles through the results
		
		for (int i = 0; i < nodes.getLength(); i++) {
			
			// Print the matching node name and value
			
			System.out.println(nodes.item(i).getParentNode().getNodeName() + " " + nodes.item(i).getNodeValue()); 
			
		}
		
		// Display every name
		// : //show/name//text()
		
		// Display everything
		// : //show/*//text()
		
		// Show names based on an attribute 
		// : //show/name[@id_code='show_001']//text()
		
		// Show actors and character names
		// : //show/actors/actor/*//text()
		
		// Show character names if they are Students
		// : //show/actors/actor/character[@profession='Student']//text()
	  
  }
  
}

XML FILE USED

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE tvshow SYSTEM "tvshows5.dtd" >
<?xml-stylesheet type="text/xsl" href="tvshows5.xsl" ?>
<tvshow>
  <show>
    <name id_code="show_001">Life On Mars</name>
    <release>2008</release>
    <network country="US">ABC</network>
    <description>The series tells the story of New York City police detective Sam Tyler.</description>
    <actors>
		<actor>
			<real_name>Jason O'Mara</real_name>
			<character profession="Detective">Sam Tyler</character>
		</actor>
		<actor>
			<real_name>Michael Imperioli</real_name>
			<character profession="Detective">Ray Carling</character>	
		</actor>
	</actors>
	<poster href="http://ia.media-imdb.com/images/M/MV5BMTM4MDg2NTk1OF5BMl5BanBnXkFtZTcwNzI4OTY5MQ@@._V1._SY317_CR12,0,214,317_.jpg" width="214" height="317" />
    <viewers units="million">7.82</viewers>
    <end_date>2009</end_date>
  </show>
  
  <show>
    <name id_code="show_002">Life On Mars</name>
    <release>2006</release>
    <network country="UK">BBC</network>
    <description>The series combines elements of science fiction and police procedural.</description>
    <actors>
		<actor>
			<real_name>John Simm</real_name>
			<character profession="Detective">Sam Tyler</character>
		</actor>
		<actor>
			<real_name>Philip Glenister</real_name>
			<character profession="Detective">Gene Hunt</character>	
		</actor>
	</actors>
	<poster href="http://ia.media-imdb.com/images/M/MV5BMTQxNzc5MjQwNF5BMl5BanBnXkFtZTcwMjU3Njc4Mg@@._V1._SY317_CR8,0,214,317_.jpg" width="214" height="317" />
    <viewers units="million">6.8</viewers>
    <end_date>2007</end_date>
  </show>
  
  <show>
    <name id_code="show_003">Freaks and Geeks</name>
    <release>1999</release>
    <network country="US">ABC</network>
    <description>The show centers on a teenage girl, Lindsay Weir, and her brother, Sam, who both attend William McKinley High School during the 1980â1981 school year in the town of Chippewa, Michigan, a fictional suburb of Detroit.</description>
    <actors>
		<actor>
			<real_name>Linda Cardellini</real_name>
			<character profession="Student">Lindsay Weir</character>
		</actor>
		<actor>
			<real_name>John Francis Daley</real_name>
			<character profession="Student">Sam Weir</character>
		</actor>
	</actors>
	<poster href="http://ia.media-imdb.com/images/M/MV5BMTQ5OTEzODYyMl5BMl5BanBnXkFtZTcwMjcxNTcwMg@@._V1._SY317_CR24,0,214,317_.jpg" width="214" height="317" />
    <viewers units="million">6.77</viewers>
    <end_date>2000</end_date>
  </show>
  
  <show>
    <name id_code="show_004">Pushing Daisies</name>
    <release>2007</release>
    <network country="US">ABC</network>
    <description>The series stars Lee Pace as Ned, a pie-maker with the ability to bring dead things back to life with his touch, an ability that comes with stipulations.</description>
	<actors>
		<actor>
			<real_name>Lee Pace</real_name>
			<character profession="Baker">Ned</character>
		</actor>
		<actor>
			<real_name>Anna Friel</real_name>
			<character profession="Baker">Charlotte Chuck Charles</character>
		</actor>
	</actors>
	<poster href="http://ia.media-imdb.com/images/M/MV5BMTY3ODYxNjU1Nl5BMl5BanBnXkFtZTcwMTI0MTU1MQ@@._V1._SY317_CR0,0,214,317_.jpg" width="214" height="317" />
    <viewers units="million">7.78</viewers>
    <end_date>2009</end_date>
  </show>
  
</tvshow>

9 Responses to “Java Video Tutorial 45”

  1. chandra says:

    i would like to have compare two xmls which is having the namespace.

    Please explain how we can do it.

    Thanks,
    Chandra

  2. chandra says:

    I am not able to rad this xml

    WFS
    1212503
    OMNISALE
    1
    ZONA1
    30/04/2008

    can you please help me on this

  3. Sami says:

    Nice video. I got a problem to run the same code and same XML file on my mac. I have not made any changes. I installed Java JDK 1.7 as shown here (http://www.newthinktank.com/2011/12/install-java-1-7-eclipse/). I’m very sure from the correct file path. Although that, I got this error:

    java.io.FileNotFoundException: /Users/follower/myXPath/src/tvshows5.dtd (No such file or directory)

  4. jose maria says:

    thx dude, i really need this!!

Leave a Reply

Your email address will not be published.

Google+