I have an xml file, with the following structure:
<elements number="3">
<contact>
<name>PAUL</name>
<surname>ONE</surname>
<code>A1</code>
<city>NEWYORK</city>
</contact>
<contact>
<name>LAURA</name>
<surname>TWO</surname>
<code>A2</code>
<city>WASHINGTON</city>
</contact>
<contact>
<name>JOHN</name>
<surname>THREE</surname>
<code>A3</code>
<city>BOSTON</city>
</contact>
I also have a class Contact, with the attributes name, surname, code and city. I am trying to create an arrayList of objects Contact from the .xml file.
My solution would be so:
private String inputContacts ="inputContacts.xml";
public ArrayList<Contact> readContacts() {
ArrayList<Contact> contacts = new ArrayList<Contact>();
int k = 0;
try {
xmlif = XMLInputFactory.newInstance();
xmlr = xmlif.createXMLStreamReader(inputContacts, new FileInputStream(inputContacts));
while (xmlr.hasNext()) {
switch (xmlr.getEventType()) {
case XMLStreamConstants.START_DOCUMENT:
System.out.println("Start Read Doc " + inputContacts);
break;
case XMLStreamConstants.START_ELEMENT:
switch (xmlr.getLocalName()) {
case "contact":
System.out.println("Tag " + xmlr.getLocalName());
Contact p = new Contact();
contacts.add(p);
k++;
break;
case "name":
contacts.get(k).setName(xmlr.getText());
break;
case "surname":
contacts.get(k).setSurname(xmlr.getText());
break;
case "code":
contacts.get(k).setCode(xmlr.getText());
break;
case "city":
contacts.get(k).setCity(xmlr.getText());
break;
default:
break;
}
break;
case XMLStreamConstants.END_ELEMENT:
System.out.println("END-Tag " + xmlr.getLocalName());
break;
case XMLStreamConstants.COMMENT:
System.out.println("// comment " + xmlr.getText());
break;
case XMLStreamConstants.CHARACTERS:
break;
}
xmlr.next();
}
}
catch (Exception e) {
System.out.println("Reader initialization error:");
System.out.println(e.getMessage());
}
return contacts;
}
The problem is that is starts reading the file, but immediately after having entered in the document, it return everything equals to null.
Thanks in advance to everybody!