Solved

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

Posted on 2013-12-17
5
450 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
Comment Utility
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
Comment Utility
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
Comment Utility
Exactly what I was looking for.
0
 
LVL 35

Expert Comment

by:mccarl
Comment Utility
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

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Suggested Solutions

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
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:

771 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

11 Experts available now in Live!

Get 1:1 Help Now