您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

java使用SAX解析xml的代码实例

2025/11/17 1:49:44发布24次查看
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
以上就是java使用sax解析xml的代码实例的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product