package cn.jane.main;
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class AdBeanFactory extends DefaultHandler {
//定义集合
private List list = null;
//定义变量
private String Value = "";
//创建类对象
private AdBean bean = null;
//空参构造
public AdBeanFactory()
{
//初始化集合
// super();
this.list = new ArrayList();
}
//集合的访问器
public List getList()
{
return list;
}
/**
* 遇到根目录开始节点时触发s
*/
public void startDocument() throws SAXException
{
System.out.println("开始解析!");
}
/**
* 遇到元素节点时触发
*/
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
{
System.out.println("遇到元素节点时触发");
if("Listing".equals(qName))
{
//初始化bean
bean = new AdBean();
this.list.add(bean);
bean.setTitle(attributes.getValue(1));
bean.setDescription(attributes.getValue(2));
}
}
/**
* 扫描到文本时触发
*/
public void characters(char[] ch, int start, int length) throws SAXException
{
//扫描到属性保存到成员Value中
this.Value = new String(ch,start,length);
}
/**
* 遇到元素节点结束时触发
*/
public void endElement(String uri, String localName, String qName) throws SAXException
{
if(qName.equals("ClickUrl")){
bean.setLink(Value);
}
}
public void endDocument() throws SAXException
{
System.out.println("*******文档解析结束*******");
}
}
package cn.jane.main;
import java.util.List;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
public class XmlParse {
public static void main( String[] argv ){
//获取解析助手
AdBeanFactory handler = new AdBeanFactory();
//创建解析工厂
SAXParserFactory factory = SAXParserFactory.newInstance();
try
{
//获取解析器
SAXParser work = factory.newSAXParser();
//调用方法
//调用方法
work.parse("c:/ad.xml", handler);
//创建集合,接收
List list = handler.getList();
// System.out.print(handler.test);
for(int i=0,z=list.size();i AdBean ad=(AdBean)list.get(i);
System.out.println(ad.getTitle());
System.out.println(ad.getDescription());
System.out.println(ad.getLink());
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
阅读(744) | 评论(0) | 转发(0) |