java sax解析xml

我碰巧通读了有关Java中XML解析和构建API的章节。 我试用了样本XML上的其他解析器。 然后,我想在我的博客上分享它,这样我就可以得到该代码的参考以及任何阅读此代码的参考。 在本文中,我将在不同的解析器中解析相同的XML,以执行将XML内容填充到对象中,然后将对象添加到列表中的相同操作。

示例中考虑的示例XML是:

<employees><employee id="111"><firstName>Rakesh</firstName><lastName>Mishra</lastName><location>Bangalore</location></employee><employee id="112"><firstName>John</firstName><lastName>Davis</lastName><location>Chennai</location></employee><employee id="113"><firstName>Rajesh</firstName><lastName>Sharma</lastName><location>Pune</location></employee>
</employees>

XML内容要提取到的对象定义如下:

class Employee{String id;String firstName;String lastName;String location;@Overridepublic String toString() {return firstName+" "+lastName+"("+id+")"+location;}
}

我提供了3个主要解析器的示例代码:

  • DOM解析器
  • SAX解析器
  • StAX解析器

使用DOM解析器

我正在使用JDK附带的DOM解析器实现,在我的示例中,我使用的是JDK7。DOM解析器将完整的XML内容加载到Tree结构中。 然后,我们遍历Node和NodeList以获取XML的内容。 下面给出了使用DOM解析器进行XML解析的代码。

public class DOMParserDemo {public static void main(String[] args) throws Exception {//Get the DOM Builder FactoryDocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();//Get the DOM BuilderDocumentBuilder builder = factory.newDocumentBuilder();//Load and Parse the XML document//document contains the complete XML as a Tree.Document document = builder.parse(ClassLoader.getSystemResourceAsStream("xml/employee.xml"));List<Employee> empList = new ArrayList<>();//Iterating through the nodes and extracting the data.NodeList nodeList = document.getDocumentElement().getChildNodes();for (int i = 0; i < nodeList.getLength(); i++) {//We have encountered an <employee> tag.Node node = nodeList.item(i);if (node instanceof Element) {Employee emp = new Employee();emp.id = node.getAttributes().getNamedItem("id").getNodeValue();NodeList childNodes = node.getChildNodes();for (int j = 0; j < childNodes.getLength(); j++) {Node cNode = childNodes.item(j);//Identifying the child tag of employee encountered. if (cNode instanceof Element) {String content = cNode.getLastChild().getTextContent().trim();switch (cNode.getNodeName()) {case "firstName":emp.firstName = content;break;case "lastName":emp.lastName = content;break;case "location":emp.location = content;break;}}}empList.add(emp);}}//Printing the Employee list populated.for (Employee emp : empList) {System.out.println(emp);}}
}class Employee{String id;String firstName;String lastName;String location;@Overridepublic String toString() {return firstName+" "+lastName+"("+id+")"+location;}
}

上面的输出将是:

Rakesh Mishra(111)Bangalore
John Davis(112)Chennai
Rajesh Sharma(113)Pune

使用SAX解析器

SAX解析器不同于DOM解析器,在DOM解析器中,SAX解析器不会将完整的XML加载到内存中,而是在遇到不同元素(例如,打开标签,关闭标签,字符数据)时逐行触发不同事件来解析XML ,评论等。 这就是SAX解析器被称为基于事件的解析器的原因。

除了XML源文件,我们还注册了扩展DefaultHandler类的处理程序。 DefaultHandler类提供了我们感兴趣的各种回调:

