SAX解析XML
一、使用SAX解析xml文件
新建一个类,继承之DefaultHandler:
示例代码如下:
package org.demo.saxxml;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class MyContentsHandler extends DefaultHandler {
String Name,Sex;
String tagName;
String xmlContent="";
@Override
//解析每个标签的时候调用的方法
public void characters(char[] ch, int start, int length)
throws SAXException {
if(tagName.equals("Name")){
Name=new String(ch,start,length);
System.out.println(Name);
}else if(tagName.equals("Sex")){
Sex=new String(ch,start,length);
}
super.characters(ch, start, length);
}
//解析xml文档结束时
@Override
public void endDocument() throws SAXException {
// TODO Auto-generated method stub
System.out.println("End...");
super.endDocument();
}
//解析xml标签结束时
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
if(localName.equals("Name")){
xmlContent+=Name+"|";
System.out.println(xmlContent);
}else if(localName.equals("Sex")){
xmlContent+=Sex+"<br>";
}
super.endElement(uri, localName, qName);
}
//解析xml文档开始时
@Override
public void startDocument() throws SAXException {
// TODO Auto-generated method stub
super.startDocument();
}
//解析xml标签开始时
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
tagName=localName;
super.startElement(uri, localName, qName, attributes);
}
public String getContent(){
return xmlContent;
}
}