SAX 解析到文件,缓存到内存

2024-04-01 21:58
文章标签 内存 解析 缓存 sax

本文主要是介绍SAX 解析到文件,缓存到内存,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目的
    通过一个小的SAX例子,我们更清晰的理解SAX的工作原理。

    本文例子主要实现:
    1. 将每个Employee信息输出到自己的文件中,文件名是以Employee ID和Employee Name来命名的,注意,观察代码中是如何得到Employee ID和Employee Name;
    2. 将每个Employee信息存入到Map中,其中,Map中的每个Value对应一个Employee的Collection,Map中的每个Key对应该Employee的ID。


    package shuai.study.sax.demo;  import java.io.File;  import java.io.IOException;  import java.util.Collection;  import java.util.HashMap;  import java.util.LinkedList;  import java.util.Map;  import javax.xml.parsers.ParserConfigurationException;  import javax.xml.parsers.SAXParser;  import javax.xml.parsers.SAXParserFactory;  import org.apache.commons.io.FileUtils;  import org.apache.commons.lang3.StringUtils;  import org.xml.sax.Attributes;  import org.xml.sax.SAXException;  import org.xml.sax.helpers.DefaultHandler;  /** * @author shengshu *  */  public class SaxHandler extends DefaultHandler {  private final static String leafNodeText = "|firstname|;|lastname|;|sex|;|country|;|province|;|city|;|village|;|mobile|;|mail|;|qq|;|postcode|;|profession|";  private Map<String, Collection<String>> companyMap = null;  private Collection<String> employeeCollection = null;  private String currentValue = null;  private String currentCharacters = null;  private StringBuffer idAndNameStringBuffer = null;  public SaxHandler(File inputFile) {  this.parseDocument(inputFile);  }  private void parseDocument(File inputFile) {  SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();  try {  SAXParser saxParser = saxParserFactory.newSAXParser();  saxParser.parse(inputFile, this);  } catch (ParserConfigurationException pce) {  pce.printStackTrace();  } catch (SAXException saxe) {  saxe.printStackTrace();  } catch (IOException ioe) {  ioe.printStackTrace();  }  }  @Override  public void startDocument() throws SAXException {  super.startDocument();  this.companyMap = new HashMap<String, Collection<String>>();  }  @Override  public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {  if (qName.equalsIgnoreCase("Employee")) {  this.employeeCollection = new LinkedList<String>();  this.idAndNameStringBuffer = new StringBuffer();  this.currentValue = attributes.getValue("ID");  }  }  @Override  public void characters(char[] buffer, int start, int length) {  this.currentCharacters = new String(buffer, start, length);  }  @Override  public void endElement(String uri, String localName, String qName) throws SAXException {  if (StringUtils.containsIgnoreCase(leafNodeText, "|" + qName + "|")) {  this.employeeCollection.add(qName + ": " + this.currentCharacters);  if (qName.equalsIgnoreCase("FirstName")) {  this.idAndNameStringBuffer.append(this.currentCharacters);  }  if (qName.equalsIgnoreCase("LastName")) {  this.idAndNameStringBuffer.append(this.currentCharacters);  }  }  if (qName.equalsIgnoreCase("Employee")) {  this.companyMap.put(this.currentValue, this.employeeCollection);  this.idAndNameStringBuffer.append("-").append(this.currentValue);  this.writeEmployee(employeeCollection, idAndNameStringBuffer.toString());  }  }  private void writeEmployee(Collection<String> employeeCollection, String fileName) {  String outputFileDirectory = SaxHandler.class.getResource("/file/output/").getPath();  String outputFilePath = outputFileDirectory + fileName + ".xml";  File outputFile = new File(outputFilePath);  try {  FileUtils.writeLines(outputFile, employeeCollection, false);  } catch (IOException ioe) {  ioe.printStackTrace();  }  }  @Override  public void endDocument() throws SAXException {  super.endDocument();  }  public Map<String, Collection<String>> getCompanyMap() {  return this.companyMap;  }  }  

    package shuai.study.sax.demo;  import java.io.File;  import java.util.Collection;  import java.util.Iterator;  import java.util.Map;  import java.util.Map.Entry;  /** * @author shengshu *  */  public class SaxDemo {  public static void displayCompany(Map<String, Collection<String>> companyMap) {  Iterator<Entry<String, Collection<String>>> companyIterator = companyMap.entrySet().iterator();  while (companyIterator.hasNext()) {  Entry<String, Collection<String>> companyEntry = companyIterator.next();  String id = companyEntry.getKey();  System.out.println("============== Employee ID " + id + " Start ==============");  Collection<String> employeeCollection = companyEntry.getValue();  Iterator<String> employeeIterator = employeeCollection.iterator();  while (employeeIterator.hasNext()) {  String leafNodeAndValue = employeeIterator.next();  System.out.println(leafNodeAndValue);  }  System.out.println("============== Employee ID " + id + " End ==============");  }  }  public static void main(String[] args) {  String inputFilePath = SaxDemo.class.getResource("/file/input/company.xml").getPath();  File inputFile = new File(inputFilePath);  SaxHandler saxHandler = new SaxHandler(inputFile);  Map<String, Collection<String>> companyMap = saxHandler.getCompanyMap();  SaxDemo.displayCompany(companyMap);  }  }  

    <?xml version = "1.0" encoding="UTF-8"?>  <Company>  <Employee ID="37">  <Name>  <FirstName>Zhou</FirstName>  <LastName>Shengshuai</LastName>  </Name>  <Sex>Male</Sex>  <Address>  <Country>China</Country>  <Province>ShanDong</Province>  <City>LinYi</City>  <Village>FengHuangYu</Village>  <Contact>  <Mobile>18108***778</Mobile>  <Mail>zhoushengshuai2007@163.com</Mail>  <QQ>254392398</QQ>  <Postcode>276422</Postcode>  </Contact>  </Address>  <Profession>Software</Profession>  </Employee>  <Employee ID="66">  <Name>  <FirstName>Wang</FirstName>  <LastName>Eric</LastName>  </Name>  <Sex>Male</Sex>  <Address>  <Country>China</Country>  <Province>HeBei</Province>  <City>QinHuangDao</City>  <Village>hhh</Village>  <Contact>  <Mobile>150*****955</Mobile>  <Mail>eric@163.com</Mail>  <QQ>666666666</QQ>  <Postcode>111666</Postcode>  </Contact>  </Address>  <Profession>Software</Profession>  </Employee>  <Employee ID="99">  <Name>  <FirstName>Shi</FirstName>  <LastName>Stone</LastName>  </Name>  <Sex>Male</Sex>  <Address>  <Country>China</Country>  <Province>HeNan</Province>  <City>PingDingShan</City>  <Village>nnn</Village>  <Contact>  <Mobile>186*****015</Mobile>  <Mail>stone@163.com</Mail>  <QQ>999999999</QQ>  <Postcode>111999</Postcode>  </Contact>  </Address>  <Profession>Software</Profession>  </Employee>  </Company>  

