0

I have this xml file that contains 3 categories:employee_list, position_details and employee_info.

<?xml version="1.0" encoding="UTF-8"?>
<employee>
    <employee_list>
        <employee ID="1">
            <firstname>Andrei</firstname>
            <lastname>Rus</lastname>
            <age>23</age>
            <position-skill ref="Java"/>
            <detail-ref ref="AndreiR"/>
        </employee>

        <employee ID="2">
            <firstname>Ion</firstname>
            <lastname>Popescu</lastname>
            <age>25</age>
            <position-skill ref="Python"/>
            <detail-ref ref="IonP"/>
        </employee>

        <employee ID="3">
            <firstname>Georgiana</firstname>
            <lastname>Domide</lastname>
            <age>33</age>
            <position-skill ref="C"/>
            <detail-ref ref="GeorgianaD"/>
        </employee>

    </employee_list>

    <position_details>
        <position ID="Java">
            <role>Junior Developer</role>
            <skill_name>Java</skill_name>
            <experience>1</experience><!-- years of experience -->
        </position>

        <position ID="Python">
            <role>Developer</role>
            <skill_name>Python</skill_name>
            <experience>3</experience> 
        </position>

        <position ID="C">
            <role>Senior Developer</role>
            <skill_name>C</skill_name>
            <experience>5</experience>
        </position>
    </position_details>

    <employee_info>
        <detail ID="AndreiR">
            <username>AndreiR</username>
            <residence>Timisoara</residence>
            <yearOfBirth>1999</yearOfBirth>
            <phone>0</phone>
        </detail>

        <detail ID="IonP">
            <username>IonP</username>
            <residence>Timisoara</residence>
            <yearOfBirth>1997</yearOfBirth>
            <phone>0</phone>
        </detail>

        <detail ID="GeorgianaD">
            <username>GeorgianaD</username>
            <residence>Arad</residence>
            <yearOfBirth>1989</yearOfBirth>
            <phone>0</phone>
        </detail>
    </employee_info>
</employee>

I would like to write java code for all 3 categories, but so far I have only managed to get past the first category (employee_list). When I try to retrieve information from the position_list or employee_info category, the program fails to find information according to each category.

I wrote the Java code for the 3 categories and the result looks like this:

package Dom;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

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

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

public class main {

