?
Solved

Another piece of code on DOM seems to be giving a NullPointer Exception on <msg> tag

Posted on 2012-09-01
13
Medium Priority
?
434 Views
Last Modified: 2012-09-02
<logentry
   revision="1">
<date>2000-07-13T10:28:31.000000Z</date>
<paths>
<path
   action="A"
   kind="">/tags</path>
<path
   action="A"
   kind="">/trunk</path>
<path
   action="A"
   kind="">/branches</path>
</paths>
<msg>New repository initialized by cvs2svn.</msg>
</logentry>

Open in new window


For the above the snippet of code to parse is:
NodeList msglist=listEntryelement.getElementsByTagName("msg");
						Element msgelement=(Element)msglist.item(0);
						if(msgelement!=null){
						NodeList msgsublist=msgelement.getChildNodes();
						msg=((Node) msgsublist.item(0)).getNodeValue().trim();
						}
						else
						{
							msg="No Message";
						}

Open in new window


I am getting the exception at the line

msg=((Node) msgsublist.item(0)).getNodeValue().trim();
0
Comment
Question by:akashsuresh
  • 7
  • 6
13 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 38357504
You need to do the same you did for the outer Element:

NodeList msgsublist=msgelement.getChildNodes();
Element text = msgsublist.item(0);
if (text != null) {
  // Do it
}

Open in new window


I suspect there's only one text node though? If so, you might as well use hasChildNodes followed by getFirstChild
0
 
LVL 1

Author Comment

by:akashsuresh
ID: 38357547
Well for every log entry there is one message,So for 100 log entries,100 messages.

Can you explain your last statement.I am not quite proficient in DOM.

NodeList msglist=listEntryelement.getElementsByTagName("msg");
						Element msgelement=(Element)msglist.item(0);
						if(msgelement!=null){
						NodeList msgsublist=msgelement.getChildNodes();
						Element text=(Element) msgsublist.item(0);
						if(text!=null)
						{
						msg=((Node) text).getNodeValue().trim();
						}
						}
						else
						{
							msg="No Message";
						}

Open in new window



This gave me an error.
0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 2000 total points
ID: 38357583
Try

if(msgelement.hasChildNodes()) {
  msg = msgsublist.item(0).getFirstChild().getNodeValue().toString().trim();
}

Open in new window

0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 1

Author Comment

by:akashsuresh
ID: 38357594
NodeList msglist=listEntryelement.getElementsByTagName("msg");
						Element msgelement=(Element)msglist.item(0);
						if(msgelement.hasChildNodes()){
						NodeList msgsublist=msgelement.getChildNodes();
						
						msg=((Node) msgsublist.item(0)).getFirstChild().getNodeValue().trim();
						
						}
						else
						{
							msg="No Message";
						}

Open in new window


Is this how you meant it to be?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 38357613
It really depends on what kind of Node you're starting with. Using these DOM operation is hard work and highly error prone. You're doing yourself no favours by not using XPath. You could get all message text with

//msg/text()

Open in new window


in one go

http://technojeeves.com/joomla/index.php/free/63-xpath-tester
0
 
LVL 1

Author Comment

by:akashsuresh
ID: 38357626
I understand that.However I have been working on this for a long time now and this is the last and final flaw to correct.I should have taken xpath from the very beginning but unfortunately I am already on the end of the road.

