Reading through list of objects

Rakshan

Mitglied
Hi, I have a list which contains student objects as shown below:

Java:
Registry(Student=[Student(Gender=M, School=Hamburg, FirstName=RP, Value=null), Student(Gender=F, School=Berlin, FirstName=SK, Value=null), Student(Gender=M, School=Frankfurt, FirstName=TK, Value=null)])

It symbolises a XML heirarchy.
XML:
<Registry
   <Student Gender="M" School="Hamburg">
        <FirstName>RP</FirstName>
    </Student>
    <Student Gender="F" School="Berlin">
        <FirstName>SK</FirstName>
    </Student>
    <Student Gender="M" School="Frankfurt">
        <FirstName>TK</FirstName>
    </Student>
</Registry>

Now I plan to add another entry into the list/xml based on the school of individual student.
For eg: I want to search through the list mentioned above, for school = "Berlin" and then add another new student if there is a match.

For eg:

Java:
Registry(Student=[Student(Gender=M, School=Hamburg, FirstName=RP, Value=null), Student(Gender=F, School=Berlin, FirstName=SK, Value=null),Student(Gender=M, School=Berlin, FirstName=KK, Value=null), Student(Gender=M, School=Frankfurt, FirstName=TK, Value=null)])

Ofcourse, I change he FirstName and Gender .. Please suggest me how to scan through the object properties inside list of objects?
 
K

kneitzel

Gast
Ok, I see two possible ways:

a) Use JSO Serialization / Deserialization - So you have classes for the required objects and you deserialize the JSON to the the Instances required. Then you change the Instances (e.g. add a Student) and afterwards you serialize it back to JSON.

b) You simply read the JSON to the structure and then you modify the JSON instances.

For both you need a library e.g. jackson, gson, ...

If you do not plan to do anything more then a is overkill in my eyes. Just read the JSON to the JSON classes (So you get a Structure of all the JsonElement implementations in gson e.g. JsonObject) You can go through the structure and add new elements. At the end you write it back of course.
 

Rakshan

Mitglied
So to give a complete overview:

I have a list of objects as displayed


Java:
Registry(Student=[Student(Gender=M, School=Hamburg, FirstName=RP, Value=null),
                  Student(Gender=F, School=Berlin, FirstName=SK, Value=null),
                  Student(Gender=M, School=Frankfurt, FirstName=TK, Value=null)])


This represents the XML structure after unmarshalling. The original structure of the XML is shown below


XML:
<?xml version="1.0" encoding="UTF-8"?>
<Registry xmlns="http://www.registar.com"
          xmlns:ms ="http://www.registar.com/ScoreVariant">
    <Student Gender = "M" School = "Hamburg">
        <FirstName>RP</FirstName>
    </Student>
    <Student Gender = "F" School = "Berlin">
        <FirstName>SK</FirstName>
    </Student>
    <Student Gender = "M" School = "Frankfurt">
        <FirstName>TK</FirstName>
    </Student>
</Registry>


There are classes written for Registry, Student and Value with getter and setter methods (used lombok package)

Now, I want to scan through the list of objects, Look for school location, and if the location is "Berlin", I want to add another student.



Java:
  List<Registry> entries = new ArrayList<Registry>();
    
    for (Registry e: entries) {
        for (Student s : e.getStudent()) {
            if (s.getSchool().equals("Berlin")) {
                 Student obj = new Student();
                 obj.setFirstName("MP");
                obj.setGender("F");
                obj.setSchool("Berlin");    // (1)
            }                 
        }             
    }