    public static void main(String[] args) {
        try {
            File xmlDoc = new File("employees.xml");
            DocumentBuilderFactory dbFact = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuild = dbFact.newDocumentBuilder(); 
            Document doc = dBuild.parse(xmlDoc);
            
            //Citim radacina
            //                                    doc localizeaza radacina   da numele ei
            System.out.println("Root element: " + doc.getDocumentElement().getNodeName());
            System.out.println("-----------------------------------------------------------------------------");
            
            //citim un array de studenti pe care il denumim NodeList
            NodeList nList = doc.getElementsByTagName("employee");
            System.out.println("Total Category inside = " + nList.getLength());
            System.out.println("-----------------------------------------------------");
            
            
            for(int i = 0 ; i<nList.getLength();i++) {
                Node nNode = nList.item(i);
                //System.out.println("Node name: " + nNode.getNodeName()+" " + (i+1));
                if(nNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement = (Element) nNode;
                    System.out.println("Person id#: " + eElement.getAttribute("id"));
                    System.out.println("Person Last Name: " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
                    System.out.println("Person First name: " + eElement.getElementsByTagName("firstname").item(0).getTextContent());
                    System.out.println("Person Age: " + eElement.getElementsByTagName("age").item(0).getTextContent());
                    System.out.println("--------------------------------------------------------------------------");
                }
            }
            
            System.out.println("=============================================================================================");
            
            nList = doc.getElementsByTagName("position");
            System.out.println("Total Category inside = " + nList.getLength());
            System.out.println("-----------------------------------------------------");
            for(int i = 0 ; i<nList.getLength();i++) {
                Node nNode = nList.item(i);
                //System.out.println("Node name: " + nNode.getNodeName()+" " + (i+1));
                if(nNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement = (Element) nNode;
                    System.out.println("Role: " + eElement.getElementsByTagName("role").item(0).getTextContent());
                    System.out.println("Skill: "+ eElement.getElementsByTagName("skill_name").item(0).getTextContent());
                    System.out.println("Experience: "+ eElement.getElementsByTagName("experience").item(0).getTextContent());
                    System.out.println("--------------------------------------------------------------------------");
                }
            }
            
            System.out.println("=============================================================================================");
            
            nList = doc.getElementsByTagName("detail");
            System.out.println("Total Category inside = " + nList.getLength());
            System.out.println("-----------------------------------------------------");
            for(int i = 0 ; i<nList.getLength();i++) {
                Node nNode = nList.item(i);
                //System.out.println("Node name: " + nNode.getNodeName()+" " + (i+1));
                if(nNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement = (Element) nNode;
                    System.out.println("Person with username: " +  eElement.getElementsByTagName("username").item(0).getTextContent());
                    System.out.println("Username: " + eElement.getElementsByTagName("username").item(0).getTextContent());
                    System.out.println("Residence: "+ eElement.getElementsByTagName("residence").item(0).getTextContent());
                    System.out.println("Year of birth: "+ eElement.getElementsByTagName("yearOfBirth").item(0).getTextContent());
                    System.out.println("Phone: "+ eElement.getElementsByTagName("phone").item(0).getTextContent());
                    System.out.println("--------------------------------------------------------------------------");
                }
            }
            
            
        }catch(Exception e) {
            
        }
        
    }

}

output:

Root element: employee
-----------------------------------------------------------------------------
Total Category inside = 4
-----------------------------------------------------
Person id#: 
Person Last Name: Rus
Person First name: Andrei
Person Age: 23
--------------------------------------------------------------------------
Person id#: 
Person Last Name: Rus
Person First name: Andrei
Person Age: 23
--------------------------------------------------------------------------
Person id#: 
Person Last Name: Popescu
Person First name: Ion
Person Age: 25
--------------------------------------------------------------------------
Person id#: 
Person Last Name: Domide
Person First name: Georgiana
Person Age: 33
--------------------------------------------------------------------------
=============================================================================================
Total Category inside = 3
-----------------------------------------------------
Role: Junior Developer
Skill: Java
Experience: 1
--------------------------------------------------------------------------
Role: Developer
Skill: Python
Experience: 3
--------------------------------------------------------------------------
Role: Senior Developer
Skill: C
Experience: 5
--------------------------------------------------------------------------
=============================================================================================
Total Category inside = 3
-----------------------------------------------------
Person with username: AndreiR
Username: AndreiR
Residence: Timisoara
Year of birth: 1999
Phone: 0
--------------------------------------------------------------------------
Person with username: IonP
Username: IonP
Residence: Timisoara
Year of birth: 1997
Phone: 0
--------------------------------------------------------------------------
Person with username: GeorgianaD
Username: GeorgianaD
Residence: Arad
Year of birth: 1989
Phone: 0
--------------------------------------------------------------------------

Is there any possibility that the output could be slightly more grouped, in the following form for each person:

PersonId
firstname
lastname
age
role
skill_name
experience
username
residence
yearOfBirth
phone

1 Answer 1

0

But you've basically done it already, you wrote the code for the three categories. "Failing to find information according to each category" might mean that the output is not the desired output. The reason could be that Document.getElementsByTagName() searches globally for all elements that have the name passed as the argument. As your root element too is named employee, it's included as an additional Node in your NodeList on doc.getElementsByTagName("employee"), which btw. doesn't have an ID attribute of it's own (note: these are case-sensitive). Hence a "Total Category inside = 4". If you then do getElementsByTagName("lastname") on this first Node/Element that's the root, sure enough, it has a <lastname/> element below it, just not as a direct child, but two levels down, the element of the first "actual"/desired <employee/>.

So what you probably want to do is to not search for your element names globally, but in the local context of the category, as you already do successfully elsewhere inside the loops. Maybe just change

NodeList nList = doc.getElementsByTagName("employee");

to

NodeList nList = doc.getElementsByTagName("employee_list");
nList = ((Element)nList.item(0)).getElementsByTagName("employee");

for the employee_list category, and likewise for the other categories.

In order to group records more nicely, you don't need to output/print them immediately. You can copy/store the values you get from the DOM in the members of an object of a class you could define, or make a more generic class which stores the field values in a List that contains a Map, or something like that. With such, you can iterate/loop over the objects or list you created, and output/print the field values in your preferred order.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.