SAX介绍
SAX(Simple API for XML)是一种事件驱动的流式XML文件处理方式,区别与DOM方式的是不需要在内存中建一棵DOM树,而是根据读取XML时遇到的标签事件来顺序处理,因此具有速度快,内存占用上的优点。
XML生成
代码如下:
package com.test.sax; import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult; import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl; public class TestCreateXml { public static void main(String[] args) {
//创建SAXTransformerFactory实例
SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
try {
//创建TransformerHandler实例
TransformerHandler handler = factory.newTransformerHandler();
//创建Transformer实例
Transformer transformer = handler.getTransformer();
//设置输出的xml属性,encoding为编码,
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
//indent是确保输出的xml文件能够自动换行
transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //创建Result对象,将Result对象加载到TransHandler中
// 注意:1、这一步必须在Transformer.setOutputProperty()之后,不然设置的xml属性将不生效
// 2、这一步也必须在TransformerHandler.startDocument()之前,不然会报错。
// 分析源码后发现,startDocument()会先判断result是否为空,为空则报错
Result result = new StreamResult("src/test-sax-create.xml");
handler.setResult(result); // 创建属性Attribute对象
AttributesImpl attr = new AttributesImpl();
//开始写文件
handler.startDocument();
//写入根节点conpany
handler.startElement("", "", "conpany", attr); //清空属性,
attr.clear();
//设置属性
attr.addAttribute( "", "", "name", "", "1");
//写入根节点的子节点book
handler.startElement("", "", "department", attr); attr.clear();
//分别写入book节点的子节点
attr.addAttribute( "", "", "name", "", "employee1");
attr.addAttribute( "", "", "id", "", "1");
handler.startElement("", "", "employee", attr);
//写入子节点内容
handler.characters("123".toCharArray(), 0, "123".toCharArray().length);
//写入子节点末尾
handler.endElement("", "", "employee");
//写入department节点末尾
handler.endElement("", "", "department");
//写入根节点末尾
handler.endElement("", "", "conpany");
//写文件结束
handler.endDocument();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
}
}
生成文件如下:
XML解析
代码如下:
package com.test.sax; import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import javax.xml.parsers.ParserConfigurationException;
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 TestParseXml { public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException {
//创建SAXTransformerFactory实例
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
//创建TransformerHandler实例
SAXParser saxParser = saxParserFactory.newSAXParser(); MyHandler myHandler = new MyHandler(); saxParser.parse(TestParseXml.class.getClassLoader().getResourceAsStream("test.xml"), myHandler);
} } class MyHandler extends DefaultHandler{ /**
* 开始解析文档时,调用的方法
*/
@Override
public void startDocument() throws SAXException {
System.out.println("---------startDocument-------");
} /**
* 文档解析完结时,调用的方法
*/
@Override
public void endDocument() throws SAXException {
System.out.println("---------endDocument-------");
super.endDocument();
} /**
* 开始解析每个元素时,调用的方法,会重复调用
*/
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { //qName 元素标签
System.out.println("---------startElement-------" + qName); // 处理属性
if(attributes != null )
{
for (int i = 0; i < attributes.getLength(); ++i)
{
String attrName = attributes.getQName(i);
String attrValue = attributes.getValue(i);
System.out.print("\t "+ attrName + "=" + attrValue);
}
}
System.out.println("");
} @Override
public void endElement(String uri, String localName, String qName) throws SAXException { System.out.println("---------endElement-------" + qName);
} /**
* 解析到每个元素的内容时会调用此方法
*/
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
String content = new String(ch,start,length);
System.out.println("---------characters-------" + "content == "+ content);
}
}
控制台输出:
---------startDocument-------
---------startElement-------conpany
name=hd
---------characters-------content == ---------startElement-------department
name=department1
---------characters-------content == ---------startElement-------employee
name=employee1 id=1
---------characters-------content == 123
---------endElement-------employee
---------characters-------content == ---------endElement-------department
---------characters-------content == ---------startElement-------department
name=department2
---------characters-------content == ---------startElement-------employee
name=employee2 id=2
---------characters-------content == 321
---------endElement-------employee
---------characters-------content == ---------startElement-------employee
name=employee3 id=3
---------endElement-------employee
---------characters-------content == ---------endElement-------department
---------characters-------content == ---------startElement-------department
name=department3
---------characters-------content == ---------endElement-------department
---------characters-------content == ---------endElement-------conpany
---------endDocument-------
Simple API for XML