• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 501
  • Last Modified:

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

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
srulison
Asked:
srulison
  • 2
  • 2
1 Solution
 
mccarlIT Business Systems Analyst / Software DeveloperCommented:
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
 
srulisonAuthor Commented:
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
 
srulisonAuthor Commented:
Exactly what I was looking for.
0
 
mccarlIT Business Systems Analyst / Software DeveloperCommented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now