Solved

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

Posted on 2013-12-17
5
451 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

Control application downtime with dependency maps

Visualize the interdependencies between application components better with Applications Manager's automated application discovery and dependency mapping feature. Resolve performance issues faster by quickly isolating problematic components.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Android studio getdrawable(int) is deprecated 4 43
backtracking recursion  code 19 54
factorial example 4 35
reverse digits of a number using for loop 5 36
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

895 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now