(1) Here I can create new object, but I am not able to add it to the XML (as the registry class has the ```List<Student> student``` as a property.


Ultimately, I want to have a output like the below


Java:
Registry(Student=[Student(Gender=M, School=Hamburg, FirstName=RP, Value=null),
                  Student(Gender=F, School=Berlin, FirstName=SK, Value=null),
                  Student(Gender=F, School=Berlin, FirstName=MP, Value=null),
                  Student(Gender=M, School=Frankfurt, FirstName=TK, Value=null)])
 
K

kneitzel

Gast
Sorry, I was a little confused and didn't read good enough - I thought that your "Java Objects" was showing some JSON that you have. My fault.

But you are correct: The same is valid with XML.

- You can use Libraries zu serialize / deserialize to/from XML. (Jackson can be used here, too) And if you already have the student java objects, then this might be the best way to go.

- You can modify the XML directly ... You load the XML to a DOM Tree (Using a DOM Parser) and then you can add Xml Elements manualy. At the end you write the DOM Tree back to the file (if it is a file).


============================

You got the classes in java already, so let us concentrate on these.

- Do you have code to serialize them to XML? Using some library? (Which if you are using one already?) Is there help required in this topic?

- Your code is creating a new student. But the new student is never added. So something like e.addStudent(obj) seems to be missing. But this might need more investigation because you might not want to change a collection that you currently iterate over.


============================

And last but not least: please allow me some advice regarding your code:

- Please try to choose more reasonable names. "e" is a registry? "s" student? "obj" a new student? I would recommend to use the longer versions:
e -> registry
s -> student
obj -> newStudent
And getStudent() is giving multiple Students? So it should be getStudents (plural) and not getStudent (singular).
And I am not sure if the Attribute names were given to you. But I would like to even do changes there e.g. School seems to be a schoolLocation

- Something I always try: Keep methods more simple. for each / for each / if -> That is already something where I would think about splitting into multiple methods. You are inside a class that holds registries. And the logic to add a student is something that happens inside a registry. Maybe the code to add another student even belongs more in the registry class? (So 2 points: 1st is the depth of Blocks, 2nd is the question: Whre does some logic belong to?) But feel free to ignore this point! This is just something I got into my mind without knowing anything about the real structure of you project and the responsibilities.
 
M

Mart

Gast
if you parse your xml file

when you dug into the students you need to get their Attribute School and compare it if its Berlin if so
you can continue digging their with your xml parser
 

Rakshan

Mitglied
Ofcourse, I would gladly take your advice. Infact, I would really appreciate because I am just starting and would be guided in the right direction. I will start naming them currently in a manner that is understandable.

First and foremost, yes so there is an input xml file that has been parsed using JAXB standard.

Registry.java
Java:
import lombok.Data;
@XmlRootElement(name="Registry")//,namespace = "http://www.registar.com")
@XmlAccessorType(XmlAccessType.FIELD)
@Data
public class Registry {  
    @XmlElement(name="Student")//,namespace = "http://www.registar.com")
    private List<Student> students;
}

Student.java
Java:
@Data

@XmlAccessorType(XmlAccessType.FIELD)
public class Student {   
    @XmlAttribute(name = "Gender")
    private String Gender;   
    @XmlAttribute(name = "School")
    private String School;   
    @XmlElement(name = "FirstName")//namespace = "http://www.registar.com")
    private String FirstName;   
    @XmlElement(name = "Value")
    private Value Value;
}

So in my main parser now, I search for the student having school at Berlin, and I add one student there( practically it doesnt make sense, but just for me to understand and get familiar)

Java:
public class Mainparser {
    public static void main(String[] args) {
        try {
            File xmlFile = new File("MultipleNS.xml");
            JAXBContext jaxbContext;
            jaxbContext = JAXBContext.newInstance(Registry.class);
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            Registry xmlentries = (Registry) jaxbUnmarshaller.unmarshal(xmlFile);           
            Student newStudent = null;               
            List<Student> students = xmlentries.getStudents();
            for (Student s : students) {
                if (s.getSchool().equals("Berlin")) {
                    newStudent=new Student();
                    newStudent.setFirstName("MP");
                    newStudent.setGender("F");
                    newStudent.setSchool("Berlin");
                    break;
                }
            }
            if(newStudent!=null) {
                students.add(newStudent);
            }       
            Marshaller marshaller = jaxbContext.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.marshal(xmlentries, System.out);
        }catch (JAXBException e) {
            e.printStackTrace();
        } catch (FactoryConfigurationError e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

I could achieve the result as below

XML:
<Registry xmlns:ms="http://www.registar.com/ScoreVariant" xmlns="http://www.registar.com">
    <Student Gender="M" School="Hamburg">
        <FirstName>RP</FirstName>
    </Student>
    <Student Gender="F" School="Berlin">
        <FirstName>SK</FirstName>
    </Student>
    <Student Gender="M" School="Frankfurt">
        <FirstName>TK</FirstName>
    </Student>
    <Student Gender="F" School="Berlin">
        <FirstName>MP</FirstName>
    </Student>
</Registry>
 
K

kneitzel

Gast
So if I understood you correctly, then you have all major parts already. The only problem is, that the order is not as wanted?

So you want to insert an item at a specific position. List<T> has a method add(int index, E element) which you could use. But you need to get the index where you want to insert the student.

One possible way could be to not use a for each loop. Instead you use a normal loop:
for (Student s : students) {
is replaced with:
Java:
for (int index=0; index < students.length(); index++) {
    Student s = students.get(index);
    // ...
}

That way you have the index when you found a matching element. You can store that inside a variable outside of the loop and then you can use something like
Java:
if(newStudent!=null) {
    students.add(storedIndex+1, newStudent); // +1 to add behind the found element.
}
 
M

Mart

Gast
Java:
            List<Student> students = xmlentries.getStudents();
            for (Student s : students) {
                if (s.getSchool().equals("Berlin")) {
                }
this is basically what i meant ...

you dug until you reached all Students and you dug through them

my digging was always getElementsByTagName but ive used another xml parser where you have to dig from the top level down to the bottom
 
Ähnliche Java Themen
  Titel Forum Antworten Datum
Rakshan Generic reading of XML document from the root tag into an Collection Allgemeine Java-Themen 0
B java.io.IOException: Problem reading font data. Allgemeine Java-Themen 9
N IOException: "Reading from an output buffer" ? Allgemeine Java-Themen 2
8u3631984 Frage Performance bei Linked List und Array List Allgemeine Java-Themen 5
L Unterschied zwischen List und LinkedList implementierung? Allgemeine Java-Themen 15
Monokuma String List nach Zahlen und Worten sortieren Allgemeine Java-Themen 9
W Enumeration ein Array/List als Eigenschaft mitgeben - warum geht das nicht? Allgemeine Java-Themen 0
X Collections Gibt es eine Klasse welche die Vorteile von List und HashMap vereint, aber konstante Laufzeit (O(1)) hat in Java? Allgemeine Java-Themen 4
W Collections Suche etwas Sorted-List-Artiges...hat jemand eine Idee? Allgemeine Java-Themen 13
M List -Tableview-Javafx-Vererbung Allgemeine Java-Themen 35
R convert 2d array list to 2d array Allgemeine Java-Themen 1
B List<Integer> ist List<Double> ? Allgemeine Java-Themen 6
L Applet Problem "security: Trusted libraries list file not found" ? Allgemeine Java-Themen 7
G Neues Objekt aus List<JsonObject> mit Stream Allgemeine Java-Themen 4
J Array-List Bubble-Sort Allgemeine Java-Themen 12
U javax.mail.Folder.list() zeigt nicht alle Ordner Allgemeine Java-Themen 5
Hacer List<? super E> Allgemeine Java-Themen 10
C Objekte in Array List speichern? Allgemeine Java-Themen 1
P List<Type> Konvertieren in List<List<Type>> Allgemeine Java-Themen 3
P Sorted List o.ä. Allgemeine Java-Themen 2
M Erste Schritte List<> unbekannt?? Allgemeine Java-Themen 8
M List casting error Allgemeine Java-Themen 3
Messoras List zeigt nur das letzte Element an Allgemeine Java-Themen 14
K Collections Collection<> mit List<String> abgleichen? Allgemeine Java-Themen 10
A List<String> auf doppelte Einträge überprüfen Allgemeine Java-Themen 4
U EJB Entity mit List Problem Allgemeine Java-Themen 2
? Objects aus List aussortieren Allgemeine Java-Themen 9
B List Pointer zurücksetzen Allgemeine Java-Themen 10
J Elemente zu einer List hinzufügen? Allgemeine Java-Themen 9
T Liste mit GregorianCalendar-Objekten in List einlesen, mit Collection sortieren und ausgeben Allgemeine Java-Themen 3
N List auf null prüfen Allgemeine Java-Themen 2
G List<Person> sortieren Allgemeine Java-Themen 6
A Probleme mit ConcurrentHashMap und List Allgemeine Java-Themen 3
C Komisches Verhalten zwischen Set und List bei contains Allgemeine Java-Themen 6
N Inverted index / inverted list Allgemeine Java-Themen 2
X Eine Map mit X -> List<Y>? Allgemeine Java-Themen 8
Shoox HashMaps in List? Allgemeine Java-Themen 3
B Frage zu Interface und List Allgemeine Java-Themen 4
H List wird nicht richtig gefüllt Allgemeine Java-Themen 6
Z aus private List<???> list eintrag löschen Allgemeine Java-Themen 4
L List <Hauser> in Combobox einfügen Allgemeine Java-Themen 5
isowiz java.util.List: Sortierung nicht nach bestimmten Attribut? Allgemeine Java-Themen 4
K von List getSelected auf ResultSet Datenbank löschen Allgemeine Java-Themen 2
E Speicher frei machen (List) Allgemeine Java-Themen 9
K List in Teillisten zerlegen Allgemeine Java-Themen 2
B Probleme mit awt.List in Chatprogramm Allgemeine Java-Themen 14
MQue List<String> aus List<Object> generieren Allgemeine Java-Themen 2
B List = ArrayList ? Allgemeine Java-Themen 12
N List<? implements "Interface"> geht nicht Allgemeine Java-Themen 13
G Byte- List mit einem Iterator durchlaufen Allgemeine Java-Themen 5
G Linked List zwischen zwei Threds übergeben Allgemeine Java-Themen 11
S List<Double> oder Double[] in double[] zu konvertieren Allgemeine Java-Themen 6
G Methode akzeptiert List<ParentClass> aber nicht List&l Allgemeine Java-Themen 2
G List- Einträge löschen Allgemeine Java-Themen 3
G java.util.List klonen Allgemeine Java-Themen 17
S Collections.binarySearch(list,"a") Allgemeine Java-Themen 7
K Bound mismatch: The generic method sort(List<T>) of ty Allgemeine Java-Themen 4
K "Too many open files" bei Property List Allgemeine Java-Themen 5
P List in Hashmap schreiben Allgemeine Java-Themen 5
J linked list per reverse() "umdrehen" Allgemeine Java-Themen 11
P java.util.List - Typ überschreiben Allgemeine Java-Themen 9
G Arraylist statt List - Sehr schlimm? Allgemeine Java-Themen 8
G List mit selbstdefinierten Objekten sortieren Allgemeine Java-Themen 2
M Datenstrukrue, List<Map<Integer, Map<String, . Allgemeine Java-Themen 2
F List<String> zu byte[] Allgemeine Java-Themen 7
G Map oder List mit festgelegter Reihenfolge Allgemeine Java-Themen 4
M Pendant zu list() und array() aus PHP in Java gegeben? Allgemeine Java-Themen 5
J Problem mit List Allgemeine Java-Themen 2
byte Generic Type einer List zur Laufzeit rausfinden? Allgemeine Java-Themen 4
S Generics List Allgemeine Java-Themen 3
G Inhalt einer Textdatei in eine AWT List schreiben Allgemeine Java-Themen 3
C access control list in java Allgemeine Java-Themen 7
T List.isEmpty() klappt nicht?!?!? Allgemeine Java-Themen 5

Ähnliche Java Themen

Neue Themen


Oben