Solved

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

Posted on 2013-12-17
5
467 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
5 Comments
 
LVL 36

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 36

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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Convert websphere application server default chained Certificates from 1024 to 2048 keysize or higher size and also you can change signatureAlgorithm . Please make sure Websphere Application Server fixpack 7.0.0.23 or Above. The following steps a…
Create a Windows 10 custom Image with custom task bar and custom start menu using XML for deployment.
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

707 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