目錄
2. Use SAXParserFactory and SAXParser to Parse the XML
3. Sample XML (input.xml)
Key Points to Remember
Handling Nested Elements or Complex Structures
首頁 Java java教程 如何用Java用SAX解析XML?

如何用Java用SAX解析XML?

Aug 08, 2025 am 02:21 AM

創建自定義DefaultHandler並重寫startElement、endElement、characters等方法以處理解析事件;2. 使用SAXParserFactory創建SAXParser實例,並通過parse方法將XML文件與自定義處理器關聯進行解析;3. SAX解析基於事件驅動,內存佔用低,適用於大文件,但只能順序讀取且不可修改XML,需手動維護上下文狀態以處理嵌套結構,解析過程從startDocument開始到endDocument結束。

How to parse XML with SAX in Java?

Parsing XML with SAX (Simple API for XML) in Java is a fast and memory-efficient way to process large XML files, as it reads the document sequentially without loading the entire file into memory. SAX uses an event-driven model—callbacks are triggered when the parser encounters elements, attributes, text, etc.

How to parse XML with SAX in Java?

Here's how to parse XML using SAX in Java:


1. Create a Custom DefaultHandler

You need to extend org.xml.sax.helpers.DefaultHandler and override key methods to handle parsing events.

How to parse XML with SAX in Java?

Commonly overridden methods:

  • startElement() – Called when an opening tag is encountered.
  • endElement() – Called when a closing tag is encountered.
  • characters() – Called for text content between tags.
  • startDocument() / endDocument() – For document-level events.
 import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class MySAXHandler extends DefaultHandler {

    boolean isFirstName = false;
    boolean isLastName = false;
    boolean isEmail = false;

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        switch (qName.toLowerCase()) {
            case "firstname":
                isFirstName = true;
                break;
            case "lastname":
                isLastName = true;
                break;
            case "email":
                isEmail = true;
                break;
        }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        String value = new String(ch, start, length).trim();
        if (value.isEmpty()) return;

        if (isFirstName) {
            System.out.println("First Name: " value);
            isFirstName = false;
        } else if (isLastName) {
            System.out.println("Last Name: " value);
            isLastName = false;
        } else if (isEmail) {
            System.out.println("Email: " value);
            isEmail = false;
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        // Optional cleanup if needed
    }

    @Override
    public void startDocument() throws SAXException {
        System.out.println("Parsing started...");
    }

    @Override
    public void endDocument() throws SAXException {
        System.out.println("Parsing ended.");
    }
}

2. Use SAXParserFactory and SAXParser to Parse the XML

Now, use the handler with a SAXParser to process an XML file or input stream.

How to parse XML with SAX in Java?
 import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.File;

