Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6074337
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T10:22:15+00:00 2026-05-23T10:22:15+00:00

I have been working on this problem for quite some time and can’t figure

  • 0

I have been working on this problem for quite some time and can’t figure it out. There is a given “xml” file that needs to be parsed and displayed on the screen:

<office>

<name>joe</name>
<surname>smith</surname>
<name>bob</name>
<surname>black</surname>

.....
</office>

I’ve found some great samples of codes on line but they don’t seem to work with an xml file that’s not set up correctly as this one, so if I’d add a tag I can get my code to work, but the problem is I can’t make any changes to the “xml” file.

It is someone else’s code I found here that’s been modified.

Here is my code with mods:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;

import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException; 

public class ReadAndPrintXMLFile{

public static void main (String argv []) throws ParserConfigurationException, SAXException, IOException{



try {

        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document doc = docBuilder.parse (new File("office.xml"));

        // normalize text representation
        doc.getDocumentElement ().normalize ();
        System.out.println ("Root element of the doc is " + 
        doc.getDocumentElement().getNodeName() + "\n");

        //counts how many times <name> is found in the file
        //then the number is used in the for loop below             
        NodeList listOfTerms = doc.getElementsByTagName("name");

        int totalTerms = listOfTerms.getLength();
        System.out.println("Total no of terms : " + totalTerms + "\n");



        for(int s= 0; s<listOfTerms.getLength() ; s++){


            Node firstTermNode = listOfTerms.item(s);
            if(firstTermNode.getNodeType() == Node.ELEMENT_NODE){


                Element firstTermElement = (Element)firstTermNode;

                //-------
                NodeList firstWordList = firstTermElement.getElementsByTagName("name");
                Element firstWordElement = (Element)firstWordList.item(0);

                NodeList textWordList = firstWordElement.getChildNodes();
                System.out.println("Name : " + 
                       ((Node)textWordList.item(0)).getNodeValue().trim());

                //-------
                NodeList defList = firstTermElement.getElementsByTagName("surname");
                Element defElement = (Element)defList.item(0);

                NodeList textDefList = defElement.getChildNodes();
                System.out.println("Surname : " + 
                       ((Node)textDefList.item(0)).getNodeValue().trim());



            }//end of if clause


        }//end of for loop with s var


    }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
}

The error message I get is this:

java.lang.NullPointerException
    at Data.main(Data.java:45) //maybe a different line in the code for you.

If I use the root of the document for counter it prints the result once, for some reason getChildNodes() is not working correctly.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T10:22:16+00:00Added an answer on May 23, 2026 at 10:22 am

    I notice that you do a .getElementsByTagName(“name”) twice. Are you expecting <name> tags within <name> ? If not then that is most likely the cause of your error, since the second time, it would return an empty list and will cause a NullPointerException when you try to reference firstWordElement

    You can’t obtain the ‘surname’ from ‘name’ list which is what you are doing in the for loop. Get them in separate steps, so to fetch the ‘name’ elements:

        NodeList listOfTerms = doc.getElementsByTagName("name");
        int totalTerms = listOfTerms.getLength();
        System.out.println("Total no of terms : " + totalTerms + "\n");
        for(int s= 0; s<listOfTerms.getLength() ; s++){
            Node firstTermNode = listOfTerms.item(s);
            if(firstTermNode.getNodeType() == Node.ELEMENT_NODE){
                Element firstTermElement = (Element)firstTermNode;
                System.out.println(firstTermElement.getTextContent());
            }//end of if clause
        }//end of for loop with s var
    

    and then to fetch the surname, just vary the tagname

    listOfTerms = doc.getElementsByTagName("surname");
    totalTerms = listOfTerms.getLength();
    System.out.println("Total no of terms : " + totalTerms + "\n");
    for(int s= 0; s<listOfTerms.getLength() ; s++){
        Node firstTermNode = listOfTerms.item(s);
        if(firstTermNode.getNodeType() == Node.ELEMENT_NODE){
            Element firstTermElement = (Element)firstTermNode;
            System.out.println(firstTermElement.getTextContent());
        }//end of if clause
    }//end of for loop with s var
    

    Hope that helps.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

No related questions found

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.