使用SaxParser和完整代碼進行XML解析

SAX解析器使用回調函數(org.xml.sax.helpers.DefaultHandler)通知客戶端XML文檔結構。 您應該擴展DefaultHandler并重寫一些方法來實現xml解析。

覆蓋的方法是

  • startDocument()和endDocument()–在XML文檔的開頭和結尾處調用的方法。
  • startElement()和endElement()–在文檔元素的開頭和結尾處調用的方法。
  • character()–以XML文檔元素的開始和結束標記之間的文本內容調用的方法。

下面的示例演示使用DefaultHandler解析和XML文檔。 它執行xml到模型類的映射并生成對象列表。

XML文檔樣本:

<?xml version="1.0" encoding="UTF-8"?>
<catalog><book id="001" lang="ENG"><isbn>23-34-42-3</isbn><regDate>1990-05-24</regDate><title>Operating Systems</title><publisher country="USA">Pearson</publisher><price>400</price><authors><author>Ganesh Tiwari</author></authors></book><book id="002"><isbn>24-300-042-3</isbn><regDate>1995-05-12</regDate><title>Distributed Systems</title><publisher country="Nepal">Ekata</publisher><price>500</price><authors><author>Mahesh Poudel</author><author>Bikram Adhikari</author><author>Ramesh Poudel</author></authors></book>
</catalog>

Book對象的模型類,用于將xml映射到對象

/*** Book class stores book information, after parsing the xml* @author Ganesh Tiwari*/
public class Book {String lang;String title;String id;String isbn;Date regDate;String publisher;int price;List<String> authors;public Book(){authors=new ArrayList<String>();}//getters and setters
}

