XML Programming-SAX
XMLProgramming-SAX
##Basic Overview
, 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.
SAXis 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.
PS:SAX cannot modify the XML file. Delete and add operations.
Why introduceSAX technology?
DOMtechnology 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
5events 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)!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Can XML files be opened with PPT? XML, Extensible Markup Language (Extensible Markup Language), is a universal markup language that is widely used in data exchange and data storage. Compared with HTML, XML is more flexible and can define its own tags and data structures, making the storage and exchange of data more convenient and unified. PPT, or PowerPoint, is a software developed by Microsoft for creating presentations. It provides a comprehensive way of

Using Python to merge and deduplicate XML data XML (eXtensibleMarkupLanguage) is a markup language used to store and transmit data. When processing XML data, sometimes we need to merge multiple XML files into one, or remove duplicate data. This article will introduce how to use Python to implement XML data merging and deduplication, and give corresponding code examples. 1. XML data merging When we have multiple XML files, we need to merge them

Convert XML data in Python to CSV format XML (ExtensibleMarkupLanguage) is an extensible markup language commonly used for data storage and transmission. CSV (CommaSeparatedValues) is a comma-delimited text file format commonly used for data import and export. When processing data, sometimes it is necessary to convert XML data to CSV format for easy analysis and processing. Python is a powerful

Implementing filtering and sorting of XML data using Python Introduction: XML is a commonly used data exchange format that stores data in the form of tags and attributes. When processing XML data, we often need to filter and sort the data. Python provides many useful tools and libraries to process XML data. This article will introduce how to use Python to filter and sort XML data. Reading the XML file Before we begin, we need to read the XML file. Python has many XML processing libraries,

Importing XML data into the database using PHP Introduction: During development, we often need to import external data into the database for further processing and analysis. As a commonly used data exchange format, XML is often used to store and transmit structured data. This article will introduce how to use PHP to import XML data into a database. Step 1: Parse the XML file First, we need to parse the XML file and extract the required data. PHP provides several ways to parse XML, the most commonly used of which is using Simple

Python implements conversion between XML and JSON Introduction: In the daily development process, we often need to convert data between different formats. XML and JSON are common data exchange formats. In Python, we can use various libraries to convert between XML and JSON. This article will introduce several commonly used methods, with code examples. 1. To convert XML to JSON in Python, we can use the xml.etree.ElementTree module

Handling Errors and Exceptions in XML Using Python XML is a commonly used data format used to store and represent structured data. When we use Python to process XML, sometimes we may encounter some errors and exceptions. In this article, I will introduce how to use Python to handle errors and exceptions in XML, and provide some sample code for reference. Use try-except statement to catch XML parsing errors When we use Python to parse XML, sometimes we may encounter some

Python parses special characters and escape sequences in XML XML (eXtensibleMarkupLanguage) is a commonly used data exchange format used to transfer and store data between different systems. When processing XML files, you often encounter situations that contain special characters and escape sequences, which may cause parsing errors or misinterpretation of the data. Therefore, when parsing XML files using Python, we need to understand how to handle these special characters and escape sequences. 1. Special characters and
