Home  >  Article  >  Backend Development  >  XML Programming-SAX

XML Programming-SAX

黄舟
黄舟Original
2017-02-20 15:11:131397browse

XMLProgramming-SAX

##Basic Overview


SAX

, full nameSimple API for XML, is both an interface and a software package. It is an alternative to XMLparsing. SAXDifferent from DOM parsing, it scans the document line by line and parses while scanning. Since the application only checks the data as it is read, there is no need to store the data in memory, which is a huge advantage when parsing large documents.

SAX

is an event-driven "push" model for processing XML, although it is not W3C standard, but it is a widely recognized API. SAXThe parser does not build a complete document tree like DOM, but activates a series of events when reading the document. These events are pushed to event handlers, which then provide access to the document content.

PSSAX cannot modify the XML file. Delete and add operations.

Why introduce

SAX technology?

DOM

technology is also a very good DOM parsing solution, why does SAX still appear? What about technology? The reason is very simple, that is, DOM saves XML in the structure of a document tree, which means that # is saved in one go ##XML is read into memory, then this is not possible in large XML files. That's why the scanning and parsing technology SAX was born.

Schematic


##SAXParsing mechanism

SAX
Parsing Allows the document to be processed when the document is read, without having to wait until the entire document is loaded before the document is operated.

In Java

, by inheriting the DefaultHandler interface, you can develop a SAXParser. The parsing mechanism of SAX is very similar to the event listening mechanism. They both wait for a certain event to be triggered and then call the corresponding method.

The most commonly used

5

events of the SAX parser: 1,

startDocument(): This marks the SAX parser scanning to the beginning of the document.

2, endDocument(), this identifies the end position of the document scanned by the SAX parser.

3, startElement(), which indicates that the SAX parser scanned The opening tag of an element.

4, character(), this indicates that the SAX parser has scanned Some text, note that it is stored in the form of char array.

5, endElement(), this indicates that the SAX parser has scanned The closing tag of an element.

Event handler common method parameter list

public void startDocument()

public void startElement(String uri, String localName, String qName,Attributes attributes)

uri - Namespace URI, if the element does not have any namespace URI, or the empty string if no namespace processing is being performed.

localName - Local name (without prefix), or the empty string if no namespace processing is being performed.

qName - Qualified name (with prefix), or the empty string if qualified name is not available.

attributes - Attributes attached to the element. If there are no attributes, it will be an empty Attributes object.

public void characters(char[] ch, int start, int length)

ch - All characters in the document.

#start - The starting position in the character array.

#length - The number of characters to use from the character array.

public void endElement(String uri, String localName, String qName)

uri - Namespace URI, or the empty string if the element does not have any namespace URI, or if no namespace processing is being performed.

localName - Local name (without prefix), or the empty string if no namespace processing is being performed.

qName - Qualified name (with prefix), or the empty string if qualified name is not available.

##public void endDocument()

Parsing method

By using the parser and event handler together, the XML document can be parsed. The parser can be created using the API of JAXP to create the SAX parser After that, you can specify the parser to parse a certain XML document. The event handler is written by the programmer. Through the parameters of the method in the event handler, the programmer can easily get the data parsed by the sax parser, so that he can decide how to process it. Data is processed.

Parsing steps

1, by calling SAXParserFactory The newInstance() method obtains the Sax parser factory object.

2, obtained by calling the newSAXParser() method through the Sax parser factory object ParserSAXParserObject

3, by calling the parse method of the parser object Associate the parser with the event handler object

Case:

XML6.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<班级 班次="1班" 编号="C1">
	<学生 地址="湖南" 学号="n1" 性别="男" 授课方式="面授" 朋友="n2" 班级编号="C1">
		<名字>张三</名字>
		<年龄>20</年龄>
		<介绍>不错</介绍>
	</学生>
	<学生 学号="n2" 性别="女" 授课方式="面授" 朋友="n1 n3" 班级编号="C1">
		<名字>李四</名字>
		<年龄>18</年龄>
		<介绍>很好</介绍>
	</学生>
	<学生 学号="n3" 性别="男" 授课方式="面授" 朋友="n2" 班级编号="C1">
		<名字>王五</名字>
		<年龄>22</年龄>
		<介绍>非常好</介绍>
	</学生>
	<学生 性别="男">
		<名字>小明</名字>
		<年龄>30</年龄>
		<介绍>好</介绍>
	</学生>
</班级>


package com.pc;
import javax.xml.parsers.*;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class XML6{
	//使用sax技术去解析xml文件
	public static void main(String[] args) throws Exception, SAXException {
		// TODO Auto-generated method stub
		//1.创建SaxParserFactory
		SAXParserFactory spf=SAXParserFactory.newInstance();
		//2.创建SaxParser 解析器
		SAXParser saxParser=spf.newSAXParser();
		//3 把xml文件和事件处理对象关联
		saxParser.parse("src/com/pc/XML6.xml",new MyDefaultHandler2() );
	}
}
// 只显示学生的名字和年龄
class MyDefaultHandler2 extends DefaultHandler{
	private boolean isName=false;
	private boolean isAge=false;
	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		// TODO Auto-generated method stub
		String con=new String(ch,start,length);
		if(!con.trim().equals("")&&(isName||isAge)){
			System.out.println(con);
		}
		isName=false;
		isAge=false;
		//super.characters(ch, start, length);
	}
	@Override
	public void endDocument() throws SAXException {
		// TODO Auto-generated method stub
		super.endDocument();
	}
	@Override
	public void endElement(String uri, String localName, String name)
			throws SAXException {
		// TODO Auto-generated method stub
		super.endElement(uri, localName, name);
	}
	@Override
	public void startDocument() throws SAXException {
		// TODO Auto-generated method stub
		super.startDocument();
	}
	@Override
	public void startElement(String uri, String localName, String name,
			Attributes attributes) throws SAXException {
		// TODO Auto-generated method stub
		if(name.equals("名字")){
			this.isName=true;
		}else if(name.equals("年龄")){
			this.isAge=true;
		}
	}
}
//定义事件处理类
class MyDefaultHandler1 extends DefaultHandler{
	//发现文档开始
	@Override
	public void startDocument() throws SAXException {
		// TODO Auto-generated method stub
		System.out.println("startDocument()");
		super.startDocument();
	}
	//发现xml文件中的一个元素
	@Override
	public void startElement(String uri, String localName, String name,
			Attributes attributes) throws SAXException {
		// TODO Auto-generated method stub
		System.out.println("元素名称="+name);	
	}
	//发现xml文件中的文本
	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		String con=new String(ch,start,length);
		//显示文本内容:
		if(!con.trim().equals("")){
			System.out.println(new String(ch,start,length));
		}
	}
	//发现xml文件中一个元素介绍</xx>
	@Override
	public void endElement(String uri, String localName, String name)
			throws SAXException {
		// TODO Auto-generated method stub
		super.endElement(uri, localName, name);
	}
	//发现文档结束
	@Override
	public void endDocument() throws SAXException {
		// TODO Auto-generated method stub
		System.out.println("endDocument()");
		super.endDocument();
	}
}

The above is the content of XML programming-SAX. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:XML Programming-DOMNext article:XML Programming-DOM