标签:win cto col saxreader 配置文件 遍历 one 生成 handler
SAXReader 解析器
1 import java.util.Iterator; 2 3 import org.dom4j.Document; 4 import org.dom4j.Element; 5 import org.dom4j.io.SAXReader; 6 7 public class Dom4jTest { 8 9 /** 10 * @param args 11 */ 12 public static void main(String[] args) { 13 try { 14 //创建解析器 15 SAXReader reader = new SAXReader(); 16 //通过解析器的read方法将配置文件读取到内存中,生成一个Document[org.dom4j]对象树 17 Document document = reader.read("conf/students.xml"); 18 //获取根节点 19 Element root = document.getRootElement(); 20 //开始遍历根节点 21 for(Iterator<Element> rootIter = root.elementIterator();rootIter.hasNext();){ 22 Element studentElt = rootIter.next(); 23 for(Iterator<Element> innerIter = studentElt.elementIterator();innerIter.hasNext();){ 24 Element innerElt = innerIter.next(); 25 String innerValue = innerElt.getStringValue(); 26 System.out.println(innerValue); 27 } 28 System.out.println("-------------------------------"); 29 } 30 } catch (Exception e) { 31 e.printStackTrace(); 32 } 33 } 34 35 }
//sax解析
1 import javax.xml.parsers.ParserConfigurationException; 2 import javax.xml.parsers.SAXParser; 3 import javax.xml.parsers.SAXParserFactory; 4 5 import org.xml.sax.Attributes; 6 import org.xml.sax.SAXException; 7 import org.xml.sax.helpers.DefaultHandler; 8 9 public class MySAXParser { 10 11 /** 12 * @param args 13 */ 14 public static void main(String[] args) { 15 try { 16 //创建解析器工厂 17 SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); 18 //创建解析器 19 SAXParser saxParser = saxParserFactory.newSAXParser(); 20 //通过解析器的parser方法 21 saxParser.parse("conf/persons.xml", new MyDefaultHandler()); 22 } catch (Exception e) { 23 // TODO Auto-generated catch block 24 e.printStackTrace(); 25 } 26 } 27 28 } 29 30 class MyDefaultHandler extends DefaultHandler{ 31 32 @Override 33 public void startElement(String uri, String localName, String qName, 34 Attributes attributes) throws SAXException { 35 System.out.print("<" + qName + ">"); 36 } 37 @Override 38 public void characters(char[] ch, int start, int length) 39 throws SAXException { 40 System.out.print(new String(ch,start,length)); 41 } 42 43 @Override 44 public void endElement(String uri, String localName, String qName) 45 throws SAXException { 46 System.out.print("</" + qName + ">"); 47 } 48 49 50 51 }
标签:win cto col saxreader 配置文件 遍历 one 生成 handler
原文地址:https://www.cnblogs.com/wings-ff/p/9250484.html