§ 注意:(XML文件中有特殊字符例如“&”的时候,解析不出来,“&”替换为“&”可以解析出来)
§ XML文件:
<?xml version="1.0" encoding="utf-8"?>
<playinfos>
<playinfo id="1">
<name>CCTV1综合</name><address>http://live.gslb.letv.com/gslb?stream_id=cctv1&amptag=live&ampext=m3u8&ampsign=live_ipad</address>
</playinfo>
<playinfo id="2">
<name>CCTV2财经 </name>
<address>http://live.gslb.letv.com/gslb?stream_id=cctv2&amptag=live&ampext=m3u8&ampsign=live_ipad</address>
</playinfo>
<playinfo id="3">
<name>CCTV-3综艺</name>
<address>http://live.gslb.letv.com/gslb?stream_id=cctv3&amptag=live&ampext=m3u8&ampsign=live_ipad</address>
</playinfo>
<playinfo id="4">
<name>CCTV-4亚洲 </name>
<address>http://live.gslb.letv.com/gslb?stream_id=cctv4&amptag=live&ampext=m3u8&ampsign=live_ipad</address>
</playinfo>
</playinfos>
§ 定义handler:
public class PlayerAddressHandler extends DefaultHandler {
private ArrayList<PlayInfo> playInfos;
private PlayInfo playInfo;
private String content;
public ArrayList<PlayInfo> getPlayInfos() {
return playInfos;
}
@Override
public void startDocument() throws SAXException {
super.startDocument();
playInfos = new ArrayList<PlayInfo>();
System.out.println("----------Start Parse Document----------" );
}
@Override
public void endDocument() throws SAXException {
System.out.println("----------End Parse Document----------" );
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
// 获得标签中的文本
content = new String(ch, start, length);
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
// 打印出localname和qName
System.out.println("LocalName->" + localName);
System.out.println("QName->" + qName);
if ("playinfo".equals(localName)) {
playInfo = new PlayInfo();
playInfo.setId(Integer.parseInt(attributes.getValue("id")));
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
super.endElement(uri, localName, qName);
if ("name".equals(localName)) {
playInfo.setName(content);
} else if ("address".equals(localName)) {
playInfo.setAddress(content);
} else if ("playinfo".equals(localName)) {
playInfos.add(playInfo);
}
}
}
§ 获取数据代码:
SAXParserFactory factory = SAXParserFactory.newInstance();
// 通过工厂对象得到一个解析器对象
SAXParser parser;
try {
parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
// 通过parser得到XMLReader对象
// 为reader对象注册事件处理接口
PlayerAddressHandler handler = new PlayerAddressHandler();
reader.setContentHandler(handler);
// 解析指定XML字符串对象
reader.parse(new InputSource(PlayAddressActivity.class.getClassLoader().getResourceAsStream("address/address_hanguo.xml")));
playinfos= handler.getPlayInfos();