public class SAXParserExample {
    public static void main(String[] args) {
        try {
            // Create a SAXParserFactory
            SAXParserFactory factory = SAXParserFactory.newInstance();

            // Create a SAXParser
            SAXParser saxParser = factory.newSAXParser();

            // Create your handler
            MySAXHandler handler = new MySAXHandler();

            // Parse the XML file
            File inputFile = new File("input.xml");
            saxParser.parse(inputFile, handler);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

3. Sample XML (input.xml)

 <?xml version="1.0" encoding="UTF-8"?>
<employees>
    <employee id="1">
        <firstname>John</firstname>
        <lastname>Doe</lastname>
        <email>john.doe@example.com</email>
    </employee>
    <employee id="2">
        <firstname>Jane</firstname>
        <lastname>Smith</lastname>
        <email>jane.smith@example.com</email>
    </employee>
</employees>

Output:

 Parsing started...
First Name: John
Last Name: Doe
Email: john.doe@example.com
First Name: Jane
Last Name: Smith
Email: jane.smith@example.com
Parsing ended.

Key Points to Remember

  • Memory Efficient : SAX is ideal for large XML files because it doesn't keep the whole document in memory.
  • Read-Only : SAX is for reading only; you can't modify the XML.
  • Event Order Matters : You must track context manually (eg, using flags or a stack) if you need hierarchical data.
  • No Random Access : You can't jump to a specific element—you process in sequence.

Handling Nested Elements or Complex Structures

For complex XML, maintain a stack or current object state in the handler. For example, create an Employee object when startElement("employee") is called, populate it during parsing, and save it when endElement("employee") is reached.


That's the core of SAX parsing in Java. It's straightforward once you understand the event-based flow. Basically just implement the handler and let the parser do the rest.

以上是如何用Java用SAX解析XML?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

Rimworld Odyssey溫度指南和Gravtech
1 個月前 By Jack chen
Rimworld Odyssey如何釣魚
1 個月前 By Jack chen
我可以有兩個支付帳戶嗎?
1 個月前 By 下次还敢
初學者的Rimworld指南:奧德賽
1 個月前 By Jack chen
PHP變量範圍解釋了
3 週前 By 百草

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Laravel 教程
1603
29
PHP教程
1506
276
Hashmap在Java內部如何工作? Hashmap在Java內部如何工作? Jul 15, 2025 am 03:10 AM

HashMap在Java中通過哈希表實現鍵值對存儲,其核心在於快速定位數據位置。 1.首先使用鍵的hashCode()方法生成哈希值,並通過位運算轉換為數組索引;2.不同對象可能產生相同哈希值,導致衝突,此時以鍊錶形式掛載節點,JDK8後鍊錶過長(默認長度8)則轉為紅黑樹提升效率;3.使用自定義類作鍵時必須重寫equals()和hashCode()方法;4.HashMap動態擴容,當元素數超過容量乘以負載因子(默認0.75)時,擴容並重新哈希;5.HashMap非線程安全,多線程下應使用Concu

如何處理Java中的字符編碼問題? 如何處理Java中的字符編碼問題? Jul 13, 2025 am 02:46 AM

處理Java中的字符編碼問題,關鍵是在每一步都明確指定使用的編碼。 1.讀寫文本時始終指定編碼,使用InputStreamReader和OutputStreamWriter並傳入明確的字符集,避免依賴系統默認編碼。 2.在網絡邊界處理字符串時確保兩端一致,設置正確的Content-Type頭並用庫顯式指定編碼。 3.謹慎使用String.getBytes()和newString(byte[]),應始終手動指定StandardCharsets.UTF_8以避免平台差異導致的數據損壞。總之,通過在每個階段

Java中的可比較與比較器 Java中的可比較與比較器 Jul 13, 2025 am 02:31 AM

在Java中,Comparable用於類內部定義默認排序規則,Comparator用於外部靈活定義多種排序邏輯。 1.Comparable是類自身實現的接口,通過重寫compareTo()方法定義自然順序,適用於類有固定、最常用的排序方式,如String或Integer。 2.Comparator是外部定義的函數式接口,通過compare()方法實現,適合同一類需要多種排序方式、無法修改類源碼或排序邏輯經常變化的情況。兩者區別在於Comparable只能定義一種排序邏輯且需修改類本身,而Compar

如何在Java的地圖上迭代? 如何在Java的地圖上迭代? Jul 13, 2025 am 02:54 AM

遍歷Java中的Map有三種常用方法:1.使用entrySet同時獲取鍵和值,適用於大多數場景;2.使用keySet或values分別遍歷鍵或值;3.使用Java8的forEach簡化代碼結構。 entrySet返回包含所有鍵值對的Set集合,每次循環獲取Map.Entry對象,適合頻繁訪問鍵和值的情況;若只需鍵或值,可分別調用keySet()或values(),也可在遍歷鍵時通過map.get(key)獲取值;Java8中可通過Lambda表達式使用forEach((key,value)-&gt

Java中的'靜態”關鍵字是什麼? Java中的'靜態”關鍵字是什麼? Jul 13, 2025 am 02:51 AM

InJava,thestatickeywordmeansamemberbelongstotheclassitself,nottoinstances.Staticvariablesaresharedacrossallinstancesandaccessedwithoutobjectcreation,usefulforglobaltrackingorconstants.Staticmethodsoperateattheclasslevel,cannotaccessnon-staticmembers,

如何在Windows中設置Java_home環境變量 如何在Windows中設置Java_home環境變量 Jul 18, 2025 am 04:05 AM

tosetjava_homeonwindows,firstLocateThejDkinStallationPath(例如,C:\ programFiles \ java \ jdk-17),tencreateasyemystemenvironmentvaria blenamedjava_homewiththatpath.next,updateThepathvariaby byadding%java \ _home%\ bin,andverifyTheSetupusingjava-versionAndjavac-v

如何使用JDBC處理Java的交易? 如何使用JDBC處理Java的交易? Aug 02, 2025 pm 12:29 PM

要正確處理JDBC事務,必須先關閉自動提交模式,再執行多個操作,最後根據結果提交或回滾;1.調用conn.setAutoCommit(false)以開始事務;2.執行多個SQL操作,如INSERT和UPDATE;3.若所有操作成功則調用conn.commit(),若發生異常則調用conn.rollback()確保數據一致性;同時應使用try-with-resources管理資源,妥善處理異常並關閉連接,避免連接洩漏;此外建議使用連接池、設置保存點實現部分回滾,並保持事務盡可能短以提升性能。

Java虛擬線程性能基準測試 Java虛擬線程性能基準測試 Jul 21, 2025 am 03:17 AM

虚拟线程在高并发、IO密集型场景下性能优势显著,但需注意测试方法与适用场景。1.正确测试应模拟真实业务尤其是IO阻塞场景,使用JMH或Gatling等工具对比平台线程;2.吞吐量差距明显,在10万并发请求下可高出几倍至十几倍,因其更轻量、调度高效;3.测试中需避免盲目追求高并发数,适配非阻塞IO模型,并关注延迟、GC等监控指标;4.实际应用中适用于Web后端、异步任务处理及大量并发IO场景,而CPU密集型任务仍适合平台线程或ForkJoinPool。

See all articles