原文: https://howtodoinjava.com/xml/sax-parser-read-xml-example/

SAX 解析器XML 的简单 API 已经存在很多年了,最初由 David Megginson 领导开发。 那时,您不得不从 David 的个人网站下载 Java 版本的 SAX。 在最终添加到 Java 标准版 1.4 中之前,它已发展为 SAX 项目

SAX 是 XML 的流接口,这意味着使用 SAX 的应用从文档的顶部开始,以顺序的时间接收到有关 XML 文档正在处理元素和属性的事件通知,并以根元素的关闭而结束。 这意味着它在线性时间内处理 XML 的效率非常高,而不会对系统内存提出过多要求。

让我们创建一个演示程序,以便使用 SAX 解析器读取 xml 文件以全面理解。

1.准备要解析的 xml 文件

该 xml 文件包含 xml 属性以及 xml 元素。

  1. <users>
  2. <user id="100">
  3. <firstname>Tom</firstname>
  4. <lastname>Hanks</lastname>
  5. </user>
  6. <user id="101">
  7. <firstname>Lokesh</firstname>
  8. <lastname>Gupta</lastname>
  9. </user>
  10. <user id="102">
  11. <firstname>HowToDo</firstname>
  12. <lastname>InJava</lastname>
  13. </user>
  14. </users>

2.创建模型类

  1. package com.howtodoinjava.xml.sax;
  2. /**
  3. * Model class. Its instances will be populated using SAX parser.
  4. * */
  5. public class User
  6. {
  7. //XML attribute id
  8. private int id;
  9. //XML element fisrtName
  10. private String firstName;
  11. //XML element lastName
  12. private String lastName;
  13. public int getId() {
  14. return id;
  15. }
  16. public void setId(int id) {
  17. this.id = id;
  18. }
  19. public String getFirstName() {
  20. return firstName;
  21. }
  22. public void setFirstName(String firstName) {
  23. this.firstName = firstName;
  24. }
  25. public String getLastName() {
  26. return lastName;
  27. }
  28. public void setLastName(String lastName) {
  29. this.lastName = lastName;
  30. }
  31. @Override
  32. public String toString() {
  33. return this.id + ":" + this.firstName + ":" +this.lastName ;
  34. }
  35. }

3.通过扩展DefaultParser构建处理器

下面的代码为解析处理器。 我在代码注释中添加了其他信息。 不过,您有任何疑问吗,请给我留言。

  1. package com.howtodoinjava.xml.sax;
  2. import java.util.ArrayList;
  3. import java.util.Stack;
  4. import org.xml.sax.Attributes;
  5. import org.xml.sax.SAXException;
  6. import org.xml.sax.helpers.DefaultHandler;
  7. public class UserParserHandler extends DefaultHandler
  8. {
  9. //This is the list which shall be populated while parsing the XML.
  10. private ArrayList userList = new ArrayList();
  11. //As we read any XML element we will push that in this stack
  12. private Stack elementStack = new Stack();
  13. //As we complete one user block in XML, we will push the User instance in userList
  14. private Stack objectStack = new Stack();
  15. public void startDocument() throws SAXException
  16. {
  17. //System.out.println("start of the document : ");
  18. }
  19. public void endDocument() throws SAXException
  20. {
  21. //System.out.println("end of the document document : ");
  22. }
  23. public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
  24. {
  25. //Push it in element stack
  26. this.elementStack.push(qName);
  27. //If this is start of 'user' element then prepare a new User instance and push it in object stack
  28. if ("user".equals(qName))
  29. {
  30. //New User instance
  31. User user = new User();
  32. //Set all required attributes in any XML element here itself
  33. if(attributes != null &amp;&amp; attributes.getLength() == 1)
  34. {
  35. user.setId(Integer.parseInt(attributes.getValue(0)));
  36. }
  37. this.objectStack.push(user);
  38. }
  39. }
  40. public void endElement(String uri, String localName, String qName) throws SAXException
  41. {
  42. //Remove last added element
  43. this.elementStack.pop();
  44. //User instance has been constructed so pop it from object stack and push in userList
  45. if ("user".equals(qName))
  46. {
  47. User object = this.objectStack.pop();
  48. this.userList.add(object);
  49. }
  50. }
  51. /**
  52. * This will be called everytime parser encounter a value node
  53. * */
  54. public void characters(char[] ch, int start, int length) throws SAXException
  55. {
  56. String value = new String(ch, start, length).trim();
  57. if (value.length() == 0)
  58. {
  59. return; // ignore white space
  60. }
  61. //handle the value based on to which element it belongs
  62. if ("firstName".equals(currentElement()))
  63. {
  64. User user = (User) this.objectStack.peek();
  65. user.setFirstName(value);
  66. }
  67. else if ("lastName".equals(currentElement()))
  68. {
  69. User user = (User) this.objectStack.peek();
  70. user.setLastName(value);
  71. }
  72. }
  73. /**
  74. * Utility method for getting the current element in processing
  75. * */
  76. private String currentElement()
  77. {
  78. return this.elementStack.peek();
  79. }
  80. //Accessor for userList object
  81. public ArrayList getUsers()
  82. {
  83. return userList;
  84. }
  85. }

4. SAX 解析器读取 XML 文件

  1. package com.howtodoinjava.xml.sax;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.util.ArrayList;
  5. import org.xml.sax.InputSource;
  6. import org.xml.sax.SAXException;
  7. import org.xml.sax.XMLReader;
  8. import org.xml.sax.helpers.XMLReaderFactory;
  9. public class UsersXmlParser
  10. {
  11. public ArrayList parseXml(InputStream in)
  12. {
  13. //Create a empty link of users initially
  14. ArrayList<user> users = new ArrayList</user><user>();
  15. try
  16. {
  17. //Create default handler instance
  18. UserParserHandler handler = new UserParserHandler();
  19. //Create parser from factory
  20. XMLReader parser = XMLReaderFactory.createXMLReader();
  21. //Register handler with parser
  22. parser.setContentHandler(handler);
  23. //Create an input source from the XML input stream
  24. InputSource source = new InputSource(in);
  25. //parse the document
  26. parser.parse(source);
  27. //populate the parsed users list in above created empty list; You can return from here also.
  28. users = handler.getUsers();
  29. } catch (SAXException e) {
  30. // TODO Auto-generated catch block
  31. e.printStackTrace();
  32. } catch (IOException e) {
  33. // TODO Auto-generated catch block
  34. e.printStackTrace();
  35. } finally {
  36. }
  37. return users;
  38. }
  39. }

5)测试 SAX 解析器

让我们编写一些代码来测试我们的处理器是否真正起作用。

  1. package com.howtodoinjava.xml.sax;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.FileNotFoundException;
  5. import java.util.ArrayList;
  6. public class TestSaxParser
  7. {
  8. public static void main(String[] args) throws FileNotFoundException
  9. {
  10. //Locate the file
  11. File xmlFile = new File("D:/temp/sample.xml");
  12. //Create the parser instance
  13. UsersXmlParser parser = new UsersXmlParser();
  14. //Parse the file
  15. ArrayList users = parser.parseXml(new FileInputStream(xmlFile));
  16. //Verify the result
  17. System.out.println(users);
  18. }
  19. }
  20. Output:
  21. [100:Tom:Hanks, 101:Lokesh:Gupta, 102:HowToDo:InJava]

下载这篇文章的源码

学习愉快!