2

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!

4
  • 1
    You set k=0 in the beginning, and then increment it after adding a new element, and then try to address this element by k, which is equal to 1 at this point. But arrays are indexed from 0, so you should get IndexOutOfBoundsException. Try to set k=-1 initially. Commented Apr 28, 2019 at 13:24
  • It doesn’t work Commented Apr 28, 2019 at 13:30
  • 1
    right, you need to use xmlr.getElementText() vs getText() Commented Apr 28, 2019 at 13:41
  • @Egor it was soo simple. Thanks! That worked perfectly! Commented Apr 28, 2019 at 14:09

1 Answer 1

1

You can use JAXB library for this purpose. For example:

Create root class with list of contacts:

@XmlRootElement(name = "elements")
@XmlAccessorType(XmlAccessType.FIELD)
public class ContactsList {
    @XmlElement(name = "contact")
    private List<Contact> list;
}

and class which represents Contact data:

@XmlRootElement(name = "contact")
public class Contact {
    private String name;
    private String surname;   
    private String code;   
    private String city;
}

and then using Unmarshaller read your .xml file e.g.:

public static void main(String[] args) throws JAXBException {
        File file = new File("your-file.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(ContactsList.class);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        ContactsList contacts = (ContactsList) unmarshaller.unmarshal(file);
        for (Contact c: contacts.getList()) {
            System.out.println(c.toString());
        }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Isn’t there a way without external libraries, but the one I already included?

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.