如何从xml创建对象的arrayList?

时间:2019-04-28 12:54:16

标签: java xml object arraylist

我有一个具有以下结构的xml文件:

$("[name='geo.region']").remove()

我还有一个类 <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> ,具有属性Contactnamesurnamecode。我正在尝试从.xml文件创建对象city的arrayList。 我的解决方案是这样的:

Contact

问题是开始读取文件,但是在输入文档后,它立即返回等于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; } 的所有内容。

在此先感谢大家!

1 个答案:

答案 0 :(得分:1)

您可以为此目的使用JAXB库。例如:

使用联系人列表创建根类:

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

代表联系人数据的类:

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

,然后使用Unmarshaller读取您的.xml文件,例如:

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());
        }
}