search
HomeBackend DevelopmentXML/RSS TutorialSample code for reading XML files using SAX method

XMLFile

<?xml version="1.0" encoding="UTF-8"?>	

	<bookstore>
		<book id="1">
			<name>冰与火之歌</name>
			<author>乔治马丁</author>
			<year>2014</year>
			<price>89</price>
		</book>
		<book id="2">
			<name>安徒生童话</name>
			<year>2004</year>
			<price>77</price>		
			<language>English</language>
		</book>
	</bookstore>

handler.java class

package xmltes;

import javax.xml.stream.events.Characters;
import javax.xml.stream.events.StartElement;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;


public class handler extends DefaultHandler{
    private static int bookNum = 0;
    //遍历xml文件的开始标签
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        // 调用DefaultHandler父类的startElement方法
        super.startElement(uri, localName, qName, attributes);
        
        //判断是不是有属性的标签/如book
        if(qName.equals("book")){
            bookNum++;
            System.out.println("====================开始遍历第"+bookNum+"书的内容================");
            //开始解析book元素
            //已知book元素下属性的名称,可以根据名称判断
           /* String value = attributes.getValue("id");
            System.out.println("book的属性值是" + value);*/
            //如果不知道数的属性名称
            int num = attributes.getLength();
            
            for(int i=0;i<num;i++){
                System.out.println("书的第" + (i+1) + "个属性名是:"+attributes.getQName(i)+"===属性值是:" + attributes.getValue(i));
            }
            
        }else if(!qName.equals("book") && !qName.equals("bookstore") ){
            System.out.println("节点名是:" + qName);
        }
        
        
        
        
    }
    //遍历xml文件的结束标签
    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        // TODO Auto-generated method stub
        super.endElement(uri, localName, qName);
        //判断这本书是否遍历结束
        if(qName.equals("book")){
            System.out.println("====================结束遍历第"+bookNum+"书的内容================");
        }
    }
    
    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        // TODO Auto-generated method stub
        super.characters(ch, start, length);
        String value = new String(ch, start, length);
        if(!value.trim().equals("")){
            System.out.println(value);
        }
    }
    
    //用来标识解析开始
    @Override
    public void startDocument() throws SAXException {
        // TODO Auto-generated method stub
        super.startDocument();
//        System.out.println("进入标识解析开始方法");
    }
    
    //用来标识解析结束
    @Override
    public void endDocument() throws SAXException {
        // TODO Auto-generated method stub
        super.endDocument();
//        System.out.println("进入标识解析结束方法");
    }
    
}

Test class

package xmltes;

import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;


public class SAXTest {
    public static void main(String[] args) {
        try {
            //获取一个SAXParserFactory的实例
            SAXParserFactory factory = SAXParserFactory.newInstance();
            //通过factory获取SAXParser实例
            SAXParser parser = factory.newSAXParser();
            //创建一个SAXParserHandler对象
            handler handler = new handler();
            parser.parse("001.xml", handler);
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

The above is the detailed content of Sample code for reading XML files using SAX method. For more information, please follow other related articles on the PHP Chinese website!

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
Mastering Well-Formed XML: Best Practices for Data ExchangeMastering Well-Formed XML: Best Practices for Data ExchangeMay 14, 2025 am 12:05 AM

Well-formedXMLiscrucialfordataexchangebecauseitensurescorrectparsingandunderstandingacrosssystems.1)Startwithadeclarationlike.2)Ensureeveryopeningtaghasaclosingtagandelementsareproperlynested.3)Useattributescorrectly,enclosingvaluesinquotesandavoidin

XML: Is it still used?XML: Is it still used?May 13, 2025 pm 03:13 PM

XMLisstillusedduetoitsstructurednature,humanreadability,andwidespreadadoptioninenterpriseenvironments.1)Itfacilitatesdataexchangeinsectorslikefinance(SWIFT)andhealthcare(HL7).2)Itshuman-readableformataidsinmanualdatainspectionandediting.3)XMLisusedin

The Anatomy of an RSS Document: Structure and ElementsThe Anatomy of an RSS Document: Structure and ElementsMay 10, 2025 am 12:23 AM

The structure of an RSS document includes three main elements: 1.: root element, defining the RSS version; 2.: Containing channel information, such as title, link, and description; 3.: Representing specific content entries, including title, link, description, etc.

Understanding RSS Documents: A Comprehensive GuideUnderstanding RSS Documents: A Comprehensive GuideMay 09, 2025 am 12:15 AM

RSS documents are a simple subscription mechanism to publish content updates through XML files. 1. The RSS document structure consists of and elements and contains multiple elements. 2. Use RSS readers to subscribe to the channel and extract information by parsing XML. 3. Advanced usage includes filtering and sorting using the feedparser library. 4. Common errors include XML parsing and encoding issues. XML format and encoding need to be verified during debugging. 5. Performance optimization suggestions include cache RSS documents and asynchronous parsing.

RSS, XML and the Modern Web: A Content Syndication Deep DiveRSS, XML and the Modern Web: A Content Syndication Deep DiveMay 08, 2025 am 12:14 AM

RSS and XML are still important in the modern web. 1.RSS is used to publish and distribute content, and users can subscribe and get updates through the RSS reader. 2. XML is a markup language and supports data storage and exchange, and RSS files are based on XML.

Beyond Basics: Advanced RSS Features Enabled by XMLBeyond Basics: Advanced RSS Features Enabled by XMLMay 07, 2025 am 12:12 AM

RSS enables multimedia content embedding, conditional subscription, and performance and security optimization. 1) Embed multimedia content such as audio and video through tags. 2) Use XML namespace to implement conditional subscriptions, allowing subscribers to filter content based on specific conditions. 3) Optimize the performance and security of RSSFeed through CDATA section and XMLSchema to ensure stability and compliance with standards.

Decoding RSS: An XML Primer for Web DevelopersDecoding RSS: An XML Primer for Web DevelopersMay 06, 2025 am 12:05 AM

RSS is an XML-based format used to publish frequently updated data. As a web developer, understanding RSS can improve content aggregation and automation update capabilities. By learning RSS structure, parsing and generation methods, you will be able to handle RSSfeeds confidently and optimize your web development skills.

JSON vs. XML: Why RSS Chose XMLJSON vs. XML: Why RSS Chose XMLMay 05, 2025 am 12:01 AM

RSS chose XML instead of JSON because: 1) XML's structure and verification capabilities are better than JSON, which is suitable for the needs of RSS complex data structures; 2) XML was supported extensively at that time; 3) Early versions of RSS were based on XML and have become a standard.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.