Solved

Java application unable to read a Node value from an XML file.

Posted on 2013-12-17
5
460 Views
Last Modified: 2013-12-17
Can somebody please help me out with this?  I am trying to figure out why my java application is not returning the value of a Node from a Test.XML file that I set up.  The code for this application is pretty basic and I have gone over it numerous times but the answer for fixing this is just not coming to me.  Below is the java App, the XML file and the output.  There are no run-time errors when I execute the program.  It's simply not giving me all of the output that it's suppose to.

In the output, you will notice that the contents for the Node Test1 is blank.   It should be Sample1.  I cannot figure out why it is not returning the value.

Test.xml
<Test>
<settings>
  <Test1>sample1</Test1>
  <Test2>Sample2</Test2>
</settings>
<settings>
  <Test3>sample3</Test3>
  <Test4>Sample4</Test4>
</settings>
</Test>

Open in new window

Java code:
/*
	Note: This version of XML Reader has been modified to read a Test.XML file.
*/


import java.io.File;
import org.w3c.dom.Document;
import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException; 

public class XMLReader{

	public static void main (String argv [])
	{
		try
		{

			//This basically this section just opens the XML file so it can be read and processed.
			DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
			Document doc = docBuilder.parse (new File("C:\\Users\\Steve\\JavaDev\\Test\\XML\\Test\\Test.xml"));

			//Normalize text representation
			doc.getDocumentElement ().normalize ();
			System.out.println ("Root element of the doc is " + doc.getDocumentElement().getNodeName());


			NodeList listOfSettings = doc.getElementsByTagName("settings");
			int totalSettings = listOfSettings.getLength();
			System.out.println("Total number of settings: " + totalSettings);


			Node firstSettingsNode = listOfSettings.item(0);
			if(firstSettingsNode.getNodeType() == Node.ELEMENT_NODE)
			{

				Element firstSettingsElement = (Element)firstSettingsNode;

				//-------
				NodeList test1List = firstSettingsElement.getElementsByTagName("Test1");
				Element firstSettingslement = (Element)test1List.item(0);

				NodeList textTest1List = firstSettingsElement.getChildNodes();
				System.out.println("The contents of Test1 is " + 
				(( Node)textTest1List.item(0)).getNodeValue().trim());
			}

		}
		catch (SAXParseException err)
		{
			System.out.println ("** Parsing error" + ", line " + err.getLineNumber () + ", uri " + err.getSystemId ());
			System.out.println(" " + err.getMessage ());
		}
		catch (SAXException e)
		{
			Exception x = e.getException ();
			((x == null) ? e : x).printStackTrace ();
		}
		catch (Throwable t)
		{
			t.printStackTrace ();
		}

		System.exit (0);

	}//end of main
}

Open in new window

Output:
M:\Test\XML\Test>java XMLReader
Root element of the doc is Test
Total number of settings: 2
The contents of Test1 is

M:\Test\XML\Test>

Open in new window

0
Comment
Question by:srulison
  • 2
  • 2
5 Comments
 
LVL 35

Accepted Solution

by:
mccarl earned 500 total points
ID: 39725633
The crux of your problem is on line 45 and it involves the naming of your variable. Notice that you are missing the 'E' in    firstSettingsElement  

However, if you were to fix this, you will get a compiler error as you are already defining a variable of that name on line 41. So I am guessing, based on the naming of your other variables, that you actually intended this to be called something quite different. I am guessing the code section should have meant to be something like this...  (notice in particular the use of test1Element on lines 8 and 10)
			if(firstSettingsNode.getNodeType() == Node.ELEMENT_NODE)
			{

				Element firstSettingsElement = (Element)firstSettingsNode;

				//-------
				NodeList test1List = firstSettingsElement.getElementsByTagName("Test1");
				Element test1Element = (Element)test1List.item(0);

				NodeList textTest1List = test1Element.getChildNodes();
				System.out.println("The contents of Test1 is " + 
				(( Node)textTest1List.item(0)).getNodeValue().trim());
			}

Open in new window

The above code should work fine now.

However, just as a small shortcut, you can reduce the amount of code slightly using the below...
			if(firstSettingsNode.getNodeType() == Node.ELEMENT_NODE)
			{

				Element firstSettingsElement = (Element)firstSettingsNode;

				//-------
				NodeList test1List = firstSettingsElement.getElementsByTagName("Test1");
				System.out.println("The contents of Test1 is " + 
				test1List.item(0).getTextContent().trim());
			}

Open in new window

The .getTextContent() method saves you from having to actually find the TEXT node that is within the ELEMENT node.
0
 

Author Comment

by:srulison
ID: 39725796
Thank you so much for your help.  I don't if I would have ever found that missing E.  

In regards to your first comment about adding code tags, I'm not sure what you mean.  Can you provide an example of a posting that has code tags so I can have that for future reference?

Thank you again for your help.
0
 

Author Closing Comment

by:srulison
ID: 39725798
Exactly what I was looking for.
0
 
LVL 35

Expert Comment

by:mccarl
ID: 39725809
Not a problem, glad to help! :)

As for the code tags, I just edited your original question so that the Test.xml file, the Java code, and the resultant output were formatted as code blocks. It makes it easier to read anything of that nature, as it formats it in a fixed width font, and provides scroll bars to when there is a lot of content.

To do this just highlight the text/code that you want to format and then click the "Code" toolbar button in the editor toolbar just above where you type in comments (or questions). Here is an example of a code formatted block...

void sayHi() {
   return "Hello World";
}

Open in new window


And here is the screenshot of me formatting it...
Screenshot - formatting code block
0

Featured Post

Forrester Webinar: xMatters Delivers 261% ROI

Guest speaker Dean Davison, Forrester Principal Consultant, explains how a Fortune 500 communication company using xMatters found these results: Achieved a 261% ROI, Experienced $753,280 in net present value benefits over 3 years and Reduced MTTR by 91% for tier 1 incidents.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
I was working on a PowerPoint add-in the other day and a client asked me "can you implement a feature which processes a chart when it's pasted into a slide from another deck?". It got me wondering how to hook into built-in ribbon events in Office.
The viewer will learn how to implement Singleton Design Pattern in Java.
This video teaches viewers about errors in exception handling.

713 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question