1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| public class XmlParserUtils { public static <T> List<T> parse(String file, Class<T> targetClass) { ArrayList<T> list = new ArrayList<>();
try{ SAXReader saxReader = new SAXReader(); Document document = saxReader.read(new File(file)); Element rootElement = document.getRootElement(); List<Element> elements = rootElement.elements("emp");
for(Element element : elements) { String name = element.element("name").getText(); String age = element.element("age").getText(); String image = element.element("image").getText(); String gender = element.element("gender").getText(); String job = element.element("job").getText();
Constructor<T> constructor = targetClass.getDeclaredConstructor(String.class, Integer.class, String.class, String.class, String.class); constructor.setAccessible(true); T object = constructor.newInstance(name, Integer.parseInt(age), image, gender, job);
list.add(object); } } catch (DocumentException e) {
e.printStackTrace(); }
return list; } }
|