public static void createXml(String fileName) throws IOException { Document document = DocumentHelper.createDocument(); Element list = document.addElement("UserList"); for (int i = 0; i <3; i++) { Element user = list.addElement("user"); user.addAttribute("ID", i+1+""); Element name = user.addElement("name"); name.setText("WeiJun Hu"); Element sex = user.addElement("sex"); sex.setText("M"); Element age = user.addElement("age"); age.setText("21"); Element email = user.addElement("email"); email.setText("962884205@qq.com"); } Writer fileWriter = new FileWriter(fileName); XMLWriter xmlWriter = new XMLWriter(fileWriter); xmlWriter.write(document); xmlWriter.close(); }
public static void parserXml(String fileName) throws MalformedURLException { File inputXml = new File(fileName); SAXReader saxReader = new SAXReader(); try { Document document = saxReader.read(inputXml); Element list = document.getRootElement(); for (Iterator i = list.elementIterator(); i.hasNext();) { Element user = (Element) i.next(); Attribute attribute = user.attribute("ID"); Integer id = Integer.parseInt(attribute.getValue()); System.out.println("ID:"+id); for (Iterator j = user.elementIterator(); j.hasNext();) { Element node = (Element) j.next(); System.out.println(node.getName() + ":" + node.getText()); }