首页 > 学院 > 开发设计 > 正文

SAX解析XML

2019-11-10 20:26:34
字体:
来源:转载
供稿:网友

介绍

java解析xml有两种基本的方式,DOMSAX。今天先简单记录下SAX解析XML。

SAX(Simple API for XML),既是一种接口,也是一种软件包。它是一种XML解析的替代方法。SAX不同于DOM解析,它逐行扫描文档,一边扫描一边解析。

示例

book.xml

<?xml version="1.0" encoding="UTF-8"?> <books> <book id="1"> <name>平凡的世界</name> <author>路遥</author> </book> <book id="2"> <name>活着</name> <author>余华</author> </book> </books>

Book.java

public class Book{ PRivate int id; private String name; private String author; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; }}

SaxParseXmlHandler.java

public class SaxParseXmlHandler extends DefaultHandler{ private List<Book> books; private Book book; private String nodeName; //开始解析文档 @Override public void startDocument() throws SAXException { books = new ArrayList<>(); } //解析开始节点 @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if("book".equals(qName)){ book=new Book(); //获取book节点的id属性 book.setId(Integer.parseInt(attributes.getValue(0))); } nodeName=qName; } //获取节点内容 @Override public void characters(char[] ch, int start, int length) throws SAXException { if(null!=nodeName){ String content=new String(ch,start,length); switch(nodeName){ case "name": book.setName(content); break; case "author": book.setAuthor(content); break; } } } //解析结束节点 @Override public void endElement(String uri, String localName, String qName) throws SAXException { if("book".equals(qName)){ books.add(book); book=null; } nodeName=null; } //结束解析文档 @Override public void endDocument() throws SAXException { super.endDocument(); } //返回解析结果 public List<Book> getBooks(){ return boooks; }}

Test.java

public class Test{ public static void main(String[] args) { try { //创建SAX解析器工厂 SAXParserFactory factory = SAXParserFactory.newInstance(); //创建SAX解析器 SAXParser saxParser = factory.newSAXParser(); //获取XML读取器 XMLReader reader = saxParser.getXMLReader(); //实例化SaxParseXmlHandler SaxParseXmlHandler handler = new SaxParseXmlHandler(); //设置内容处理器 reader.setContentHandler(handler); //读取XML reader.parse("book.xml"); List<Book> books = handler.getBooks(); for (Book book : books) { System.out.println("id:" + book.getId() + ",name:" + book.getName() + ",author:" + book.getAuthor()); } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }}

打印结果

这里写图片描述

注意事项

读取XML文件时,如果XML文件和当前类不在同一个路径,可采用写完整路径的方式读取。如:

InputStream is = Test.class.getClassLoader().getResourceAsStream("com/ywb/context/config/book.xml");reader.parse(new InputSource(is));
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表