Java Video Tutorial 44

Parse XML JavaAfter I made my XML Video Tutorial, you asked me to show you how to parse XML with Java. So, that is what I’m doing in this tutorial.

I wasn’t sure how much to cover, because I could literally create a 5 part series on this topic. I decided to cover the basics in the video and provide another example in the code below.

If you want to see more, tell me and I’ll cover more on parsing XML with Java.

If you like videos like this, please tell Google [googleplusone]

Sharing is always appreciated

Code from the Video


// Simple API for XML only allows you to read from an XML 
// file. SAX doesn't require you to read the document into memory

import org.xml.sax.*;

// Used to read an XML file into memory where the doc is 
// stored as a bunch of objects. You can write back to the file

import org.w3c.dom.*;

// Used to gather XML elements into DOM objects

import javax.xml.parsers.*;

public class Lesson44{
	public static void main(String[] args){
		// Creates a DOM object in memory. Now you can access
		// data in the xml file
		Document xmlDoc = getDocument("./src/tvshows5.xml");
		// Get the name of the root element
        System.out.println("Root element is " + 
        // The nodelist contains all of the nodes in the xml file
        NodeList listOfShows = xmlDoc.getElementsByTagName("show");
     // Get the number of children in the root element
        System.out.println("Number of shows " + listOfShows.getLength());
        // The element you want to print out
        String elementName = "network";
        // The attribute to search for
        String attrName = "country";
        // Send the NodeList for processing
        getElementAndAttrib(listOfShows, elementName, attrName);
        // Additional Code not in the Video -------------------
		// Returns an Element object represented by the root element
		// of the xml file
		Element theRoot = xmlDoc.getDocumentElement();
		// Get the first child or show element in this situation
		Element showElement = (Element)theRoot.getFirstChild();
		// Object that will contain all of the show data
		tvShow tvs;
		// Cycle through all of the show elements until the end
		while(showElement != null){
			// Go get the first element in show which is name
			tvs = getShowData(showElement);
			// Print out the value of showName
			// Get the next show
			showElement = (Element)showElement.getNextSibling();

	// Reads an XML file into a DOM document
	private static Document getDocument(String docString) {
		try {
			// API used to convert XML into a DOM object tree
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			// Ignore all of the comments
			// Ignore white space in elements
			// Validate the XML as it is parsed
			// Provides access to the documents data
			DocumentBuilder builder = factory.newDocumentBuilder();
			// Takes the document 
			return builder.parse(new InputSource(docString));
		catch(Exception ex){
		return null;
	private static tvShow getShowData(Element ele){
		// Returns the first child element in the xml file. 
		// That element is name
		Element nameElement = (Element)ele.getFirstChild();
		// Save the value in this element as a String
		String showName = getTextValue(nameElement).trim();
		// Create a tvShow object that holds the values stored
		// in the show elements
		return new tvShow(showName);

	private static String getTextValue(Node theNode) {
		// Get the value of the first child element
		return theNode.getFirstChild().getNodeValue();
	private static void getElementAndAttrib(NodeList listOfShows, String elementName, String attrName){
			// Cycle through the number of shows
        	for(int i=0; i < listOfShows.getLength(); i++){
        		// Get the first show node
        		Node showNode = listOfShows.item(i);
        		// Convert into an element to gain access to element methods
        		Element showElement = (Element)showNode;
        		// Create a list of nodes that have the name defined in elementName
        		NodeList networkList = showElement.getElementsByTagName(elementName);
        		// Get the first and only element in this situation
        		Element networkElement = (Element)networkList.item(0);

        		// Returns a list of node elements
        		// Each value is in a node in side of the network node
        		// That's why you have to get the child nodes for network
                NodeList elementList = networkElement.getChildNodes();
                // Check if the element has the attribute set

                	System.out.println(elementName + " : " + ((Node)elementList.item(0)).getNodeValue().trim() +
                		" has attribute " + networkElement.getAttribute(attrName));
                } else {
        catch(Exception ex){
	private static class tvShow{
		public String showName, showNetwork;
		public tvShow(String showName){
			this.showName = showName;

XML File I Use

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE tvshow SYSTEM "tvshows5.dtd" >
<?xml-stylesheet type="text/xsl" href="tvshows5.xsl" ?>
    <name id_code="show_001">Life On Mars</name>
    <network country="US">ABC</network>
    <description>The series tells the story of New York City police detective Sam Tyler.</description>
			<real_name>Jason O'Mara</real_name>
			<character profession="Detective">Sam Tyler</character>
			<real_name>Michael Imperioli</real_name>
			<character profession="Detective">Ray Carling</character>	
	<poster href=",0,214,317_.jpg" width="214" height="317" />
    <viewers units="million">7.82</viewers>
    <name id_code="show_002">Life On Mars</name>
    <network country="UK">BBC</network>
    <description>The series combines elements of science fiction and police procedural.</description>
			<real_name>John Simm</real_name>
			<character profession="Detective">Sam Tyler</character>
			<real_name>Philip Glenister</real_name>
			<character profession="Detective">Gene Hunt</character>	
	<poster href=",0,214,317_.jpg" width="214" height="317" />
    <viewers units="million">6.8</viewers>
    <name id_code="show_003">Freaks and Geeks</name>
    <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>
			<real_name>Linda Cardellini</real_name>
			<character profession="Student">Lindsay Weir</character>
			<real_name>John Francis Daley</real_name>
			<character profession="Student">Sam Weir</character>
	<poster href=",0,214,317_.jpg" width="214" height="317" />
    <viewers units="million">6.77</viewers>
    <name id_code="show_004">Pushing Daisies</name>
    <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>
			<real_name>Lee Pace</real_name>
			<character profession="Baker">Ned</character>
			<real_name>Anna Friel</real_name>
			<character profession="Baker">Charlotte Chuck Charles</character>
	<poster href=",0,214,317_.jpg" width="214" height="317" />
    <viewers units="million">7.78</viewers>

25 Responses to “Java Video Tutorial 44”

  1. mr.roshik says:

    Thanks for sharing, whts your next tutorial series ?

  2. mr.roshik says:

    superb bro.

    • admin says:

      Thank you 🙂 Part 46 is going to be really good

      • Peter says:

        I appreciate the video very much. As a Noob, I spent several hours trying to determine why I was getting a “document not properly formed error”. Turns out that the DTD file is not listed along with the code. I only learned this after a considerable amount of internet research and going to your XML 4 tutorial. Please help Noobs by keeping all the associated code together for each video. But, I also learned more about XML in general during my research on StackOverflow, so its good & bad.

  3. Ven V. says:

    Fantastic explanation of parsing xml file in JAVA with examples.
    Appreciate your lecture whole-heartedly.

  4. Niraj says:

    Warning: validation was turned on but an org.xml.sax.ErrorHandler was not
    set, which is probably not what is desired. Parser will use a default
    ErrorHandler to print the first 10 errors. Please call
    the ‘setErrorHandler’ method to fix this.
    Error: URI=file:///home/niraj/webcode/Lesson44/src/tvshow.xml Line=4: Element type “tvshow” must be declared.
    Error: URI=file:///home/niraj/webcode/Lesson44/src/tvshow.xml Line=5: Element type “show” must be declared.
    Error: URI=file:///home/niraj/webcode/Lesson44/src/tvshow.xml Line=6: Element type “name” must be declared.
    Error: URI=file:///home/niraj/webcode/Lesson44/src/tvshow.xml Line=7: Element type “release” must be declared.
    Error: URI=file:///home/niraj/webcode/Lesson44/src/tvshow.xml Line=8: Element type “network” must be declared.
    Error: URI=file:///home/niraj/webcode/Lesson44/src/tvshow.xml Line=9: Element type “description” must be declared.
    Error: URI=file:///home/niraj/webcode/Lesson44/src/tvshow.xml Line=10: Element type “actors” must be declared.
    Error: URI=file:///home/niraj/webcode/Lesson44/src/tvshow.xml Line=11: Element type “actor” must be declared.
    Error: URI=file:///home/niraj/webcode/Lesson44/src/tvshow.xml Line=12: Element type “real_name” must be declared.
    Error: URI=file:///home/niraj/webcode/Lesson44/src/tvshow.xml Line=13: Element type “character” must be declared.
    Root element is tvshow
    Number of shows 4
    network : ABC has attribute US
    network : BBC has attribute UK
    network : ABC has attribute US
    network : ABC has attribute US

  5. Nicholas Bukovec says:

    I replaced the document src with a web address, but I always get a 403 error. How can I get past this?

  6. Karthik says:

    You are Awesome !!!….. thanks a ton for all your tutorials…..
    please let me know if you have some online tutorials (advanced Java )… to handle very large xml files (somewhere between 1- 5 GB)…
    god bless you….
    take care…. coz you are very important…

  7. Eviatar Levy says:

    hi i like your tutorials, they are very helpfull for me!
    thank you!
    if you can, it will be great to have one tutorial about xml SAX
    parser. they are common as well..

    take care…

  8. anon says:

    Doesn’t like this line:

    Element showElement = (Element)theRoot.getFirstChild();

    Exception in thread “main” java.lang.ClassCastException: cannot be cast to org.w3c.dom.Element
    at readingXMLTest.Lesson44.main(

    Casting error. New to this, so a little unsure on what the particulars are between Elements & Nodes… ugh, going to take some reading.

  9. Ash says:

    Very interesting tutorial.

    I have a general question tho.

    What would you recommend to use to update the xml element content . Basically , what is the best way to copy one node content to another node?

    ex : Just to make it more clear. what would you recommend to copy “Copy me” and replace “text”…hope that makes sense…

    Copy me


  10. Ben says:


    Thanks a lot for your great tutorial
    Is there a way to dl the code ? I can not copy paste the code , it takes some other things with it

    • Derek Banas says:

      You’re very welcome 🙂 If you put your mouse over the top right corner of the code, 3 icons pop up. Click on the one named view source and you’ll get the code without line numbers. Sorry about that

  11. Shital says:

    Hi Derek,

    Your tutorials are amazing, I am following those since few months, I liked it very very much!Kudos to you for providing such wonderful tutorials that to free! and your efforts for creating those! Lots of blessings to you!

Leave a Reply

Your email address will not be published.