一、DOM方式解析XMLhtml
給予DOM的解析方式,是把整個XML文檔加載到內存,轉化成DOM樹,能夠隨機的訪問DOM樹的任何數據,速度快、比較靈活,可是消耗資源比較多,不適用大的xml文檔解析,測試超過10M內存溢出。java
public class DOM01 { public static void printAttr(Node node){ NamedNodeMap map = node.getAttributes(); for(int i=0;i<map.getLength();i++){ Node attrNode = map.item(0); System.out.println(attrNode.getNodeName()+":"+attrNode.getFirstChild().getNodeValue()); } } public static void main(String[] args) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse("src/student.xml"); NodeList nodeLlist = doc.getElementsByTagName("students"); Element element = (Element)nodeLlist.item(0); NodeList studentNodeList = element.getElementsByTagName("student"); for(int i=0;i<studentNodeList.getLength();i++){ Element e = (Element)studentNodeList.item(i); //e.getElementsByTagName("name").item(0).getFirstChild().setNodeValue("haha"); System.out.println(e.getElementsByTagName("name").item(0).getFirstChild().getNodeValue()); printAttr(e.getElementsByTagName("name").item(0)); } // System.out.println("姓名:"+element.getElementsByTagName("name").item(0).getFirstChild().getNodeValue()); } catch (Exception e) { e.printStackTrace(); } } }
二、SAX方式解析xmlnode
SAX工做原理是對文檔順序掃描,當掃描到文檔開始與結束、元素開始結束等地方時通知回調函數作出相應的動做,而後繼續掃描,直至文檔結束。消耗資源比較少,適合大文檔解析,可是隻能讀取不能修改,開發也較複雜。框架
public class SAX extends DefaultHandler{ private List<Student> students = null; private Student student = null; private String preTag = null;//記錄上一個節點名稱 @Override public void startDocument() throws SAXException { System.out.println("開始讀取學生信息"); students = new ArrayList<Student>(); } @Override public void endDocument() throws SAXException { System.out.println("\n 信息讀取完畢"); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if("student".equals(qName)){ student = new Student(); student.setId(attributes.getValue(0)); }preTag = qName; } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if("student".equals(qName)){ students.add(student); student = null; }preTag = null; } @Override public void characters(char[] ch, int start, int length) throws SAXException { if(preTag != null){ String content = new String(ch, start, length); if("name".equals(preTag)){ student.setName(content); }else if("sex".equals(preTag)){ student.setSex(content); }else if("age".equals(preTag)){ student.setAge(content); } } } public static void main(String[] args) throws Exception{ SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); SAX sax = new SAX(); parser.parse("src/student.xml", sax); for(Student student : sax.students){ System.out.println(student); } } }
JDOM和DOM4j解析xml:ide
兩個都是解析XML優秀的框架,可是二者也有區別,具體能夠參考http://www.cnblogs.com/zhi-hao/p/4016363.html函數
JDOM封裝xml實例:測試
public class JDOM01 { public static void main(String[] args) throws Exception{ Element student = new Element("student"); Attribute id = new Attribute("id", "001"); Attribute aa = new Attribute("aa", "xx"); student.setAttribute(id); student.setAttribute(aa); Element name = new Element("name"); Element age = new Element("age"); Element sex = new Element("sex"); name.setText("張三"); student.addContent(name); sex.setText("男"); student.addContent(sex); age.setText("18"); student.addContent(age); Document document = new Document(student); XMLOutputter outputter = new XMLOutputter(); outputter.setFormat(outputter.getFormat().setEncoding("UTF-8")); outputter.output(document, new FileOutputStream("src/student2.xml")); } }
JDOM解析xml實例:ui
public class JDOM02 { public static void main(String[] args) throws Exception{ SAXBuilder builder = new SAXBuilder(); Document document = builder.build("src/student.xml"); Element students = document.getRootElement(); List studentList = students.getChildren("student"); for(int i=0;i<studentList.size();i++){ Element student = (Element)studentList.get(i); String id = student.getAttributeValue("id"); String name = student.getChildText("name"); String sex = student.getChildText("sex"); String age = student.getChildText("age"); System.out.println("學號:"+id+",姓名:"+name+",性別:"+sex+",年齡:"+age); } } }
DOM4j封裝xml實例:spa
public class DOM4j01 { public static void main(String[] args) throws Exception{ Document document = DocumentHelper.createDocument(); Element studentElement = document.addElement("student"); studentElement.addAttribute("id", "001"); studentElement.addAttribute("aa", "xx"); Element name = studentElement.addElement("name"); name.setText("張三"); Element sex = studentElement.addElement("sex"); sex.setText("男"); Element age = studentElement.addElement("age"); age.setText("20"); OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("UTF-8"); XMLWriter writer = new XMLWriter(new FileOutputStream("src/student3.xml"),format); writer.write(document); writer.close(); } }
DOM4j解析xml實例:code
public class DOM4j02 { public static void main(String[] args) throws Exception{ SAXReader saxReader = new SAXReader(); Document doc = saxReader.read("src/student.xml"); Element rootElement = doc.getRootElement(); @SuppressWarnings("rawtypes") Iterator iter = rootElement.elementIterator(); while(iter.hasNext()){ Element studentElement = (Element)iter.next(); System.out.println("學號:"+studentElement.attributeValue("id")); System.out.println("姓名:"+studentElement.elementText("name")); System.out.println("========================================="); } } }
總的來講DOM4J是最好的,目前許多開源項目中也大量採用 DOM4J,例如大名鼎鼎的 Hibernate 也用 DOM4J 來讀取 XML 配置文件。若是不考慮可移植性,那就採用DOM4J吧