The final function of DOM and SAX is to allow us to use languages such as java JavaScript to obtain nodes, text, attributes and other information in xml files.
This article is quoted from other blogs. The content is easy to understand. In order to save time, I have directly excerpted it. There are usually two ways to parse XML in JAVA, DOM and SAX. Although DOM is a W3C standard and provides a standard parsing method, its parsing efficiency has always been unsatisfactory, because when using DOM to parse XML, the parser reads the entire document and builds a memory-resident tree structure (node tree). ), and then your code can use the DOM's standard interface to manipulate the tree structure. But in most cases we are only interested in part of the document, without parsing the entire document first, and it is also very time-consuming to index some of the data we need from the root node of the node tree.
SAX is an alternative to XML parsing. Compared to the Document Object Model DOM, SAX is a faster and lighter way to read and manipulate XML data
#. SAX allows you to process a document as it is read, so you don't have to wait for the entire document to be stored before taking action. It doesn't involve the overhead and conceptual leaps necessary for the DOM. SAX API is an event-based API suitable for processing data streams, that is, processing data sequentially as the data flows. The SAX API
# will notify you when certain events occur while it is parsing your document. Data you do not save will be discarded when you respond to it.
The following is an example of SAX parsing XML (a bit long, because all methods of SAX event processing are annotated in detail). There are four main interfaces for processing events in the SAX API. , they are ContentHandler, DTDHandler, EntityResolver and ErrorHandler respectively. The following example may be a bit lengthy. In fact, as long as you inherit the DefaultHandler class and overwrite some of the event processing methods, you can also achieve the effect of this example. But in order to have an overview, let's take a look at all the main event parsing methods in the SAX API. (In fact, DefaultHandler implements the above four event handler interfaces, and then provides the default implementation of each abstract method.)
1, ContentHandler interface: receiving documents Handler interface for notifications of logical content.
Java Code Collection Code
'import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org. xml.sax.Locator;
import org.xml.sax.SAXException;
class MyContentHandler implements ContentHandler{
StringBuffer jsonStringBuffer;
int frontBlankCount = 0;
public MyContentHandler(){
jsonStringBuffer = new StringBuffer();
}
/*
* Receive notification of character data.
* In the DOM, ch[begin:end] is equivalent to the node value of the Text node (nodeValue)
*/
@Override
public void characters(char[] ch, int begin, int length) throws SAXException {
StringBuffer buffer = new StringBuffer();
for(int i = begin; i
switch(ch[i]){
case '\\\\\\\\\\\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append("\\\\\\\ \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"");break;
default : buffer .append(ch[i]);
}
}
System.out.println(this.toBlankString(this.frontBlankCount)+
">>> characters("+length+"): "+buffer.toString());
}
/*
* Receive notification of the end of the document.
*/
@Override
public void endDocument() throws SAXException {
System.out.println(this.toBlankString(--this. frontBlankCount)+
">>> end document");
}
}}System.out.println(this.toBlankString(this.frontBlankCount)+">>> ignorable whitespace("+length+"): "+ buffer.toString());}
##}
/*
* Receive notification of skipped entities.
* The meaning of the parameters is as follows:
* name: The name of the entity to be skipped. If it is a parameter entity, the name will start with '%',
* If it is an external DTD subset, it will be the string "[dtd]"
*/
@Override
public void skippedEntity(String name ) throws SAXException {
System.out.println(this.toBlankString(this.frontBlankCount)+
">>> skipped_entity : "+name);
}
/*
* Receive notification of the start of a document.
*/
@Override
public void startDocument() throws SAXException {
System.out.println(this.toBlankString(this.frontBlankCount++) +
">>> start document ");
}
/*
* Receive notification of the start of an element.
* The meaning of the parameters is as follows:
* uri: the namespace of the element
* localName: the local name of the element (without prefix)
* qName : Qualified name of the element (with prefix)
* atts : Attribute collection of the element
*/
@Override
public void startElement(String uri , String localName, String qName,
Attributes atts) throws SAXException {
System.out.println(this.toBlankString(this.frontBlankCount++)+
">> ;> start element : "+qName+"("+uri+")");
}
/*
* Start prefix URI namespace scope mapping.
* The information for this event is not necessary for normal namespace processing:
* When the http://xml.org/sax/features/namespaces feature is true (default),
* The SAX XML reader will automatically replace prefixes in element and attribute names.
* Parameter meanings are as follows:
* prefix: prefix
* uri: namespace
*/
@Override
public void startPrefixMapping(String prefix,String uri)
throws SAXException {
System.out.println(this.toBlankString(this.frontBlankCount++)+
">>> start prefix_mapping : xmlns:"+prefix+" = "
+"\\\\\\\\\\\\\\\\\\\\\\\ \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\""+uri+"\\\\\ \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ \\\\\\\\\"");
}
private String toBlankString(int count ){
StringBuffer buffer = new StringBuffer();
for(int i = 0;i
buffer.append(" ");
return buffer.toString();
}
}'
2, DDTHandler interface: processor interface that receives notifications of DTD-related events
Java code collection code
'import org.xml.sax.DTDHandler;
import org.xml.sax.SAXException;
String notationName) throws SAXException {System.out.println(">>> unparsed entity declare : (name = "+name+",systemId = " +publicId+",publicId = "+systemId+",notationName = "+notationName+")");}
##import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
##public class MyEntityResolver implements EntityResolver {
/*
* Returns:
* An InputSource object describing the new input source, or null,
* to request the parser to open a regular URI connection to the system identifier.
*/
@Override
public InputSource resolveEntity(String publicId, String systemId)
throws SAXException, IOException {
return null;
}
}
##public class MyErrorHandler implements ErrorHandler {
/*
* Receive notification of recoverable errors
*/
@Override
public void error(SAXParseException e) throws SAXException {
System.err.println ("Error ("+e.getLineNumber()+","
+e.getColumnNumber()+") : "+e.getMessage());
}
/*
* Receive notification of unrecoverable errors.
*/
@Override
public void fatalError(SAXParseException e) throws SAXException {
System.err.println("FatalError ("+e .getLineNumber()+","
+e.getColumnNumber()+") : "+e.getMessage());
}
/*
* Receive notification of unrecoverable errors.
*/
@Override
public void warning(SAXParseException e) throws SAXException {
System.err.println("Warning ("+e .getLineNumber()+","
+e.getColumnNumber()+") : "+e.getMessage());
}
}
The main method of the Test class prints event information when parsing books.xml.
Java Code Collection Code
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.xml.sax.ContentHandler;
import org.xml.sax.DTDHandler;
import org.xml.sax .EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
##public class Test {
public static void main(String[] args) throws SAXException,
EntityResolver entityResolver = new MyEntityResolver();
//Create an XML parser (read and parse XML through SAX)
//Set the XML parser's handler for handling document content-related eventsreader.setContentHandler(contentHandler);//Set the XML parser's handler for handling error eventsreader.setErrorHandler(errorHandler);//Set the handler of the XML parser to handle DTD related eventsreader.setDTDHandler(dtdHandler);//Set the entity parser of the XML parserreader.setEntityResolver(entityResolver);//Parse the books.xml documentreader.parse(new InputSource( new FileReader("books.xml")));} ##}'
##Thinking in JAVA
##Core JAVA2
C++ primer
##>>> set document_locator: (lineNumber = 1, columnNumber = 1, systemId = null, publicId = null)
Error (2,7) : Document root element "books", must match DOCTYPE root "null".
>>> start prefix_mapping : xmlns: = "http://test.org/books"
> >> start element : books(http://test.org/books)
>>> characters(2): \\\\\\\\\\\\\\ \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ n\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ \\\\\\\\\\\\\\t
>>> characters(2): \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\n\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\t
>>> start element : book(http://test.org/books)
>>> characters(3): \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\n\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\t\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\t
>>> start element : name(http://test.org/books)
>>> characters(16): Thinking in JAVA
>>> end element : name(http://test.org/books)
>>> characters(2): \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\n\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\t
>>> end element : book(http://test.org/books)
>>> characters(2): \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\n\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\t
>>> start element : book(http://test.org/books)
>>> characters(3): \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\n\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\t\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\t
>>> start element : name(http://test.org/books)
>>> characters(10): Core JAVA2
>>> end element : name(http://test.org/books)
>>> characters(2): \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\n\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\t
>>> end element : book(http://test.org/books)
>>> characters(2): \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\n\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\t
>>> start element : book(http://test.org/books)
>>> characters(3): \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\n\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\t\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\t
>>> start element : name(http://test.org/books)
>>> characters(10): C++ primer
>>> end element : name(http://test.org/books)
>>> characters(2): \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\n\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\t
>>> end element : book(http://test.org/books)
>>> characters(1): \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\n
>>> end element : books(http://test.org/books)
>>> end prefix_mapping :
>>> end document
The above is the detailed content of Detailed explanation of XML SAX parsing. For more information, please follow other related articles on the PHP Chinese website!

The methods of reading XML files in Python include: 1. Use the xml.etree.ElementTree library for basic parsing; 2. Use the lxml library and XPath expression for advanced parsing. Through these methods, data in XML files can be processed and extracted efficiently.

Converting XML data into a table can be achieved through the following steps: 1. Parsing the XML file, 2. Mapping the data to the table structure, 3. Generating the table data. This transformation process can be easily implemented using Python's xml.etree.ElementTree and pandas libraries.

The reason for formatting XML files is to improve human reading and maintenance efficiency. 1. Manual formatting is inefficient and error-prone. 2. Automation tools such as Notepad and VisualStudioCode can quickly organize XML files. 3. Use Python's xml.dom.minidom module to simply format XML strings, but be careful to add additional blank nodes.

The .xsm file is an XMLSchema file that defines the structure and constraints of an XML file. 1) Use a text editor such as Notepad or VisualStudioCode to open the .xsm file. 2) For advanced features, use OxygenXMLEditor or AltovaXMLSpy for Schema verification and autocomplete. 3) Through Python's lxml library, you can verify whether the XML file complies with Schema, and use streaming processing to optimize the processing performance of large files.

The XML file sent in WeChat can be opened and processed through the following steps: 1. Extract the XML file from WeChat: Press and hold the file long and select "Save to mobile phone" or "Download". 2. Open files on different devices: Use browser or Notepad on Windows, browser or TextEdit on Mac, File app on iOS, File manager or XML viewer app on Android. 3. Understand and use XML file content: view file content through a browser or text editor, and use programming languages such as Python to parse and modify them if necessary.

The core function of XML files is to store and transfer structured data. 1) You can use the DOM or SAX method to parse XML files. DOM is suitable for small files and SAX is suitable for large files. 2) Generating XML files can be written directly through DOM or directly. 3) When processing namespaces, use namespace prefixes to avoid label conflicts. 4) When debugging, use verification tools and exception handling. 5) When optimizing, use SAX parser and cache mechanism.

Use Python to convert xlsx files to xml files. 1) Use the openpyxl library to read the xlsx file, 2) Use the xml.etree.ElementTree library to create and write the xml file, 3) Iterate through the data in the xlsx file and fill it into the xml structure, 4) Handle the encoding, data type and missing value problems that may be encountered.

Converting an invoice to XML format can be achieved through the following steps: 1. Data analysis: Extract relevant information from the invoice. 2. Data mapping: Map the extracted data into the XML structure. 3.XML generation: Use Python's xml.etree.ElementTree module to generate XML files. This process includes gradually building an XML tree structure and writing to the file.


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

Zend Studio 13.0.1
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Chinese version
Chinese version, very easy to use

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
