java使用SAX解析xml的程式碼實例

Y2J
發布: 2017-04-26 15:43:09
原創
1860 人瀏覽過

import java.io.File; import java.util.LinkedList; import java.util.List; 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 ParseXMLFileWithSAX extends DefaultHandler { private StringBuffer buffer = new StringBuffer(); private static String responseCode; private static String date; private static String title; private static Currency currency; private static Rates rates; public static void main(String[] args) throws Exception { DefaultHandler handler = new ParseXMLFileWithSAX(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(false); SAXParser parser = factory.newSAXParser(); parser.parse(new File("in.xml"), handler); System.out.println("Response Code:" + responseCode); System.out.println("Date:" + date); System.out.println("Title:" + title); System.out.println("Rates:"); for (Currency curr : rates.currencies) { System.out.println("\tCode:" + curr.code + " - Rate:" + curr.rate); } } private static class Currency { public String code; public String rate; } private static class Rates { public List currencies = new LinkedList(); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { buffer.setLength(0); if (qName.equals("response")) { responseCode = attributes.getValue("code"); } else if (qName.equals("date")) { date = ""; } else if (qName.equals("title")) { title = ""; } else if (qName.equals("rates")) { rates = new Rates(); } else if (qName.equals("currency")) { currency = new Currency(); } } @Override public void endElement(String uri, String localName, String qName)throws SAXException { if (qName.equals("date")) { date = buffer.toString(); } else if (qName.equals("title")) { title = buffer.toString(); } else if (qName.equals("currency")) { rates.currencies.add(currency); } else if (qName.equals("code")) { currency.code = buffer.toString(); } else if (qName.equals("rate")) { currency.rate = buffer.toString(); } } public void characters(char[] ch, int start, int length) { buffer.append(ch, start, length); } }
登入後複製

輸入xml檔:

  2008-11-07 Exchange rates for 2008-11-07   EUR 1.220   USD 1.275   
登入後複製

輸出:

Response Code:200 Date:2008-11-07 Title:Exchange rates for 2008-11-07 Rates: Code:EUR - Rate:1.0 Code:USD - Rate:1.275600
登入後複製

以上是java使用SAX解析xml的程式碼實例的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!