标签:
Dom4j and Sax difference。
有以下几点:
1 SAXReader reader = new SAXReader(); 2 InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("data.xml"); 3 // InputStream is = new FileInputStream(new File("C:/test/data.xml")); 4 Document doc = reader.read(is); 5 Element ele = doc.getRootElement(); 6 @SuppressWarnings("unchecked") 7 List<Element> list = ele.elements(); 8 for(Element elelist : list){ 9 if("driver".equals(elelist.getName())){ 10 driver = elelist.getTextTrim(); 11 } 12 if("url".equals(elelist.getName())){ 13 url = elelist.getTextTrim(); 14 } 15 if("password".equals(elelist.getName())){ 16 password = elelist.getTextTrim(); 17 } 18 if("username".equals(elelist.getName())){ 19 username = elelist.getTextTrim(); 20 } 21 22 }
有以下几点:
1 package com.devil.util; 2 3 import java.io.IOException; 4 5 import javax.xml.parsers.ParserConfigurationException; 6 import javax.xml.parsers.SAXParser; 7 import javax.xml.parsers.SAXParserFactory; 8 9 import org.xml.sax.Attributes; 10 import org.xml.sax.SAXException; 11 import org.xml.sax.helpers.DefaultHandler; 12 13 public class SAXParse extends DefaultHandler { 14 private static String driver = null; 15 private static String url = null; 16 private static String username = null; 17 private static String password = null; 18 private String elementValue = null; 19 20 static { 21 SAXParserFactory factory = SAXParserFactory.newInstance(); 22 try { 23 SAXParser parse = factory.newSAXParser(); 24 parse.parse(Thread.currentThread().getContextClassLoader().getResourceAsStream("data.xml"), new SAXParse()); 25 } catch (ParserConfigurationException e) { 26 e.printStackTrace(); 27 } catch (SAXException e) { 28 e.printStackTrace(); 29 } catch (IOException e) { 30 e.printStackTrace(); 31 } 32 33 } 34 @Override 35 public void startElement(String paramString1, String localName, 36 String qname, Attributes pattr) throws SAXException { 37 } 38 39 @Override 40 public void characters(char[] ch, int start, int end) throws SAXException { 41 elementValue = new String(ch, start, end); 42 43 } 44 45 @Override 46 public void endElement(String NamespaceUrl, String localName, String qname) 47 throws SAXException { 48 49 if (qname.equals("driver")) { 50 driver = elementValue.trim(); 51 } 52 if ("url".equals(qname)) { 53 url = elementValue.trim(); 54 } 55 if ("password".equals(qname)) { 56 password = elementValue.trim(); 57 } 58 if ("username".equals(qname)) { 59 username = elementValue.trim(); 60 } 61 62 } 63 64 public static String getDriver() { 65 return driver; 66 } 67 68 public static String getUrl() { 69 return url; 70 } 71 72 public static String getUsername() { 73 return username; 74 } 75 76 public static String getPassword() { 77 return password; 78 } 79 80 81 public static void main(String[] args) { 82 83 System.out.println(SAXParse.getDriver()); 84 } 85 }
XML的两种解析方式,Dom4j and SAX parse
标签:
原文地址:http://www.cnblogs.com/Devilwx/p/4632199.html