  • startElement() –遇到标签的开始时触发此事件。
  • endElement() –遇到标签结尾时触发此事件。
  • character() –遇到一些文本数据时触发此事件。

下面给出了使用SAX Parser解析XML的代码:

import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;public class SAXParserDemo {public static void main(String[] args) throws Exception {SAXParserFactory parserFactor = SAXParserFactory.newInstance();SAXParser parser = parserFactor.newSAXParser();SAXHandler handler = new SAXHandler();parser.parse(ClassLoader.getSystemResourceAsStream("xml/employee.xml"), handler);//Printing the list of employees obtained from XMLfor ( Employee emp : handler.empList){System.out.println(emp);}}
}
/*** The Handler for SAX Events.*/
class SAXHandler extends DefaultHandler {List<Employee> empList = new ArrayList<>();Employee emp = null;String content = null;@Override//Triggered when the start of tag is found.public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {switch(qName){//Create a new Employee object when the start tag is foundcase "employee":emp = new Employee();emp.id = attributes.getValue("id");break;}}@Overridepublic void endElement(String uri, String localName, String qName) throws SAXException {switch(qName){//Add the employee to list once end tag is foundcase "employee":empList.add(emp);       break;//For all other end tags the employee has to be updated.case "firstName":emp.firstName = content;break;case "lastName":emp.lastName = content;break;case "location":emp.location = content;break;}}@Overridepublic void characters(char[] ch, int start, int length) throws SAXException {content = String.copyValueOf(ch, start, length).trim();}}class Employee {String id;String firstName;String lastName;String location;@Overridepublic String toString() {return firstName + " " + lastName + "(" + id + ")" + location;}
}

上面的输出将是:

Rakesh Mishra(111)Bangalore
John Davis(112)Chennai
Rajesh Sharma(113)Pune

使用StAX解析器

StAX代表XML的Streaming API,并且StAX Parser与DOM有所不同,就像SAX Parser一样。 StAX解析器与SAX解析器也有细微的区别。

  • SAX解析器推送数据,但StAX解析器从XML提取所需的数据。
  • StAX解析器将光标保持在文档的当前位置,从而可以提取光标处可用的内容,而SAX解析器在遇到某些数据时发出事件。

XMLInputFactory和XMLStreamReader是两个可用于加载XML文件的类。 当我们使用XMLStreamReader读取XML文件时,将以整数值的形式生成事件,然后将这些事件与XMLStreamConstants中的常量进行比较。 以下代码显示了如何使用StAX解析器解析XML:

import java.util.ArrayList;
import java.util.List;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;public class StaxParserDemo {public static void main(String[] args) throws XMLStreamException {List<Employee> empList = null;Employee currEmp = null;String tagContent = null;XMLInputFactory factory = XMLInputFactory.newInstance();XMLStreamReader reader = factory.createXMLStreamReader(ClassLoader.getSystemResourceAsStream("xml/employee.xml"));while(reader.hasNext()){int event = reader.next();switch(event){case XMLStreamConstants.START_ELEMENT: if ("employee".equals(reader.getLocalName())){currEmp = new Employee();currEmp.id = reader.getAttributeValue(0);}if("employees".equals(reader.getLocalName())){empList = new ArrayList<>();}break;case XMLStreamConstants.CHARACTERS:tagContent = reader.getText().trim();break;case XMLStreamConstants.END_ELEMENT:switch(reader.getLocalName()){case "employee":empList.add(currEmp);break;case "firstName":currEmp.firstName = tagContent;break;case "lastName":currEmp.lastName = tagContent;break;case "location":currEmp.location = tagContent;break;}break;case XMLStreamConstants.START_DOCUMENT:empList = new ArrayList<>();break;}}//Print the employee list populated from XMLfor ( Employee emp : empList){System.out.println(emp);}}
}class Employee{String id;String firstName;String lastName;String location;@Overridepublic String toString(){return firstName+" "+lastName+"("+id+") "+location;}
}

上面的输出是:

Rakesh Mishra(111) Bangalore
John Davis(112) Chennai
Rajesh Sharma(113) Pune

到此为止,我已经介绍了解析相同的XML文档并执行使用所有三个解析器来填充Employee对象列表的相同任务:

  • DOM解析器
  • SAX解析器
  • StAX解析器
参考:来自Experiences Unlimited博客的JCG合作伙伴 Mohamed Sanaulla 在Java中使用DOM,SAX和StAX Parser在Java中解析XML 。

翻译自: https://www.javacodegeeks.com/2013/05/parsing-xml-using-dom-sax-and-stax-parser-in-java.html

java sax解析xml

java sax解析xml_在Java中使用DOM,SAX和StAX解析器解析XML相关推荐

  1. XML解析的三种方式(dom,sax,dom4j)

    1.Dom解析: 要解析的xml文件内容: <?xml version="1.0" encoding="utf-8" standalone="n ...

  2. java并发集合有哪些_java中常见并发集合有哪些?详细解析

    关于java中有关集合的知识点,相信大家还是有所了解的.集合中所包含的知识点是非常丰富的,而且可以细分为很多类型.今天就来为大家介绍一下并发集合的有关知识,并且用实际代码为大家展示,一起来看看吧. 首 ...

  3. java 读utf-8 xml_用Java和UTF-8編碼生成有效的XML。

    I am using JAXP to generate and parse an XML document from which some fields are loaded from a datab ...

  4. java 读utf-8 xml_〖JAVA经验〗JDom输出UTF-8的XML完美解决方法

    完美的解决方法从辟谣开始: 1)JDOM是否生成UTF-8的文件与Format是否设置无关,只有输出其他字符编码才需要设置,见下面的注释. 2)JDOM输出UTF-8文件乱码的根本原因并非在JDOMA ...

