java解析xml文件方法
对xml数据的解析,在网络程序中经常会用到。在这里介绍SAX方法来处理xml文档。SAX是基于事件的,由回调机制实现。
在这里需要解析的文件mp3.xml
<?xml version="1.0" encoding="ISO-8859-1"?><resources><resource><id>0001</id><mp3.name>Fayray-I Wanna Be Free.mp3</mp3.name><mp3.size>4867102</mp3.size><lrc.name>Fayray-I Wanna Be Free.lrc</lrc.name><lrc.size>1453</lrc.size></resource><resource><id>0002</id><mp3.name>teens-fire_fly.mp3</mp3.name><mp3.size>2999636</mp3.size><lrc.name>teens-fire_fly.lrc</lrc.name><lrc.size>1986</lrc.size></resource></resources>
import java.io.Serializable;public class Mp3Info implements Serializable{private static final long serialVersionUID = 1L;private String id;private String mp3Name;private String mp3Size;private String lrcName;private String lrcSize;public Mp3Info() {super();}public Mp3Info(String id, String mp3Name, String mp3Size, String lrcName,String lrcSize) {super();this.id = id;this.mp3Name = mp3Name;this.mp3Size = mp3Size;this.lrcName = lrcName;this.lrcSize = lrcSize;}public String getId() {return id;}public void setId(String id) {this.id = id;}public String getMp3Name() {return mp3Name;}public void setMp3Name(String mp3Name) {this.mp3Name = mp3Name;}public String getMp3Size() {return mp3Size;}public void setMp3Size(String mp3Size) {this.mp3Size = mp3Size;}public String getLrcName() {return lrcName;}public void setLrcName(String lrcName) {this.lrcName = lrcName;}public String getLrcSize() {return lrcSize;}public void setLrcSize(String lrcSize) {this.lrcSize = lrcSize;}@Overridepublic String toString() {return "Mp3Info [id=" + id + ", mp3Name=" + mp3Name + ", mp3Size="+ mp3Size + ", lrcName=" + lrcName + ", lrcSize=" + lrcSize+ "]";}}
private List<Mp3Info> parse(String xmlStr){List<Mp3Info> infos = new ArrayList<Mp3Info>();SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();SAXParser parser = null;//saxParserFactory.setNamespaceAware(true);//saxParserFactory.setValidating(true);try {parser = saxParserFactory.newSAXParser();//用于封装JDK提供的解析器 } catch(SAXException e) { e.printStackTrace(System.err); System.exit(1); } catch(ParserConfigurationException e) { e.printStackTrace(System.err); System.exit(1); } System.out.println("\nStarting parse ..."); Mp3ListContentHandler mp3ListContentHandler = new Mp3ListContentHandler(infos); try{parser.parse(new InputSource(new StringReader(xmlStr)), mp3ListContentHandler);for(Iterator<Mp3Info> iterator = infos.iterator(); iterator.hasNext();){Mp3Info mp3Info = (Mp3Info)iterator.next();System.out.println(mp3Info);} }catch(IOException e) { //System.out.println("--------------->2"); e.printStackTrace(System.err); }catch(SAXException e) { //System.out.println("--------------->3"); e.printStackTrace(System.err); }return infos;}
import java.util.List;import jia.model.Mp3Info;import org.xml.sax.Attributes;import org.xml.sax.SAXException;import org.xml.sax.helpers.DefaultHandler;public class Mp3ListContentHandler extends DefaultHandler{private List<Mp3Info> infos = null;private Mp3Info mp3Info = null;private String tagName = null;//Constructorpublic Mp3ListContentHandler(List<Mp3Info> infos) {this.infos = infos;}public List<Mp3Info> getInfos() {return infos;}public void setInfos(List<Mp3Info> infos) {this.infos = infos;}@Overridepublic void characters(char[] ch, int start, int length)throws SAXException {String temp = new String(ch, start, length);//System.out.println("Characters: " + temp);if (tagName.equals("id")) {mp3Info.setId(temp);} else if (tagName.equals("mp3.name")) {mp3Info.setMp3Name(temp);} else if (tagName.equals("mp3.size")) {mp3Info.setMp3Size(temp);} else if (tagName.equals("lrc.name")) {mp3Info.setLrcName(temp);} else if (tagName.equals("lrc.size")) {mp3Info.setLrcSize(temp);}}@Overridepublic void endDocument() throws SAXException {//System.out.println("End document");}@Overridepublic void endElement(String uri, String localName, String qName)throws SAXException {if (qName.equals("resource")) {infos.add(mp3Info);}tagName = "";//System.out.println("End element: local name: " + localName + " qname: " // + qName + " uri: "+uri);}@Overridepublic void startDocument() throws SAXException {System.out.println("Start document:");}@Overridepublic void startElement(String uri, String localName, String qName,Attributes attr) throws SAXException {//System.out.println("Start element: local name: " + localName + " qname: " // x); pre.writeAttribute('title', 'java解析xml文件方法'); }); $$('#main .blog_comment > div').each(function(comment){// comment var post_id = comment.id.substr(2); $$("#"+comment.id+" pre[name=code]").each(function(pre, index){ var location = window.location; source_url = location.protocol + "//" + location.host + location.pathname + location.search; source_url += "#" + comment.id; pre.writeAttribute('codeable_id', post_id); pre.writeAttribute('codeable_type', "BlogComment"); pre.writeAttribute('source_url', source_url); pre.writeAttribute('pre_index', index); pre.writeAttribute('title', 'java解析xml文件方法'); }); }); code_favorites_init(); fix_image_size($$('div.blog_content img'), 700); function quote_comment(id) { new Ajax.Request('/editor/quote', { parameters: {'id':id, 'type':'BlogComment'}, onSuccess:function(response){editor.bbcode_editor.textarea.insertAfterSelection(response.responseText); Element.scrollTo(editor.bbcode_editor.textarea.element);} }); } new WeiboShare({share_buttons: $('share_weibo'), img_scope: $('blog_content')});