这篇关于SAX 解析到文件,缓存到内存的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/868234

相关文章

golang内存对齐的项目实践

《golang内存对齐的项目实践》本文主要介绍了golang内存对齐的项目实践,内存对齐不仅有助于提高内存访问效率,还确保了与硬件接口的兼容性,是Go语言编程中不可忽视的重要优化手段,下面就来介绍一下... 目录一、结构体中的字段顺序与内存对齐二、内存对齐的原理与规则三、调整结构体字段顺序优化内存对齐四、内

C语言中自动与强制转换全解析

《C语言中自动与强制转换全解析》在编写C程序时,类型转换是确保数据正确性和一致性的关键环节,无论是隐式转换还是显式转换,都各有特点和应用场景,本文将详细探讨C语言中的类型转换机制,帮助您更好地理解并在... 目录类型转换的重要性自动类型转换(隐式转换)强制类型转换(显式转换)常见错误与注意事项总结与建议类型

MySQL 缓存机制与架构解析(最新推荐)

《MySQL缓存机制与架构解析(最新推荐)》本文详细介绍了MySQL的缓存机制和整体架构,包括一级缓存(InnoDBBufferPool)和二级缓存(QueryCache),文章还探讨了SQL... 目录一、mysql缓存机制概述二、MySQL整体架构三、SQL查询执行全流程四、MySQL 8.0为何移除查

在Rust中要用Struct和Enum组织数据的原因解析

《在Rust中要用Struct和Enum组织数据的原因解析》在Rust中,Struct和Enum是组织数据的核心工具,Struct用于将相关字段封装为单一实体,便于管理和扩展,Enum用于明确定义所有... 目录为什么在Rust中要用Struct和Enum组织数据?一、使用struct组织数据:将相关字段绑

使用Java实现一个解析CURL脚本小工具

《使用Java实现一个解析CURL脚本小工具》文章介绍了如何使用Java实现一个解析CURL脚本的工具,该工具可以将CURL脚本中的Header解析为KVMap结构,获取URL路径、请求类型,解析UR... 目录使用示例实现原理具体实现CurlParserUtilCurlEntityICurlHandler

深入解析Spring TransactionTemplate 高级用法(示例代码)

《深入解析SpringTransactionTemplate高级用法(示例代码)》TransactionTemplate是Spring框架中一个强大的工具,它允许开发者以编程方式控制事务,通过... 目录1. TransactionTemplate 的核心概念2. 核心接口和类3. TransactionT

数据库使用之union、union all、各种join的用法区别解析

《数据库使用之union、unionall、各种join的用法区别解析》:本文主要介绍SQL中的Union和UnionAll的区别,包括去重与否以及使用时的注意事项,还详细解释了Join关键字,... 目录一、Union 和Union All1、区别:2、注意点:3、具体举例二、Join关键字的区别&php

Spring IOC控制反转的实现解析

《SpringIOC控制反转的实现解析》:本文主要介绍SpringIOC控制反转的实现,IOC是Spring的核心思想之一,它通过将对象的创建、依赖注入和生命周期管理交给容器来实现解耦,使开发者... 目录1. IOC的基本概念1.1 什么是IOC1.2 IOC与DI的关系2. IOC的设计目标3. IOC

java中的HashSet与 == 和 equals的区别示例解析

《java中的HashSet与==和equals的区别示例解析》HashSet是Java中基于哈希表实现的集合类,特点包括:元素唯一、无序和可包含null,本文给大家介绍java中的HashSe... 目录什么是HashSetHashSet 的主要特点是HashSet 的常用方法hasSet存储为啥是无序的

Linux内存泄露的原因排查和解决方案(内存管理方法)

《Linux内存泄露的原因排查和解决方案(内存管理方法)》文章主要介绍了运维团队在Linux处理LB服务内存暴涨、内存报警问题的过程,从发现问题、排查原因到制定解决方案,并从中学习了Linux内存管理... 目录一、问题二、排查过程三、解决方案四、内存管理方法1)linux内存寻址2)Linux分页机制3)