XML现在用的很广,在很多情况下,数据资源都由XML进行记录。我们希望获得资源的清单,就需要对XML文件进行解析。
当然,解析的前提条件是下载XML文件,之前学习过文件的下载实现方法(http://blog.csdn.net/huim_lin/article/details/9857317),此处不再赘述。
接着,需要创建一个继承自DefaultHandler的一个类,用处是处理遇到XML标签的事件。
这个类需要Override characters、startDocument、endDocument、startElement、endElement等几个方法,同时根据需要可以写这个类的构造方法。
学习过程中,本人构造的类:
package com.example.xml; import java.util.List; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import com.example.model.Mp3Info; public class Mp3ListContentHandler extends DefaultHandler{ private List<Mp3Info> infos=null; private Mp3Info mp3Info; private String target=null;
//根据当前获取到的资源字符串设置MP3实体的属性。
@ Override public void characters( char[] ch,int start,int length ) throws SAXException { String temp=new String(ch,start,length); if(target.equals("id")){ mp3Info.setId(temp); } else if(target.equals("mp3.name")){ mp3Info.setMp3Name(temp); } else if(target.equals("mp3.size")){ mp3Info.setMp3Size(temp); } else if(target.equals("lrc.name")){ mp3Info.setLrcName(temp); } else if(target.equals("lrc.size")){ mp3Info.setLrcSize(temp); } } //当文档结束时,我们不需要额外的操作。 @ Override public void endDocument() throws SAXException { super.endDocument(); } //在一个标签结束时,如果是一个资源元素的结束符,那么我们需要将当前元素放到List中,并且注意需要将target置空! @ Override public void endElement( String uri,String localName,String qName ) throws SAXException { if(qName.equals("resouce")){ infos.add(mp3Info); } target=""; } //根据需要,传入List public Mp3ListContentHandler ( List< Mp3Info > infos ) { super(); this.infos = infos; } //在本例子中,文档的开始,我们也不需要任何处理 @ Override public void startDocument() throws SAXException { super.startDocument(); } //标签开始时,需要判断是不是一个元素的开始标志,如果是,那么实例化 @ Override public void startElement( String uri,String qName,Attributes attributes ) throws SAXException { this.target=localName; if(target.equals("resouce")){ mp3Info=new Mp3Info(); } } }
创建了这个类,那么我们就要开始解析XML文档了。
在这个例子中,学习的是SAX的解析方法。至于SAX的特征,我学得还不是很明白,望不吝赐教。
用SAX的解析步骤如下:
//strXML为下载下来了的XML文档。
private List< Mp3Info > parse( String strXML ) { List< Mp3Info > infos = new ArrayList< Mp3Info >(); SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); try { XMLReader xmlReader = saxParserFactory.newSAXParser().getXMLReader(); Mp3ListContentHandler mp3ListContentHandler = new Mp3ListContentHandler(infos); xmlReader.setContentHandler(mp3ListContentHandler); xmlReader.parse(new InputSource(new StringReader(strXML))); for ( Iterator iterator = infos.iterator(); iterator.hasNext(); ) { Mp3Info mp3Info = ( Mp3Info ) iterator.next();
//测试解析的元素 System.out.println(mp3Info); } } catch ( Exception e ) { } //infos中存储了XML的资源元素。 return infos; }
如此一来,XML中的信息就可以获取到了! (编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|