更多: zhilu jiaocheng
通过扩展 DefaultParser 来构建处理程序
package com.onitroad.xml.sax; import java.util.ArrayList; import java.util.Stack; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class UserParserHandler extends DefaultHandler { //This is the list which shall be populated while parsing the XML. private ArrayList userList = new ArrayList(); //As we read any XML element we will push that in this stack private Stack elementStack = new Stack(); //As we complete one user block in XML, we will push the User instance in userList private Stack objectStack = new Stack(); public void startDocument() throws SAXException { //System.out.println("start of the document : "); } public void endDocument() throws SAXException { //System.out.println("end of the document document : "); } public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { //Push it in element stack this.elementStack.push(qName); //If this is start of 'user' element then prepare a new User instance and push it in object stack if ("user".equals(qName)) { //New User instance User user = new User(); //Set all required attributes in any XML element here itself if(attributes != null && attributes.getLength() == 1) { user.setId(Integer.parseInt(attributes.getValue(0))); } this.objectStack.push(user); } } public void endElement(String uri, String localName, String qName) throws SAXException { //Remove last added element this.elementStack.pop(); //User instance has been constructed so pop it from object stack and push in userList if ("user".equals(qName)) { User object = this.objectStack.pop(); this.userList.add(object); } } /** * This will be called everytime parser encounter a value node * */ public void characters(char[] ch, int start, int length) throws SAXException { String value = new String(ch, start, length).trim(); if (value.length() == 0) { return; // ignore white space } //handle the value based on to which element it belongs if ("firstName".equals(currentElement())) { User user = (User) this.objectStack.peek(); user.setFirstName(value); } else if ("lastName".equals(currentElement())) { User user = (User) this.objectStack.peek(); user.setLastName(value); } } /** * Utility method for getting the current element in processing * */ private String currentElement() { return this.elementStack.peek(); } //Accessor for userList object public ArrayList getUsers() { return userList; } }
SAX是一个XML流接口,这意味着使用SAX的应用程序可以接收有关正在处理的XML文档的事件通知—元素和属性,时间顺序从文档顶部开始,到根元素关闭为止。
这意味着它在线性时间内处理 XML 非常有效,而不会对系统内存提出太多要求。
SAX 解析器读取 XML 文件
package com.onitroad.xml.sax; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; public class UsersXmlParser { public ArrayList parseXml(InputStream in) { //Create a empty link of users initially ArrayList<user> users = new ArrayList</user><user>(); try { //Create default handler instance UserParserHandler handler = new UserParserHandler(); //Create parser from factory XMLReader parser = XMLReaderFactory.createXMLReader(); //Register handler with parser parser.setContentHandler(handler); //Create an input source from the XML input stream InputSource source = new InputSource(in); //parse the document parser.parse(source); //populate the parsed users list in above created empty list; You can return from here also. users = handler.getUsers(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { } return users; } }
创建模型类
package com.onitroad.xml.sax; /** * Model class. Its instances will be populated using SAX parser. * */ public class User { //XML attribute id private int id; //XML element fisrtName private String firstName; //XML element lastName private String lastName; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Override public String toString() { return this.id + ":" + this.firstName + ":" +this.lastName ; } }
测试 SAX 解析器
package com.onitroad.xml.sax; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.ArrayList; public class TestSaxParser { public static void main(String[] args) throws FileNotFoundException { //Locate the file File xmlFile = new File("D:/temp/sample.xml"); //Create the parser instance UsersXmlParser parser = new UsersXmlParser(); //Parse the file ArrayList users = parser.parseXml(new FileInputStream(xmlFile)); //Verify the result System.out.println(users); } }
要解析的xml测试文件
此 xml 文件还包含 xml 属性以及 xml 元素。
<users> <user id="100"> <firstname>Tom</firstname> <lastname>Hanks</lastname> </user> <user id="101"> <firstname>JackLi</firstname> <lastname>Gupta</lastname> </user> <user id="102"> <firstname>HowToDo</firstname> <lastname>InJava</lastname> </user> </users>
日期:2020-09-17 00:10:14 来源:oir作者:oir