PathInfo path1=new PathInfo(null,null,null);
		List<LogProcess> logobject=new LinkedList<LogProcess>();
		List<PathInfo> pathinfo=new LinkedList<PathInfo>();
		List<PathInfo> alp4=new LinkedList<PathInfo>();
		ArrayList<String> pi10=new ArrayList<String>();
		
		try{
			
				DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
			
				DocumentBuilder db=dbf.newDocumentBuilder();
				Document d1=db.parse(fname);
				d1.getDocumentElement().normalize();
				
				NodeList logentrylist=d1.getElementsByTagName("logentry");
		
					Node n=logentrylist.item(0);
					Node att=n.getAttributes().getNamedItem("revision");
					
				NodeList list=d1.getElementsByTagName("author");
				
				int revision;
				Node temp,temp1;
				String author,date,msg = "None";
				al=new ArrayList<String>();
				
				for(int t=0;t<logentrylist.getLength();t++){
					Node list1=logentrylist.item(t);
						
					if(list1.getNodeType()==Node.ELEMENT_NODE)
					{
						Element listEntryelement=(Element)list1;
						Element le=(Element)logentrylist.item(t);
						
						NamedNodeMap nodelogmap=le.getAttributes();
						String rev=((Node)nodelogmap.item(0)).getNodeValue().trim();
						revision=Integer.parseInt(rev);
						NodeList authlist=listEntryelement.getElementsByTagName("author");
						Element authelement=(Element)authlist.item(0);
						if(authelement!=null){
						NodeList authsublist=authelement.getChildNodes();
						author=((Node) authsublist.item(0)).getNodeValue().trim();
						
						}
						else{
							author="Anonymous";
						}
						
						NodeList datelist=listEntryelement.getElementsByTagName("date");
						Element dateelement=(Element)datelist.item(0);
						NodeList datesublist=dateelement.getChildNodes();
						date=((Node) datesublist.item(0)).getNodeValue().trim();
						
												
						NodeList pathlist=listEntryelement.getElementsByTagName("path");
						
						
						pathinfo=new LinkedList<PathInfo>();
						for(int i=0;i<pathlist.getLength();i++)
						{//System.out.println(pathlist.getLength());
							Element pe=(Element)pathlist.item(i);
							
							NamedNodeMap peattr=pe.getAttributes();
							temp=peattr.item(0);
							temp1=peattr.item(1);
							
							path1=new PathInfo(temp.getNodeValue(),temp1.getNodeValue(),pe.getTextContent());
							pathinfo.add(path1);
							
							
						}
						
						NodeList msglist=listEntryelement.getElementsByTagName("msg");
						Element msgelement=(Element)msglist.item(0);
						if(msgelement.hasChildNodes()){
						NodeList msgsublist=msgelement.getChildNodes();
						
						msg=((Node) msgsublist.item(0)).getFirstChild().getNodeValue().trim();
						
						}
						else
						{
							msg="No Message";
						}
						LogProcess lp=new LogProcess(revision,author,date,pathinfo,msg);
						logobject.add(lp);
					
					}
						//System.out.println(pathinfo.size());	
						
						/*for(LogProcess lp3:logobject)
						{
							for(List<PathInfo> pi3:pathinfo)
							{
							  for(PathInfo pi7:pathinf)
							  {
								System.out.println(pi7.getFilepath());
							  }
							}
						}*

Open in new window


I would really appreciate if you could help me sort this out.

If you notice in the above code "datetist" works fine the same way,but msglist seems to mess up
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 38357639
You'd be better off just getting the <msg> element directly off each <logentry>
0
 
LVL 1

Author Comment

by:akashsuresh
ID: 38357655
I tried that already.does not work.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 38357722
Back later
0
 
LVL 1

Author Comment

by:akashsuresh
ID: 38358803
I found that the exception comes at the places where the tag shows <msg></msg>
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 2000 total points
ID: 38359017
The approach i mentioned works fine for me, whatever the state of the <msg> element:

import org.w3c.dom.*;

import java.io.*;

import java.util.*;

import javax.xml.parsers.*;


public class LogXml {
    public static void main(String[] args) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        DocumentBuilder db = dbf.newDocumentBuilder();
        Document d1 = db.parse(args[0]);
        d1.getDocumentElement().normalize();

        NodeList logentrylist = d1.getElementsByTagName("logentry");

        for (int i = 0; i < logentrylist.getLength(); i++) {
            Node n = logentrylist.item(i);
            Element e = (Element) n;
            NodeList msgs = e.getElementsByTagName("msg");

            for (int j = 0; j < msgs.getLength(); j++) {
                Node msg = msgs.item(j);

                if (msg.hasChildNodes()) {
                    System.out.println(msg.getFirstChild().getNodeValue().trim());
                }
            }
        }
    }
}

Open in new window

0
 
LVL 1

Author Comment

by:akashsuresh
ID: 38359125
You are a life saver.It works for me as well.Thank you so much
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 38359130
:)
How large is your log file btw?
0

Featured Post

[Webinar] Database Backup and Recovery

Does your company store data on premises, off site, in the cloud, or a combination of these? If you answered “yes”, you need a data backup recovery plan that fits each and every platform. Watch now as as Percona teaches us how to build agile data backup recovery plan.

Question has a verified solution.

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

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
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…
Suggested Courses
Course of the Month9 days, 7 hours left to enroll

621 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