  5. java json转换xml_在Java中将JSON转换为XML

    我是json的新手.我有一个程序可以从json对象生成xml. String str = "{'name':'JSON','integer':1,'double':2.0,'boolean' ...

  6. c libxml2解析html,在Python中,lxml和libxml2哪个更适合解析格式错误的html?

    在libxml2 page中,您可以看到以下注释:Note that some of the Python purist dislike the default set of Python bindi ...

  7. 用Java实现二叉树前序遍历、中序遍历和后序遍历。

    用Java实现二叉树前序遍历.中序遍历和后序遍历. 解析: public class Tree {private int data; /* 数据节点 */private Tree left; /* 左 ...

  8. java面试题及答案 JAVA相关基础知识

    1.面向对象的特征有哪些方面 1).抽象: 抽象就是忽略一个主题中与当前目标无关的那些方面,以便更充分地注意与当前目标有关的方面.抽象并不打算了解全部问题,而只是选择其中的一部分,暂时不用部分细节.抽 ...

  9. Java面试题目汇总/英文Java面试题(核心知识)

    一.面向对象的三个基本特征    2.方法重载和方法重写的概念和区别    3.接口和内部类.抽象类的特性    4.文件读写的基本类    **5.串行化的注意事项以及如何实现串行化    6.线程 ...

最新文章

  1. TensorFlow常用Python扩展包
  2. 数据库Mysql的学习(八)-储存过程和事务和导入导出
  3. 各种媒体在线播放代码
  4. python显示无效语法怎么处理-Python不支持 i ++ 语法的原因解析
  5. Linux C: 文件操作相关的系统调用
  6. Page directive: illegal to have multiple occurrences of contentType with different values
  7. [css] 如何让背景图片固定不随滚动条滚动
  8. powershell加win的dns服务器,解决网站负载均衡问题
  9. JAVA开发血泪之路:一步步搭建spring框架
  10. 高速的二舍八入三七作五_京承高速收费“二舍八入 三七作五”
  11. JavaScript变量复制
  12. php布署 群辉_docker一键搭建Nginx+PHP环境(含自动部署命令)
  13. 转: 参数修饰符ref,out ,params的区别
  14. 输出调节2.3——内模控制器设计
  15. Excel-图表与文本框/图片的组合
  16. 设置屏幕亮度,并且监听屏幕亮度变化
  17. struts中的javascript - seinbar的专栏
  18. html5一键打包成苹果软件,GDB苹果网页一键打包工具如何使用?GDB苹果网页一键打包工具安装使用教程...
  19. f4在计算机中的作用,F4键原来这么神奇!F4在办公时的妙用你知多少
  20. 【代码篇】通过三维坐标在CAD里自动输出三维模型

热门文章

  1. 汇编语言(十二)之统计小于平均数的个数
  2. java各种集合的线程安全
  3. 秒杀系统设计的 5 个要点:前端三板斧+后端两条路
  4. 关于 NIO 你不得不知道的一些“地雷”
  5. jQuery选择器案例之——index.js
  6. ssm使用全注解实现增删改查案例——IEmpService
  7. 2015蓝桥杯省赛---java---B---1(三角形面积)
  8. Tomacat乱码解决
  9. layUI 日期组件单独使用 并且放大
  10. 计算机文化基础分析总结,《计算机文化基础实训》教学方案设计与课题分析总结.doc...