Solution to using sax to parse xml in java
In java, there are two ways to parse xml documents natively, namely: Dom parsing and Sax parsing
Dom parsing is powerful and can be added, deleted, modified and checked. During operation, the xml document will be treated as a document object. The method is read into the memory, so it is suitable for small documents
Sax parsing reads the content line by line and element by element from beginning to end. It is more inconvenient to modify, but it is suitable for large read-only documents
This article mainly explains Sax parsing, and the rest will be placed later
Sax uses an event-driven approach to parse documents. To put it simply, it is like watching a movie in a cinema. You can watch it from beginning to end without going back (Dom can read it back and forth)
In the process of watching a movie, every time you encounter a plot, A tear, a shoulder rub, you will mobilize your brain and nerves to receive or process this information
Similarly, during the parsing process of Sax, when the beginning and end of the document are read, the beginning and end of the element will trigger some Callback methods, you can perform corresponding event processing in these callback methods
These four methods are: startDocument(), endDocument(), startElement(), endElement
In addition, light reading It is not enough to go to the node. We also need the characters() method to carefully process the content contained in the element.
Collecting these callback methods forms a class, which is the trigger we need.
Generally, the document is read from the Main method, but the document is processed in the trigger. This is the so-called event-driven parsing method.
As shown above, in In the trigger, the document is first read, and then the elements are parsed one by one. The content of each element will be returned to the characters() method
Then the element reading is ended. After all elements are read, the document is ended. Analysis
Now we start to create the trigger class. To create this class, we first need to inherit DefaultHandler
Create SaxHandler and override the corresponding method:
import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class SaxHandler extends DefaultHandler { /* 此方法有三个参数 arg0是传回来的字符数组,其包含元素内容 arg1和arg2分别是数组的开始位置和结束位置 */ @Override public void characters(char[] arg0, int arg1, int arg2) throws SAXException { String content = new String(arg0, arg1, arg2); System.out.println(content); super.characters(arg0, arg1, arg2); } @Override public void endDocument() throws SAXException { System.out.println("\n…………结束解析文档…………"); super.endDocument(); } /* arg0是名称空间 arg1是包含名称空间的标签,如果没有名称空间,则为空 arg2是不包含名称空间的标签 */ @Override public void endElement(String arg0, String arg1, String arg2) throws SAXException { System.out.println("结束解析元素 " + arg2); super.endElement(arg0, arg1, arg2); } @Override public void startDocument() throws SAXException { System.out.println("…………开始解析文档…………\n"); super.startDocument(); } /*arg0是名称空间 arg1是包含名称空间的标签,如果没有名称空间,则为空 arg2是不包含名称空间的标签 arg3很明显是属性的集合 */ @Override public void startElement(String arg0, String arg1, String arg2, Attributes arg3) throws SAXException { System.out.println("开始解析元素 " + arg2); if (arg3 != null) { for (int i = 0; i < arg3.getLength(); i++) { // getQName()是获取属性名称, System.out.print(arg3.getQName(i) + "=\"" + arg3.getValue(i) + "\""); } } System.out.print(arg2 + ":"); super.startElement(arg0, arg1, arg2, arg3); } }
XML document:
<?xml version="1.0" encoding="UTF-8"?> <books> <book id="001"> <title>Harry Potter</title> <author>J K. Rowling</author> </book> <book id="002"> <title>Learning XML</title> <author>Erik T. Ray</author> </book> </books>
TestDemo test class:
import java.io.File; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; public class TestDemo { public static void main(String[] args) throws Exception { // 1.实例化SAXParserFactory对象 SAXParserFactory factory = SAXParserFactory.newInstance(); // 2.创建解析器 SAXParser parser = factory.newSAXParser(); // 3.获取需要解析的文档,生成解析器,最后解析文档 File f = new File("books.xml"); SaxHandler dh = new SaxHandler(); parser.parse(f, dh); } }
Output result:
…………开始解析文档………… 开始解析元素 books books: 开始解析元素 book id="001"book: 开始解析元素 title title:Harry Potter 结束解析元素 title 开始解析元素 author author:J K. Rowling 结束解析元素 author 结束解析元素 book 开始解析元素 book id="002"book: 开始解析元素 title title:Learning XML 结束解析元素 title 开始解析元素 author author:Erik T. Ray 结束解析元素 author 结束解析元素 book 结束解析元素 books …………结束解析文档…………
Although the above shows the execution process correctly, the output is very messy
For more clarity To execute this process, we can also rewrite SaxHandler to restore the original xml document
Rewritten SaxHandler class:
import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class SaxHandler extends DefaultHandler { @Override public void characters(char[] arg0, int arg1, int arg2) throws SAXException { System.out.print(new String(arg0, arg1, arg2)); super.characters(arg0, arg1, arg2); } @Override public void endDocument() throws SAXException { System.out.println("\n结束解析"); super.endDocument(); } @Override public void endElement(String arg0, String arg1, String arg2) throws SAXException { System.out.print("</"); System.out.print(arg2); System.out.print(">"); super.endElement(arg0, arg1, arg2); } @Override public void startDocument() throws SAXException { System.out.println("开始解析"); String s = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; System.out.println(s); super.startDocument(); } @Override public void startElement(String arg0, String arg1, String arg2, Attributes arg3) throws SAXException { System.out.print("<"); System.out.print(arg2); if (arg3 != null) { for (int i = 0; i < arg3.getLength(); i++) { System.out.print(" " + arg3.getQName(i) + "=\"" + arg3.getValue(i) + "\""); } } System.out.print(">"); super.startElement(arg0, arg1, arg2, arg3); } }
More solutions to using sax to parse xml in java For method-related articles, please pay attention to the PHP Chinese website!

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

AI Hentai Generator
Generate AI Hentai for free.

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



The speed of mobile XML to PDF depends on the following factors: the complexity of XML structure. Mobile hardware configuration conversion method (library, algorithm) code quality optimization methods (select efficient libraries, optimize algorithms, cache data, and utilize multi-threading). Overall, there is no absolute answer and it needs to be optimized according to the specific situation.

It is impossible to complete XML to PDF conversion directly on your phone with a single application. It is necessary to use cloud services, which can be achieved through two steps: 1. Convert XML to PDF in the cloud, 2. Access or download the converted PDF file on the mobile phone.

It is not easy to convert XML to PDF directly on your phone, but it can be achieved with the help of cloud services. It is recommended to use a lightweight mobile app to upload XML files and receive generated PDFs, and convert them with cloud APIs. Cloud APIs use serverless computing services, and choosing the right platform is crucial. Complexity, error handling, security, and optimization strategies need to be considered when handling XML parsing and PDF generation. The entire process requires the front-end app and the back-end API to work together, and it requires some understanding of a variety of technologies.

To open a web.xml file, you can use the following methods: Use a text editor (such as Notepad or TextEdit) to edit commands using an integrated development environment (such as Eclipse or NetBeans) (Windows: notepad web.xml; Mac/Linux: open -a TextEdit web.xml)

XML formatting tools can type code according to rules to improve readability and understanding. When selecting a tool, pay attention to customization capabilities, handling of special circumstances, performance and ease of use. Commonly used tool types include online tools, IDE plug-ins, and command-line tools.

An application that converts XML directly to PDF cannot be found because they are two fundamentally different formats. XML is used to store data, while PDF is used to display documents. To complete the transformation, you can use programming languages and libraries such as Python and ReportLab to parse XML data and generate PDF documents.

Use most text editors to open XML files; if you need a more intuitive tree display, you can use an XML editor, such as Oxygen XML Editor or XMLSpy; if you process XML data in a program, you need to use a programming language (such as Python) and XML libraries (such as xml.etree.ElementTree) to parse.

XML Online Format Tools automatically organizes messy XML code into easy-to-read and maintain formats. By parsing the syntax tree of XML and applying formatting rules, these tools optimize the structure of the code, enhancing its maintainability and teamwork efficiency.