XML解析(Sax)的Java代碼:

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class MySaxParser extends DefaultHandler {List<Book> bookL;String bookXmlFileName;String tmpValue;Book bookTmp;SimpleDateFormat sdf= new SimpleDateFormat("yy-MM-dd");public MySaxParser(String bookXmlFileName) {this.bookXmlFileName = bookXmlFileName;bookL = new ArrayList<Book>();parseDocument();printDatas();}private void parseDocument() {// parseSAXParserFactory factory = SAXParserFactory.newInstance();try {SAXParser parser = factory.newSAXParser();parser.parse(bookXmlFileName, this);} catch (ParserConfigurationException e) {System.out.println("ParserConfig error");} catch (SAXException e) {System.out.println("SAXException : xml not well formed");} catch (IOException e) {System.out.println("IO error");}}private void printDatas() {// System.out.println(bookL.size());for (Book tmpB : bookL) {System.out.println(tmpB.toString());}}@Overridepublic void startElement(String s, String s1, String elementName, Attributes attributes) throws SAXException {// if current element is book , create new book// clear tmpValue on start of elementif (elementName.equalsIgnoreCase("book")) {bookTmp = new Book();bookTmp.setId(attributes.getValue("id"));bookTmp.setLang(attributes.getValue("lang"));}// if current element is publisherif (elementName.equalsIgnoreCase("publisher")) {bookTmp.setPublisher(attributes.getValue("country"));}}@Overridepublic void endElement(String s, String s1, String element) throws SAXException {// if end of book element add to listif (element.equals("book")) {bookL.add(bookTmp);}if (element.equalsIgnoreCase("isbn")) {bookTmp.setIsbn(tmpValue);}if (element.equalsIgnoreCase("title")) {bookTmp.setTitle(tmpValue);}if(element.equalsIgnoreCase("author")){bookTmp.getAuthors().add(tmpValue);}if(element.equalsIgnoreCase("price")){bookTmp.setPrice(Integer.parseInt(tmpValue));}if(element.equalsIgnoreCase("regDate")){try {bookTmp.setRegDate(sdf.parse(tmpValue));} catch (ParseException e) {System.out.println("date parsing error");}}}@Overridepublic void characters(char[] ac, int i, int j) throws SAXException {tmpValue = new String(ac, i, j);}public static void main(String[] args) {new MySaxParser("catalog.xml");}
}

解析輸出:

Book [lang=ENG, title=Operating Systems, id=001, isbn=23-34-42-3, regDate=Thu May 24 00:00:00 NPT 1990, publisher=USA, price=400, authors=[Ganesh Tiwari]]
Book [lang=null, title=Distributed Systems, id=002, isbn=24-300-042-3, regDate=Fri May 12 00:00:00 NPT 1995, publisher=Nepal, price=500, authors=[Mahesh Poudel, Bikram Adhikari, Ramesh Poudel]]

參考:在GT's Blog上, 使用我們的JCG合作伙伴 Ganesh Tiwari 提供的完整代碼 , 使用SaxParser進行XML解析 。


翻譯自: https://www.javacodegeeks.com/2012/01/xml-parsing-using-saxparser-with.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/373368.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/373368.shtml
英文地址,請注明出處:http://en.pswp.cn/news/373368.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

mysql添加字符串日期時間_mysql學習筆記--- 字符串函數、日期時間函數

一、常見字符串函數&#xff1a;1、CHAR_LENGTH 獲取長度(字符為單位)2、FORMAT 格式化3、INSERT 替換的方式插入4、INSTR 獲取位置5、LEFT/RIGHT 取左、取右6、LENGTH 獲取長度(字節為單位)7、LTRIM/RTRIM/TRIM 去空格(左/右/自定義)8、STRCMP 字符串比較9、CONCAT 字…

Android異常和工具使用筆記

Android異常和工具使用筆記 1、r文件找不到去你的工程目錄下&#xff0c;手動的把gen刪掉&#xff0c;然后去project中刷新一下&#xff0c;在編譯看看。以前遇到過類似的問題&#xff0c;實在不行就把你的eclispe,adt升級到最新的版本吧 抓住那么一點點線索&#xff0c;就要去…

ADO.NET 核心對象簡介

ADO.NET ADO.NET是.NET中一組用于和數據源進行交互的面向對象類庫&#xff0c;提供了數據訪問的高層接口。 ADO.NET類庫在System.Data命名空間內&#xff0c;根據我們訪問的不同數據庫選擇命名空間&#xff0c;System.Data.SqlClient。 ADO.NET類最重要的優點是支持數據庫以斷開…

MongoDB與Spring Data項目

如今&#xff0c;我們所有人都在觀察NoSql解決方案的爆炸式增長。 我已經習慣了RDBMS&#xff0c;但這些并不是您可能遇到的所有挑戰的解決方案。 根據最近的經驗&#xff0c;我有機會使用MongoDB –文檔數據庫。 在本文中&#xff0c;我打算介紹將MongoDB與Spring Data項目一起…

java轉換為字符串_java – 如何從int轉換為字符串?

正常方式是Integer.toString(i)或String.valueOf(i)。串聯將工作&#xff0c;但它是非常規的&#xff0c;可能是一個難聞的氣味&#xff0c;因為它暗示作者不知道上述兩種方法(他們不知道什么&#xff1f;)。Java在使用字符串(見the documentation)時對操作符提供了特殊的支持&…

簡學LINGO(三)——實例篇

1. 裝配線平衡模型 一個裝配線含有一系列的工作站。在終于產品的加工過程中每一個工作站運行一種或者是幾種特定的任務。裝配線周期是指全部工作站完畢分配給他們各自任務所花費時間的最大值。平衡裝配線的目標是為每一個工作站分配加工任務。盡可能使每一個工作站運行同樣數量…

Hibernate緩存級別教程

開始使用Hibernate的人們常見的問題之一就是性能&#xff0c;如果您沒有太多的Hibernate經驗&#xff0c;您會發現應用程序變慢的速度。 如果啟用sql跟蹤&#xff0c;您將看到有多少查詢被發送到數據庫&#xff0c;而這些查詢幾乎不需要Hibernate知識就可以避免。 在當前文章中…

java方法執行的時間_計算Java中任意一個方法的執行時間的工具類

1 packagealgorithm.study.utils;23 importjava.lang.reflect.Method;45 /**6 * This class is getting a method execute time and provide some other functions.7 *8 *authorygh 2017年2月24日9 */10 public classMethodExecuteTimeUtils {1112 /**13 * Get a method execut…

如何在 IIS 中設置 HTTPS 服務

Windows Server2008、IIS7啟用CA認證及證書制作完整過程 這篇文章介紹了如何安裝證書申請工具&#xff1b; 如何在iis創建證書申請&#xff1b; 如何使用iis申請證書生成的txt文件&#xff0c;在工具中開始申請證書&#xff1b; 如何導出證書&#xff1b; 以及在網站中開始使用…

Android之衛星菜單的實現

衛星菜單是現在一個非常受歡迎的“控件”&#xff0c;很多Android程序員都趨之若鶩&#xff0c;預覽如下圖。傳統的衛星菜單是用Animation實現的&#xff0c;需要大量的代碼&#xff0c;而且算法極多&#xff0c;一不小心就要通宵Debug。本帖貼出用屬性動畫Animator來實現衛星菜…

Java中的WADL:溫和的介紹

WADL&#xff08; Web應用程序描述語言 &#xff09;對REST而言&#xff0c;WSDL對SOAP而言。 這種語言的僅僅存在引起了很多爭議&#xff08;請參閱&#xff1a; 我們需要WADL嗎&#xff1f; 或者 需要 WADL還是不需要WADL &#xff09;。 我可以想到使用WADL的一些合法用例&a…

類成員函數模板特化

//類成員函數模板特化 #include <stdio.h> class A{ public:template <class T>void Print(){printf("A template\n");} };template<> void A::Print<int>(){printf("int\n"); }int main(){A a;a.Print<double>();a.Print&l…

為云量身定制您的服務

相信大家都聽說過Amazon的AWS。作為業內最為成熟的云服務提供商&#xff0c;其運行規模&#xff0c;穩定性&#xff0c;安全性都已經經過了市場的考驗。時至今日&#xff0c;越來越多的應用被部署在了AWS之上。這其中不乏Zynga及Netflix這樣著名的服務。 然而這一切并沒有停滯不…

在Vaadin和JSF之間選擇

隨著最新版本的Primefaces 3.0的發布&#xff0c;JSF終于達到了前所未有的成熟度和實用性&#xff0c;使其與其他流行的Rich Internet Applications&#xff08;RIA&#xff09;選項如Google Web Toolkit&#xff08;GWT&#xff09;&#xff0c;ExtJS&#xff0c;Vaadin&#…

20145202馬超《信息安全系統設計基礎》實驗二總結

[實驗二]&#xff08;http://www.cnblogs.com/nizaikanwoma/p/6131778.html&#xff09; 轉載于:https://www.cnblogs.com/tuolemi/p/6131987.html

java 連接ldap_ldap java 連接demo

public class LDAPHelper {/*** LDAP可以理解為一個多級目錄&#xff0c;這里&#xff0c;表示要連接到那個具體的目錄*/private final String baseDn "ouPeople,dcchangyeyi,dccom";private LdapContext ctx null;private final Control[] connCtls null;private…

flask開發restful api系列(1)

在此之前&#xff0c;向大家說明的是&#xff0c;我們整個框架用的是flask sqlalchemy redis。如果沒有開發過web&#xff0c;還是先去學習一下&#xff0c;這邊只是介紹如果從開發web轉換到開發移動端。如果flask還不是很熟悉&#xff0c;我建議先到這個網站簡單學習一下&am…

Apache Commons Lang StringUtils

因此&#xff0c;認為最好談論我喜歡的另一個Java庫。 它已經存在了一段時間&#xff0c;也許不是最令人興奮的庫&#xff0c;但是它非常有用。 我可能每天都使用它。 org.apache.commons.lang.StringUtils StringUtils是Apache Commons Lang&#xff08; http://commons.apac…

JEE7:展望新時代

計劃于2012年下半年發布的Java EE 7預計的JSR都已啟動并正在運行。 Java EE 7發行版是日期驅動的&#xff0c;它將反映該行業遷移到云中時不斷變化的需求&#xff1a;任何未準備就緒的內容將推遲到Java EE 8中使用 。 這是Java EE 7平臺中不同規范的關鍵功能的更新和摘要。 1。…

Cocos2d-JS項目之UI界面的優化

測試環境&#xff1a; iphone4、iOS6.1.2、chrome 37.2062.60&#xff0c;Cocos2d-js 3.6 之前寫了不少&#xff0c;實際項目也按這個去優化了&#xff0c;也有效果&#xff0c;但到最后才發現&#xff0c;尼瑪&#xff0c;之前都搞錯了&#xff0c;之所以有效果是歪打正著。。…