您好,登錄后才能下訂單哦!
java如何使用SAX解析xml?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
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<Currency> currencies = new LinkedList<Currency>(); } @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文件:
<?xml version="1.0" encoding="UTF-8" ?> <response code="200"> <date>2008-11-07</date> <title>Exchange rates for 2008-11-07</title> <rates> <currency> <code>EUR</code> <rate>1.220</rate> </currency> <currency> <code>USD</code> <rate>1.275</rate> </currency> </rates> </response>
輸出:
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
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。